@strapi/cloud-cli 4.25.1 → 4.25.3

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/dist/index.js CHANGED
@@ -41,10 +41,11 @@ const jwt = require("jsonwebtoken");
41
41
  const stringify = require("fast-safe-stringify");
42
42
  const ora = require("ora");
43
43
  const cliProgress = require("cli-progress");
44
- const EventSource = require("eventsource");
45
44
  const fs$1 = require("fs/promises");
46
45
  const pkgUp = require("pkg-up");
47
46
  const yup = require("yup");
47
+ const _ = require("lodash");
48
+ const EventSource = require("eventsource");
48
49
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
49
50
  function _interopNamespace(e) {
50
51
  if (e && e.__esModule)
@@ -80,10 +81,11 @@ const jwt__default = /* @__PURE__ */ _interopDefault(jwt);
80
81
  const stringify__default = /* @__PURE__ */ _interopDefault(stringify);
81
82
  const ora__default = /* @__PURE__ */ _interopDefault(ora);
82
83
  const cliProgress__namespace = /* @__PURE__ */ _interopNamespace(cliProgress);
83
- const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
84
84
  const fs__default = /* @__PURE__ */ _interopDefault(fs$1);
85
85
  const pkgUp__default = /* @__PURE__ */ _interopDefault(pkgUp);
86
86
  const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
87
+ const ___default = /* @__PURE__ */ _interopDefault(_);
88
+ const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
87
89
  const apiConfig = {
88
90
  apiBaseUrl: utils.env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
89
91
  dashboardBaseUrl: utils.env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
@@ -194,7 +196,7 @@ async function saveLocalConfig(data) {
194
196
  await fse__default.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
195
197
  }
196
198
  const name = "@strapi/cloud-cli";
197
- const version = "4.25.0";
199
+ const version = "4.25.2";
198
200
  const description = "Commands to interact with the Strapi Cloud";
199
201
  const keywords = [
200
202
  "strapi",
@@ -235,10 +237,11 @@ const scripts = {
235
237
  build: "pack-up build",
236
238
  clean: "run -T rimraf ./dist",
237
239
  lint: "run -T eslint .",
240
+ "test:unit": "run -T jest",
238
241
  watch: "pack-up watch"
239
242
  };
240
243
  const dependencies = {
241
- "@strapi/utils": "4.25.0",
244
+ "@strapi/utils": "4.25.2",
242
245
  axios: "1.6.0",
243
246
  chalk: "4.1.2",
244
247
  "cli-progress": "3.12.0",
@@ -263,8 +266,8 @@ const devDependencies = {
263
266
  "@types/cli-progress": "3.11.5",
264
267
  "@types/eventsource": "1.1.15",
265
268
  "@types/lodash": "^4.14.191",
266
- "eslint-config-custom": "4.25.0",
267
- tsconfig: "4.25.0"
269
+ "eslint-config-custom": "4.25.2",
270
+ tsconfig: "4.25.2"
268
271
  };
269
272
  const engines = {
270
273
  node: ">=18.0.0 <=20.x.x",
@@ -293,7 +296,7 @@ const packageJson = {
293
296
  engines
294
297
  };
295
298
  const VERSION = "v1";
296
- async function cloudApiFactory(token) {
299
+ async function cloudApiFactory({ logger }, token) {
297
300
  const localConfig = await getLocalConfig();
298
301
  const customHeaders = {
299
302
  "x-device-id": localConfig.deviceId,
@@ -346,8 +349,19 @@ async function cloudApiFactory(token) {
346
349
  getUserInfo() {
347
350
  return axiosCloudAPI.get("/user");
348
351
  },
349
- config() {
350
- return axiosCloudAPI.get("/config");
352
+ async config() {
353
+ try {
354
+ const response = await axiosCloudAPI.get("/config");
355
+ if (response.status !== 200) {
356
+ throw new Error("Error fetching cloud CLI config from the server.");
357
+ }
358
+ return response;
359
+ } catch (error) {
360
+ logger.debug(
361
+ "🥲 Oops! Couldn't retrieve the cloud CLI config from the server. Please try again."
362
+ );
363
+ throw error;
364
+ }
351
365
  },
352
366
  listProjects() {
353
367
  return axiosCloudAPI.get("/projects");
@@ -386,7 +400,7 @@ const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defi
386
400
  }, Symbol.toStringTag, { value: "Module" }));
387
401
  let cliConfig;
388
402
  async function tokenServiceFactory({ logger }) {
389
- const cloudApiService = await cloudApiFactory();
403
+ const cloudApiService = await cloudApiFactory({ logger });
390
404
  async function saveToken(str) {
391
405
  const appConfig = await getLocalConfig();
392
406
  if (!appConfig) {
@@ -435,14 +449,17 @@ async function tokenServiceFactory({ logger }) {
435
449
  "There seems to be a problem with your login information. Please try logging in again."
436
450
  );
437
451
  }
452
+ return Promise.reject(new Error("Invalid token"));
438
453
  }
439
454
  return new Promise((resolve, reject) => {
440
455
  jwt__default.default.verify(idToken, getKey, (err) => {
441
456
  if (err) {
442
457
  reject(err);
443
- } else {
444
- resolve();
445
458
  }
459
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1e3)) {
460
+ reject(new Error("Token is expired"));
461
+ }
462
+ resolve();
446
463
  });
447
464
  });
448
465
  }
@@ -476,15 +493,15 @@ async function tokenServiceFactory({ logger }) {
476
493
  throw e;
477
494
  }
478
495
  }
479
- async function getValidToken() {
480
- const token = await retrieveToken();
481
- if (!token) {
482
- logger.log("No token found. Please login first.");
483
- return null;
484
- }
485
- if (!await isTokenValid(token)) {
486
- logger.log("Unable to proceed: Token is expired or not valid. Please login again.");
487
- return null;
496
+ async function getValidToken(ctx, loginAction2) {
497
+ let token = await retrieveToken();
498
+ while (!token || !await isTokenValid(token)) {
499
+ logger.log(
500
+ token ? "Oops! Your token seems expired or invalid. Please login again." : "We couldn't find a valid token. You need to be logged in to use this feature."
501
+ );
502
+ if (!await loginAction2(ctx))
503
+ return null;
504
+ token = await retrieveToken();
488
505
  }
489
506
  return token;
490
507
  }
@@ -618,17 +635,235 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
618
635
  local: strapiInfoSave,
619
636
  tokenServiceFactory
620
637
  }, Symbol.toStringTag, { value: "Module" }));
621
- async function handleError(ctx, error) {
638
+ yup__namespace.object({
639
+ name: yup__namespace.string().required(),
640
+ exports: yup__namespace.lazy(
641
+ (value) => yup__namespace.object(
642
+ typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
643
+ if (typeof value2 === "object") {
644
+ acc[key] = yup__namespace.object({
645
+ types: yup__namespace.string().optional(),
646
+ source: yup__namespace.string().required(),
647
+ module: yup__namespace.string().optional(),
648
+ import: yup__namespace.string().required(),
649
+ require: yup__namespace.string().required(),
650
+ default: yup__namespace.string().required()
651
+ }).noUnknown(true);
652
+ } else {
653
+ acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
654
+ }
655
+ return acc;
656
+ }, {}) : void 0
657
+ ).optional()
658
+ )
659
+ });
660
+ const loadPkg = async ({ cwd, logger }) => {
661
+ const pkgPath = await pkgUp__default.default({ cwd });
662
+ if (!pkgPath) {
663
+ throw new Error("Could not find a package.json in the current directory");
664
+ }
665
+ const buffer = await fs__default.default.readFile(pkgPath);
666
+ const pkg = JSON.parse(buffer.toString());
667
+ logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
668
+ return pkg;
669
+ };
670
+ async function getProjectNameFromPackageJson(ctx) {
671
+ try {
672
+ const packageJson2 = await loadPkg(ctx);
673
+ return packageJson2.name || "my-strapi-project";
674
+ } catch (e) {
675
+ return "my-strapi-project";
676
+ }
677
+ }
678
+ function applyDefaultName(newDefaultName, questions, defaultValues) {
679
+ const newDefaultValues = ___default.default.cloneDeep(defaultValues);
680
+ newDefaultValues.name = newDefaultName;
681
+ const newQuestions = questions.map((question) => {
682
+ const questionCopy = ___default.default.cloneDeep(question);
683
+ if (questionCopy.name === "name") {
684
+ questionCopy.default = newDefaultName;
685
+ }
686
+ return questionCopy;
687
+ });
688
+ return { newQuestions, newDefaultValues };
689
+ }
690
+ const openModule$1 = import("open");
691
+ async function promptLogin(ctx) {
692
+ const response = await inquirer__default.default.prompt([
693
+ {
694
+ type: "confirm",
695
+ name: "login",
696
+ message: "Would you like to login?"
697
+ }
698
+ ]);
699
+ if (response.login) {
700
+ const loginSuccessful = await loginAction(ctx);
701
+ return loginSuccessful;
702
+ }
703
+ return false;
704
+ }
705
+ async function loginAction(ctx) {
706
+ const { logger } = ctx;
622
707
  const tokenService = await tokenServiceFactory(ctx);
708
+ const existingToken = await tokenService.retrieveToken();
709
+ const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
710
+ const trackFailedLogin = async () => {
711
+ try {
712
+ await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
713
+ } catch (e) {
714
+ logger.debug("Failed to track failed login", e);
715
+ }
716
+ };
717
+ if (existingToken) {
718
+ const isTokenValid = await tokenService.isTokenValid(existingToken);
719
+ if (isTokenValid) {
720
+ try {
721
+ const userInfo = await cloudApiService.getUserInfo();
722
+ const { email } = userInfo.data.data;
723
+ if (email) {
724
+ logger.log(`You are already logged into your account (${email}).`);
725
+ } else {
726
+ logger.log("You are already logged in.");
727
+ }
728
+ logger.log(
729
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
730
+ );
731
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
732
+ return true;
733
+ } catch (e) {
734
+ logger.debug("Failed to fetch user info", e);
735
+ }
736
+ }
737
+ }
738
+ let cliConfig2;
739
+ try {
740
+ logger.info("🔌 Connecting to the Strapi Cloud API...");
741
+ const config = await cloudApiService.config();
742
+ cliConfig2 = config.data;
743
+ } catch (e) {
744
+ logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
745
+ logger.debug(e);
746
+ return false;
747
+ }
748
+ try {
749
+ await cloudApiService.track("willLoginAttempt", {});
750
+ } catch (e) {
751
+ logger.debug("Failed to track login attempt", e);
752
+ }
753
+ logger.debug("🔐 Creating device authentication request...", {
754
+ client_id: cliConfig2.clientId,
755
+ scope: cliConfig2.scope,
756
+ audience: cliConfig2.audience
757
+ });
758
+ const deviceAuthResponse = await axios__default.default.post(cliConfig2.deviceCodeAuthUrl, {
759
+ client_id: cliConfig2.clientId,
760
+ scope: cliConfig2.scope,
761
+ audience: cliConfig2.audience
762
+ }).catch((e) => {
763
+ logger.error("There was an issue with the authentication process. Please try again.");
764
+ if (e.message) {
765
+ logger.debug(e.message, e);
766
+ } else {
767
+ logger.debug(e);
768
+ }
769
+ });
770
+ openModule$1.then((open) => {
771
+ open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
772
+ logger.error("We encountered an issue opening the browser. Please try again later.");
773
+ logger.debug(e.message, e);
774
+ });
775
+ });
776
+ logger.log("If a browser tab does not open automatically, please follow the next steps:");
777
+ logger.log(
778
+ `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
779
+ );
780
+ logger.log(
781
+ `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
782
+ `
783
+ );
784
+ const tokenPayload = {
785
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
786
+ device_code: deviceAuthResponse.data.device_code,
787
+ client_id: cliConfig2.clientId
788
+ };
789
+ let isAuthenticated = false;
790
+ const authenticate = async () => {
791
+ const spinner = logger.spinner("Waiting for authentication");
792
+ spinner.start();
793
+ const spinnerFail = () => spinner.fail("Authentication failed!");
794
+ while (!isAuthenticated) {
795
+ try {
796
+ const tokenResponse = await axios__default.default.post(cliConfig2.tokenUrl, tokenPayload);
797
+ const authTokenData = tokenResponse.data;
798
+ if (tokenResponse.status === 200) {
799
+ try {
800
+ logger.debug("🔐 Validating token...");
801
+ await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
802
+ logger.debug("🔐 Token validation successful!");
803
+ } catch (e) {
804
+ logger.debug(e);
805
+ spinnerFail();
806
+ throw new Error("Unable to proceed: Token validation failed");
807
+ }
808
+ logger.debug("🔍 Fetching user information...");
809
+ const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
810
+ await cloudApiServiceWithToken.getUserInfo();
811
+ logger.debug("🔍 User information fetched successfully!");
812
+ try {
813
+ logger.debug("📝 Saving login information...");
814
+ await tokenService.saveToken(authTokenData.access_token);
815
+ logger.debug("📝 Login information saved successfully!");
816
+ isAuthenticated = true;
817
+ } catch (e) {
818
+ logger.error(
819
+ "There was a problem saving your login information. Please try logging in again."
820
+ );
821
+ logger.debug(e);
822
+ spinnerFail();
823
+ return false;
824
+ }
825
+ }
826
+ } catch (e) {
827
+ if (e.message === "Unable to proceed: Token validation failed") {
828
+ logger.error(
829
+ "There seems to be a problem with your login information. Please try logging in again."
830
+ );
831
+ spinnerFail();
832
+ await trackFailedLogin();
833
+ return false;
834
+ }
835
+ if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
836
+ logger.debug(e);
837
+ spinnerFail();
838
+ await trackFailedLogin();
839
+ return false;
840
+ }
841
+ await new Promise((resolve) => {
842
+ setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
843
+ });
844
+ }
845
+ }
846
+ spinner.succeed("Authentication successful!");
847
+ logger.log("You are now logged into Strapi Cloud.");
848
+ logger.log(
849
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
850
+ );
851
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
852
+ try {
853
+ await cloudApiService.track("didLogin", { loginMethod: "cli" });
854
+ } catch (e) {
855
+ logger.debug("Failed to track login", e);
856
+ }
857
+ };
858
+ await authenticate();
859
+ return isAuthenticated;
860
+ }
861
+ async function handleError(ctx, error) {
623
862
  const { logger } = ctx;
624
863
  logger.debug(error);
625
864
  if (error instanceof axios.AxiosError) {
626
865
  const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
627
866
  switch (error.response?.status) {
628
- case 401:
629
- logger.error("Your session has expired. Please log in again.");
630
- await tokenService.eraseToken();
631
- return;
632
867
  case 403:
633
868
  logger.error(
634
869
  errorMessage || "You do not have permission to create a project. Please contact support for assistance."
@@ -654,28 +889,48 @@ async function handleError(ctx, error) {
654
889
  "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
655
890
  );
656
891
  }
657
- const action$3 = async (ctx) => {
892
+ async function createProject$1(ctx, cloudApi, projectInput) {
658
893
  const { logger } = ctx;
659
- const { getValidToken } = await tokenServiceFactory(ctx);
660
- const token = await getValidToken();
894
+ const spinner = logger.spinner("Setting up your project...").start();
895
+ try {
896
+ const { data } = await cloudApi.createProject(projectInput);
897
+ await save({ project: data });
898
+ spinner.succeed("Project created successfully!");
899
+ return data;
900
+ } catch (e) {
901
+ spinner.fail("An error occurred while creating the project on Strapi Cloud.");
902
+ throw e;
903
+ }
904
+ }
905
+ const action$2 = async (ctx) => {
906
+ const { logger } = ctx;
907
+ const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
908
+ const token = await getValidToken(ctx, promptLogin);
661
909
  if (!token) {
662
910
  return;
663
911
  }
664
- const cloudApi = await cloudApiFactory(token);
912
+ const cloudApi = await cloudApiFactory(ctx, token);
665
913
  const { data: config } = await cloudApi.config();
666
- const { questions, defaults: defaultValues } = config.projectCreation;
914
+ const { newQuestions: questions, newDefaultValues: defaultValues } = applyDefaultName(
915
+ await getProjectNameFromPackageJson(ctx),
916
+ config.projectCreation.questions,
917
+ config.projectCreation.defaults
918
+ );
667
919
  const projectAnswersDefaulted = fp.defaults(defaultValues);
668
920
  const projectAnswers = await inquirer__default.default.prompt(questions);
669
921
  const projectInput = projectAnswersDefaulted(projectAnswers);
670
- const spinner = logger.spinner("Setting up your project...").start();
671
922
  try {
672
- const { data } = await cloudApi.createProject(projectInput);
673
- await save({ project: data });
674
- spinner.succeed("Project created successfully!");
675
- return data;
923
+ return await createProject$1(ctx, cloudApi, projectInput);
676
924
  } catch (e) {
677
- spinner.fail("Failed to create project on Strapi Cloud.");
678
- await handleError(ctx, e);
925
+ if (e instanceof axios.AxiosError && e.response?.status === 401) {
926
+ logger.warn("Oops! Your session has expired. Please log in again to retry.");
927
+ await eraseToken();
928
+ if (await promptLogin(ctx)) {
929
+ return await createProject$1(ctx, cloudApi, projectInput);
930
+ }
931
+ } else {
932
+ await handleError(ctx, e);
933
+ }
679
934
  }
680
935
  };
681
936
  function notificationServiceFactory({ logger }) {
@@ -709,38 +964,6 @@ function notificationServiceFactory({ logger }) {
709
964
  };
710
965
  };
711
966
  }
712
- yup__namespace.object({
713
- name: yup__namespace.string().required(),
714
- exports: yup__namespace.lazy(
715
- (value) => yup__namespace.object(
716
- typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
717
- if (typeof value2 === "object") {
718
- acc[key] = yup__namespace.object({
719
- types: yup__namespace.string().optional(),
720
- source: yup__namespace.string().required(),
721
- module: yup__namespace.string().optional(),
722
- import: yup__namespace.string().required(),
723
- require: yup__namespace.string().required(),
724
- default: yup__namespace.string().required()
725
- }).noUnknown(true);
726
- } else {
727
- acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
728
- }
729
- return acc;
730
- }, {}) : void 0
731
- ).optional()
732
- )
733
- });
734
- const loadPkg = async ({ cwd, logger }) => {
735
- const pkgPath = await pkgUp__default.default({ cwd });
736
- if (!pkgPath) {
737
- throw new Error("Could not find a package.json in the current directory");
738
- }
739
- const buffer = await fs__default.default.readFile(pkgPath);
740
- const pkg = JSON.parse(buffer.toString());
741
- logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
742
- return pkg;
743
- };
744
967
  const buildLogsServiceFactory = ({ logger }) => {
745
968
  return async (url, token, cliConfig2) => {
746
969
  const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
@@ -803,7 +1026,7 @@ const buildLogsServiceFactory = ({ logger }) => {
803
1026
  };
804
1027
  };
805
1028
  async function upload(ctx, project, token, maxProjectFileSize) {
806
- const cloudApi = await cloudApiFactory(token);
1029
+ const cloudApi = await cloudApiFactory(ctx, token);
807
1030
  try {
808
1031
  const storagePath = await getTmpStoragePath();
809
1032
  const projectFolder = path__namespace.default.resolve(process.cwd());
@@ -894,7 +1117,7 @@ async function getProject(ctx) {
894
1117
  const { project } = await retrieve();
895
1118
  if (!project) {
896
1119
  try {
897
- return await action$3(ctx);
1120
+ return await action$2(ctx);
898
1121
  } catch (e) {
899
1122
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
900
1123
  ctx.logger.debug(e);
@@ -903,10 +1126,9 @@ async function getProject(ctx) {
903
1126
  }
904
1127
  return project;
905
1128
  }
906
- const action$2 = async (ctx) => {
1129
+ const action$1 = async (ctx) => {
907
1130
  const { getValidToken } = await tokenServiceFactory(ctx);
908
- const cloudApiService = await cloudApiFactory();
909
- const token = await getValidToken();
1131
+ const token = await getValidToken(ctx, promptLogin);
910
1132
  if (!token) {
911
1133
  return;
912
1134
  }
@@ -914,6 +1136,7 @@ const action$2 = async (ctx) => {
914
1136
  if (!project) {
915
1137
  return;
916
1138
  }
1139
+ const cloudApiService = await cloudApiFactory(ctx);
917
1140
  try {
918
1141
  await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
919
1142
  } catch (e) {
@@ -978,183 +1201,27 @@ const runAction = (name2, action2) => (...args) => {
978
1201
  });
979
1202
  };
980
1203
  const command$3 = ({ command: command2, ctx }) => {
981
- command2.command("cloud:deploy").alias("deploy").description("Deploy a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("deploy", action$2)(ctx));
1204
+ command2.command("cloud:deploy").alias("deploy").description("Deploy a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("deploy", action$1)(ctx));
982
1205
  };
983
1206
  const deployProject = {
984
1207
  name: "deploy-project",
985
1208
  description: "Deploy a Strapi Cloud project",
986
- action: action$2,
1209
+ action: action$1,
987
1210
  command: command$3
988
1211
  };
989
- const openModule = import("open");
990
- const action$1 = async (ctx) => {
991
- const { logger } = ctx;
992
- const tokenService = await tokenServiceFactory(ctx);
993
- const existingToken = await tokenService.retrieveToken();
994
- const cloudApiService = await cloudApiFactory(existingToken || void 0);
995
- const trackFailedLogin = async () => {
996
- try {
997
- await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
998
- } catch (e) {
999
- logger.debug("Failed to track failed login", e);
1000
- }
1001
- };
1002
- if (existingToken) {
1003
- const isTokenValid = await tokenService.isTokenValid(existingToken);
1004
- if (isTokenValid) {
1005
- try {
1006
- const userInfo = await cloudApiService.getUserInfo();
1007
- const { email } = userInfo.data.data;
1008
- if (email) {
1009
- logger.log(`You are already logged into your account (${email}).`);
1010
- } else {
1011
- logger.log("You are already logged in.");
1012
- }
1013
- logger.log(
1014
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1015
- );
1016
- logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1017
- return true;
1018
- } catch (e) {
1019
- logger.debug("Failed to fetch user info", e);
1020
- }
1021
- }
1022
- }
1023
- let cliConfig2;
1024
- try {
1025
- logger.info("🔌 Connecting to the Strapi Cloud API...");
1026
- const config = await cloudApiService.config();
1027
- cliConfig2 = config.data;
1028
- } catch (e) {
1029
- logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
1030
- logger.debug(e);
1031
- return false;
1032
- }
1033
- try {
1034
- await cloudApiService.track("willLoginAttempt", {});
1035
- } catch (e) {
1036
- logger.debug("Failed to track login attempt", e);
1037
- }
1038
- logger.debug("🔐 Creating device authentication request...", {
1039
- client_id: cliConfig2.clientId,
1040
- scope: cliConfig2.scope,
1041
- audience: cliConfig2.audience
1042
- });
1043
- const deviceAuthResponse = await axios__default.default.post(cliConfig2.deviceCodeAuthUrl, {
1044
- client_id: cliConfig2.clientId,
1045
- scope: cliConfig2.scope,
1046
- audience: cliConfig2.audience
1047
- }).catch((e) => {
1048
- logger.error("There was an issue with the authentication process. Please try again.");
1049
- if (e.message) {
1050
- logger.debug(e.message, e);
1051
- } else {
1052
- logger.debug(e);
1053
- }
1054
- });
1055
- openModule.then((open) => {
1056
- open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
1057
- logger.error("We encountered an issue opening the browser. Please try again later.");
1058
- logger.debug(e.message, e);
1059
- });
1060
- });
1061
- logger.log("If a browser tab does not open automatically, please follow the next steps:");
1062
- logger.log(
1063
- `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
1064
- );
1065
- logger.log(
1066
- `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
1067
- `
1068
- );
1069
- const tokenPayload = {
1070
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1071
- device_code: deviceAuthResponse.data.device_code,
1072
- client_id: cliConfig2.clientId
1073
- };
1074
- let isAuthenticated = false;
1075
- const authenticate = async () => {
1076
- const spinner = logger.spinner("Waiting for authentication");
1077
- spinner.start();
1078
- const spinnerFail = () => spinner.fail("Authentication failed!");
1079
- while (!isAuthenticated) {
1080
- try {
1081
- const tokenResponse = await axios__default.default.post(cliConfig2.tokenUrl, tokenPayload);
1082
- const authTokenData = tokenResponse.data;
1083
- if (tokenResponse.status === 200) {
1084
- try {
1085
- logger.debug("🔐 Validating token...");
1086
- await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
1087
- logger.debug("🔐 Token validation successful!");
1088
- } catch (e) {
1089
- logger.debug(e);
1090
- spinnerFail();
1091
- throw new Error("Unable to proceed: Token validation failed");
1092
- }
1093
- logger.debug("🔍 Fetching user information...");
1094
- const cloudApiServiceWithToken = await cloudApiFactory(authTokenData.access_token);
1095
- await cloudApiServiceWithToken.getUserInfo();
1096
- logger.debug("🔍 User information fetched successfully!");
1097
- try {
1098
- logger.debug("📝 Saving login information...");
1099
- await tokenService.saveToken(authTokenData.access_token);
1100
- logger.debug("📝 Login information saved successfully!");
1101
- isAuthenticated = true;
1102
- } catch (e) {
1103
- logger.error(
1104
- "There was a problem saving your login information. Please try logging in again."
1105
- );
1106
- logger.debug(e);
1107
- spinnerFail();
1108
- return false;
1109
- }
1110
- }
1111
- } catch (e) {
1112
- if (e.message === "Unable to proceed: Token validation failed") {
1113
- logger.error(
1114
- "There seems to be a problem with your login information. Please try logging in again."
1115
- );
1116
- spinnerFail();
1117
- await trackFailedLogin();
1118
- return false;
1119
- }
1120
- if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
1121
- logger.debug(e);
1122
- spinnerFail();
1123
- await trackFailedLogin();
1124
- return false;
1125
- }
1126
- await new Promise((resolve) => {
1127
- setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
1128
- });
1129
- }
1130
- }
1131
- spinner.succeed("Authentication successful!");
1132
- logger.log("You are now logged into Strapi Cloud.");
1133
- logger.log(
1134
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1135
- );
1136
- logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1137
- try {
1138
- await cloudApiService.track("didLogin", { loginMethod: "cli" });
1139
- } catch (e) {
1140
- logger.debug("Failed to track login", e);
1141
- }
1142
- };
1143
- await authenticate();
1144
- return isAuthenticated;
1145
- };
1146
1212
  const command$2 = ({ command: command2, ctx }) => {
1147
1213
  command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1148
1214
  "after",
1149
1215
  "\nAfter running this command, you will be prompted to enter your authentication information."
1150
- ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", action$1)(ctx));
1216
+ ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", loginAction)(ctx));
1151
1217
  };
1152
1218
  const login = {
1153
1219
  name: "login",
1154
1220
  description: "Strapi Cloud Login",
1155
- action: action$1,
1221
+ action: loginAction,
1156
1222
  command: command$2
1157
1223
  };
1224
+ const openModule = import("open");
1158
1225
  const action = async (ctx) => {
1159
1226
  const { logger } = ctx;
1160
1227
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
@@ -1163,9 +1230,21 @@ const action = async (ctx) => {
1163
1230
  logger.log("You're already logged out.");
1164
1231
  return;
1165
1232
  }
1166
- const cloudApiService = await cloudApiFactory(token);
1233
+ const cloudApiService = await cloudApiFactory(ctx, token);
1234
+ const config = await cloudApiService.config();
1235
+ const cliConfig2 = config.data;
1167
1236
  try {
1168
1237
  await eraseToken();
1238
+ openModule.then((open) => {
1239
+ open.default(
1240
+ `${cliConfig2.baseUrl}/oidc/logout?client_id=${encodeURIComponent(
1241
+ cliConfig2.clientId
1242
+ )}&logout_hint=${encodeURIComponent(token)}
1243
+ `
1244
+ ).catch((e) => {
1245
+ logger.debug(e.message, e);
1246
+ });
1247
+ });
1169
1248
  logger.log(
1170
1249
  "🔌 You have been logged out from the CLI. If you are on a shared computer, please make sure to log out from the Strapi Cloud Dashboard as well."
1171
1250
  );
@@ -1189,12 +1268,12 @@ const logout = {
1189
1268
  command: command$1
1190
1269
  };
1191
1270
  const command = ({ command: command2, ctx }) => {
1192
- command2.command("cloud:create-project").description("Create a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("cloud:create-project", action$3)(ctx));
1271
+ command2.command("cloud:create-project").description("Create a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("cloud:create-project", action$2)(ctx));
1193
1272
  };
1194
1273
  const createProject = {
1195
1274
  name: "create-project",
1196
1275
  description: "Create a new project",
1197
- action: action$3,
1276
+ action: action$2,
1198
1277
  command
1199
1278
  };
1200
1279
  const cli = {