@webiny/cognito 6.5.2-beta.0 → 6.5.2-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/admin/Cognito.js +1 -1
  2. package/admin/Cognito.js.map +1 -1
  3. package/admin/Extension.js +6 -0
  4. package/admin/Extension.js.map +1 -1
  5. package/admin/SecurityPermission.js +1 -1
  6. package/admin/SecurityPermission.js.map +1 -1
  7. package/admin/features/users/resetUserMfa/ResetUserMfaGateway.d.ts +11 -0
  8. package/admin/features/users/resetUserMfa/ResetUserMfaGateway.js +42 -0
  9. package/admin/features/users/resetUserMfa/ResetUserMfaGateway.js.map +1 -0
  10. package/admin/features/users/resetUserMfa/ResetUserMfaUseCase.d.ts +10 -0
  11. package/admin/features/users/resetUserMfa/ResetUserMfaUseCase.js +18 -0
  12. package/admin/features/users/resetUserMfa/ResetUserMfaUseCase.js.map +1 -0
  13. package/admin/features/users/resetUserMfa/abstractions/ResetUserMfaGateway.d.ts +11 -0
  14. package/admin/features/users/resetUserMfa/abstractions/ResetUserMfaGateway.js +5 -0
  15. package/admin/features/users/resetUserMfa/abstractions/ResetUserMfaGateway.js.map +1 -0
  16. package/admin/features/users/resetUserMfa/abstractions/ResetUserMfaUseCase.d.ts +12 -0
  17. package/admin/features/users/resetUserMfa/abstractions/ResetUserMfaUseCase.js +5 -0
  18. package/admin/features/users/resetUserMfa/abstractions/ResetUserMfaUseCase.js.map +1 -0
  19. package/admin/features/users/resetUserMfa/abstractions/index.d.ts +2 -0
  20. package/admin/features/users/resetUserMfa/abstractions/index.js +2 -0
  21. package/admin/features/users/resetUserMfa/feature.d.ts +3 -0
  22. package/admin/features/users/resetUserMfa/feature.js +19 -0
  23. package/admin/features/users/resetUserMfa/feature.js.map +1 -0
  24. package/admin/features/users/resetUserMfa/index.d.ts +2 -0
  25. package/admin/features/users/resetUserMfa/index.js +2 -0
  26. package/admin/presentation/Cognito/components/FederatedProviders.js +1 -1
  27. package/admin/presentation/Cognito/components/FederatedProviders.js.map +1 -1
  28. package/admin/presentation/Cognito/components/SetNewPassword.js.map +1 -1
  29. package/admin/presentation/Cognito/components/SetupTotp.js +6 -5
  30. package/admin/presentation/Cognito/components/SetupTotp.js.map +1 -1
  31. package/admin/presentation/Cognito/components/View.js +5 -5
  32. package/admin/presentation/Cognito/components/View.js.map +1 -1
  33. package/admin/presentation/userMenu/AccountDetails.js +1 -1
  34. package/admin/presentation/userMenu/AccountDetails.js.map +1 -1
  35. package/admin/presentation/users/ResetMfa/ResetMfaPresenter.d.ts +25 -0
  36. package/admin/presentation/users/ResetMfa/ResetMfaPresenter.js +61 -0
  37. package/admin/presentation/users/ResetMfa/ResetMfaPresenter.js.map +1 -0
  38. package/admin/presentation/users/ResetMfa/ResetMfaPresenter.test.d.ts +1 -0
  39. package/admin/presentation/users/ResetMfa/ResetMfaPresenter.test.js +135 -0
  40. package/admin/presentation/users/ResetMfa/ResetMfaPresenter.test.js.map +1 -0
  41. package/admin/presentation/users/ResetMfa/abstractions.d.ts +38 -0
  42. package/admin/presentation/users/ResetMfa/abstractions.js +5 -0
  43. package/admin/presentation/users/ResetMfa/abstractions.js.map +1 -0
  44. package/admin/presentation/users/ResetMfa/feature.d.ts +6 -0
  45. package/admin/presentation/users/ResetMfa/feature.js +17 -0
  46. package/admin/presentation/users/ResetMfa/feature.js.map +1 -0
  47. package/admin/presentation/users/UserForm/UserFormPresenter.test.js +2 -2
  48. package/admin/presentation/users/UserForm/UserFormPresenter.test.js.map +1 -1
  49. package/admin/ui/views/Users/UsersForm.js +5 -1
  50. package/admin/ui/views/Users/UsersForm.js.map +1 -1
  51. package/admin/ui/views/Users/components/ResetMfa.d.ts +12 -0
  52. package/admin/ui/views/Users/components/ResetMfa.js +61 -0
  53. package/admin/ui/views/Users/components/ResetMfa.js.map +1 -0
  54. package/api/CognitoApiFeature.js +2 -0
  55. package/api/CognitoApiFeature.js.map +1 -1
  56. package/api/domain/errors.d.ts +19 -0
  57. package/api/domain/errors.js +21 -1
  58. package/api/domain/errors.js.map +1 -1
  59. package/api/features/CognitoIdp/CognitoIdentityProvider.d.ts +2 -0
  60. package/api/features/CognitoIdp/CognitoIdentityProvider.js +20 -0
  61. package/api/features/CognitoIdp/CognitoIdentityProvider.js.map +1 -1
  62. package/api/features/CognitoIdp/abstractions.d.ts +6 -0
  63. package/api/features/CognitoIdp/abstractions.js.map +1 -1
  64. package/api/features/CognitoService/CognitoService.d.ts +1 -0
  65. package/api/features/CognitoService/CognitoService.js +9 -0
  66. package/api/features/CognitoService/CognitoService.js.map +1 -1
  67. package/api/features/CognitoService/abstractions.d.ts +5 -0
  68. package/api/features/CognitoService/abstractions.js.map +1 -1
  69. package/api/features/CognitoService/adminDeleteSoftwareToken.d.ts +16 -0
  70. package/api/features/CognitoService/adminDeleteSoftwareToken.js +69 -0
  71. package/api/features/CognitoService/adminDeleteSoftwareToken.js.map +1 -0
  72. package/api/features/CognitoService/adminDeleteSoftwareToken.test.d.ts +1 -0
  73. package/api/features/CognitoService/adminDeleteSoftwareToken.test.js +91 -0
  74. package/api/features/CognitoService/adminDeleteSoftwareToken.test.js.map +1 -0
  75. package/api/features/ResetUserMfa/ResetUserMfaUseCase.d.ts +14 -0
  76. package/api/features/ResetUserMfa/ResetUserMfaUseCase.js +43 -0
  77. package/api/features/ResetUserMfa/ResetUserMfaUseCase.js.map +1 -0
  78. package/api/features/ResetUserMfa/abstractions.d.ts +24 -0
  79. package/api/features/ResetUserMfa/abstractions.js +5 -0
  80. package/api/features/ResetUserMfa/abstractions.js.map +1 -0
  81. package/api/features/ResetUserMfa/feature.d.ts +4 -0
  82. package/api/features/ResetUserMfa/feature.js +11 -0
  83. package/api/features/ResetUserMfa/feature.js.map +1 -0
  84. package/api/features/ResetUserMfa/index.d.ts +2 -0
  85. package/api/features/ResetUserMfa/index.js +2 -0
  86. package/api/graphql/user.gql.js +19 -0
  87. package/api/graphql/user.gql.js.map +1 -1
  88. package/package.json +23 -20
@@ -81,6 +81,26 @@ class CognitoDeleteUserError extends BaseError {
81
81
  }), this.code = "Cognito/User/Delete";
82
82
  }
83
83
  }
84
+ class CognitoResetMfaError extends BaseError {
85
+ constructor(error){
86
+ super({
87
+ message: `Failed to reset the user's MFA in Cognito: ${error.message}`,
88
+ data: {
89
+ error
90
+ }
91
+ }), this.code = "Cognito/User/ResetMfa";
92
+ }
93
+ }
94
+ class CognitoExternalUserError extends BaseError {
95
+ constructor(id){
96
+ super({
97
+ message: "This user signs in through an external identity provider, which manages their MFA.",
98
+ data: {
99
+ id
100
+ }
101
+ }), this.code = "Cognito/User/External";
102
+ }
103
+ }
84
104
  class CognitoSharedAccountError extends BaseError {
85
105
  constructor(id){
86
106
  super({
@@ -91,6 +111,6 @@ class CognitoSharedAccountError extends BaseError {
91
111
  }), this.code = "Cognito/Account/Shared";
92
112
  }
93
113
  }
94
- export { CognitoAccountExistsError, CognitoAccountInOtherTenantError, CognitoAccountNotFoundError, CognitoCreateUserError, CognitoDeleteUserError, CognitoGetUserError, CognitoSharedAccountError, CognitoUpdateRollbackError, CognitoUpdateUserError };
114
+ export { CognitoAccountExistsError, CognitoAccountInOtherTenantError, CognitoAccountNotFoundError, CognitoCreateUserError, CognitoDeleteUserError, CognitoExternalUserError, CognitoGetUserError, CognitoResetMfaError, CognitoSharedAccountError, CognitoUpdateRollbackError, CognitoUpdateUserError };
95
115
 
96
116
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"api/domain/errors.js","sources":["../../../src/api/domain/errors.ts"],"sourcesContent":["import { BaseError } from \"@webiny/feature/api\";\n\n/**\n * Error when a user already exists in Cognito User Pool\n */\nexport class CognitoAccountExistsError extends BaseError<{ email: string }> {\n override readonly code = \"Cognito/Account/Exists\" as const;\n\n constructor(email: string) {\n super({\n message: `An account with this email already exists in your Cognito User Pool.`,\n data: { email }\n });\n }\n}\n\n/**\n * Error when creating a user whose email already has an account in another tenant:\n * that account has to be linked to this tenant instead\n */\nexport class CognitoAccountInOtherTenantError extends BaseError<{ email: string }> {\n override readonly code = \"Cognito/Account/ExistsInOtherTenant\" as const;\n\n constructor(email: string) {\n super({\n message: `This email already has an account in another tenant. Link it instead.`,\n data: { email }\n });\n }\n}\n\n/**\n * Error when linking an email that has no account in the Cognito User Pool\n */\nexport class CognitoAccountNotFoundError extends BaseError<{ email: string }> {\n override readonly code = \"Cognito/Account/NotFound\" as const;\n\n constructor(email: string) {\n super({\n message: `There's no account with this email.`,\n data: { email }\n });\n }\n}\n\n/**\n * Error when loading an account from the Cognito User Pool fails\n */\nexport class CognitoGetUserError extends BaseError<{ error: Error }> {\n override readonly code = \"Cognito/User/Get\" as const;\n\n constructor(error: Error) {\n super({\n message: `Failed to load the account from Cognito: ${error.message}`,\n data: { error }\n });\n }\n}\n\n/**\n * Error when creating a user in Cognito fails\n */\nexport class CognitoCreateUserError extends BaseError<{ error: Error }> {\n override readonly code = \"Cognito/User/Create\" as const;\n\n constructor(error: Error) {\n super({\n message: `Failed to create user in Cognito: ${error.message}`,\n data: { error }\n });\n }\n}\n\n/**\n * Error when updating a user in Cognito fails\n */\nexport class CognitoUpdateUserError extends BaseError<{ error: Error }> {\n override readonly code = \"Cognito/User/Update\" as const;\n\n constructor(error: Error) {\n super({\n message: `Failed to update user in Cognito: ${error.message}`,\n data: { error }\n });\n }\n}\n\n/**\n * Error when updating a user fails and some tenants' records can't be put back,\n * so those records no longer match the Cognito account\n */\nexport class CognitoUpdateRollbackError extends BaseError<{\n error: Error;\n tenants: string[];\n rollbackErrors: Error[];\n}> {\n override readonly code = \"Cognito/User/UpdateRollback\" as const;\n\n constructor(error: Error, tenants: string[], rollbackErrors: Error[]) {\n super({\n message: `Failed to update user: ${error.message}. The user's records in tenants ${tenants.join(\", \")} could not be restored and no longer match the Cognito account.`,\n data: { error, tenants, rollbackErrors }\n });\n }\n}\n\n/**\n * Error when deleting a user from Cognito fails\n */\nexport class CognitoDeleteUserError extends BaseError<{ error: Error }> {\n override readonly code = \"Cognito/User/Delete\" as const;\n\n constructor(error: Error) {\n super({\n message: `Failed to delete user from Cognito: ${error.message}`,\n data: { error }\n });\n }\n}\n\n/**\n * Error when an administrator changes the sign-in details of an account that other tenants share\n */\nexport class CognitoSharedAccountError extends BaseError<{ id: string }> {\n override readonly code = \"Cognito/Account/Shared\" as const;\n\n constructor(id: string) {\n super({\n message: `This person's account is also used in other tenants, so only they can change its name, email and password.`,\n data: { id }\n });\n }\n}\n"],"names":["CognitoAccountExistsError","BaseError","email","CognitoAccountInOtherTenantError","CognitoAccountNotFoundError","CognitoGetUserError","error","CognitoCreateUserError","CognitoUpdateUserError","CognitoUpdateRollbackError","tenants","rollbackErrors","CognitoDeleteUserError","CognitoSharedAccountError","id"],"mappings":";AAKO,MAAMA,kCAAkCC;IAG3C,YAAYC,KAAa,CAAE;QACvB,KAAK,CAAC;YACF,SAAS;YACT,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAMO,MAAMC,yCAAyCF;IAGlD,YAAYC,KAAa,CAAE;QACvB,KAAK,CAAC;YACF,SAAS;YACT,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAME,oCAAoCH;IAG7C,YAAYC,KAAa,CAAE;QACvB,KAAK,CAAC;YACF,SAAS;YACT,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAMG,4BAA4BJ;IAGrC,YAAYK,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,yCAAyC,EAAEA,MAAM,OAAO,EAAE;YACpE,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAMC,+BAA+BN;IAGxC,YAAYK,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,kCAAkC,EAAEA,MAAM,OAAO,EAAE;YAC7D,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAME,+BAA+BP;IAGxC,YAAYK,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,kCAAkC,EAAEA,MAAM,OAAO,EAAE;YAC7D,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAMO,MAAMG,mCAAmCR;IAO5C,YAAYK,KAAY,EAAEI,OAAiB,EAAEC,cAAuB,CAAE;QAClE,KAAK,CAAC;YACF,SAAS,CAAC,uBAAuB,EAAEL,MAAM,OAAO,CAAC,gCAAgC,EAAEI,QAAQ,IAAI,CAAC,MAAM,+DAA+D,CAAC;YACtK,MAAM;gBAAEJ;gBAAOI;gBAASC;YAAe;QAC3C,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAMC,+BAA+BX;IAGxC,YAAYK,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,oCAAoC,EAAEA,MAAM,OAAO,EAAE;YAC/D,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAMO,kCAAkCZ;IAG3C,YAAYa,EAAU,CAAE;QACpB,KAAK,CAAC;YACF,SAAS;YACT,MAAM;gBAAEA;YAAG;QACf,SANc,IAAI,GAAG;IAOzB;AACJ"}
1
+ {"version":3,"file":"api/domain/errors.js","sources":["../../../src/api/domain/errors.ts"],"sourcesContent":["import { BaseError } from \"@webiny/feature/api\";\n\n/**\n * Error when a user already exists in Cognito User Pool\n */\nexport class CognitoAccountExistsError extends BaseError<{ email: string }> {\n override readonly code = \"Cognito/Account/Exists\" as const;\n\n constructor(email: string) {\n super({\n message: `An account with this email already exists in your Cognito User Pool.`,\n data: { email }\n });\n }\n}\n\n/**\n * Error when creating a user whose email already has an account in another tenant:\n * that account has to be linked to this tenant instead\n */\nexport class CognitoAccountInOtherTenantError extends BaseError<{ email: string }> {\n override readonly code = \"Cognito/Account/ExistsInOtherTenant\" as const;\n\n constructor(email: string) {\n super({\n message: `This email already has an account in another tenant. Link it instead.`,\n data: { email }\n });\n }\n}\n\n/**\n * Error when linking an email that has no account in the Cognito User Pool\n */\nexport class CognitoAccountNotFoundError extends BaseError<{ email: string }> {\n override readonly code = \"Cognito/Account/NotFound\" as const;\n\n constructor(email: string) {\n super({\n message: `There's no account with this email.`,\n data: { email }\n });\n }\n}\n\n/**\n * Error when loading an account from the Cognito User Pool fails\n */\nexport class CognitoGetUserError extends BaseError<{ error: Error }> {\n override readonly code = \"Cognito/User/Get\" as const;\n\n constructor(error: Error) {\n super({\n message: `Failed to load the account from Cognito: ${error.message}`,\n data: { error }\n });\n }\n}\n\n/**\n * Error when creating a user in Cognito fails\n */\nexport class CognitoCreateUserError extends BaseError<{ error: Error }> {\n override readonly code = \"Cognito/User/Create\" as const;\n\n constructor(error: Error) {\n super({\n message: `Failed to create user in Cognito: ${error.message}`,\n data: { error }\n });\n }\n}\n\n/**\n * Error when updating a user in Cognito fails\n */\nexport class CognitoUpdateUserError extends BaseError<{ error: Error }> {\n override readonly code = \"Cognito/User/Update\" as const;\n\n constructor(error: Error) {\n super({\n message: `Failed to update user in Cognito: ${error.message}`,\n data: { error }\n });\n }\n}\n\n/**\n * Error when updating a user fails and some tenants' records can't be put back,\n * so those records no longer match the Cognito account\n */\nexport class CognitoUpdateRollbackError extends BaseError<{\n error: Error;\n tenants: string[];\n rollbackErrors: Error[];\n}> {\n override readonly code = \"Cognito/User/UpdateRollback\" as const;\n\n constructor(error: Error, tenants: string[], rollbackErrors: Error[]) {\n super({\n message: `Failed to update user: ${error.message}. The user's records in tenants ${tenants.join(\", \")} could not be restored and no longer match the Cognito account.`,\n data: { error, tenants, rollbackErrors }\n });\n }\n}\n\n/**\n * Error when deleting a user from Cognito fails\n */\nexport class CognitoDeleteUserError extends BaseError<{ error: Error }> {\n override readonly code = \"Cognito/User/Delete\" as const;\n\n constructor(error: Error) {\n super({\n message: `Failed to delete user from Cognito: ${error.message}`,\n data: { error }\n });\n }\n}\n\n/**\n * Error when resetting a user's MFA in Cognito fails\n */\nexport class CognitoResetMfaError extends BaseError<{ error: Error }> {\n override readonly code = \"Cognito/User/ResetMfa\" as const;\n\n constructor(error: Error) {\n super({\n message: `Failed to reset the user's MFA in Cognito: ${error.message}`,\n data: { error }\n });\n }\n}\n\n/**\n * Error when resetting the MFA of a user who signs in through an external identity provider,\n * which manages their MFA\n */\nexport class CognitoExternalUserError extends BaseError<{ id: string }> {\n override readonly code = \"Cognito/User/External\" as const;\n\n constructor(id: string) {\n super({\n message: `This user signs in through an external identity provider, which manages their MFA.`,\n data: { id }\n });\n }\n}\n\n/**\n * Error when an administrator changes the sign-in details of an account that other tenants share\n */\nexport class CognitoSharedAccountError extends BaseError<{ id: string }> {\n override readonly code = \"Cognito/Account/Shared\" as const;\n\n constructor(id: string) {\n super({\n message: `This person's account is also used in other tenants, so only they can change its name, email and password.`,\n data: { id }\n });\n }\n}\n"],"names":["CognitoAccountExistsError","BaseError","email","CognitoAccountInOtherTenantError","CognitoAccountNotFoundError","CognitoGetUserError","error","CognitoCreateUserError","CognitoUpdateUserError","CognitoUpdateRollbackError","tenants","rollbackErrors","CognitoDeleteUserError","CognitoResetMfaError","CognitoExternalUserError","id","CognitoSharedAccountError"],"mappings":";AAKO,MAAMA,kCAAkCC;IAG3C,YAAYC,KAAa,CAAE;QACvB,KAAK,CAAC;YACF,SAAS;YACT,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAMO,MAAMC,yCAAyCF;IAGlD,YAAYC,KAAa,CAAE;QACvB,KAAK,CAAC;YACF,SAAS;YACT,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAME,oCAAoCH;IAG7C,YAAYC,KAAa,CAAE;QACvB,KAAK,CAAC;YACF,SAAS;YACT,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAMG,4BAA4BJ;IAGrC,YAAYK,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,yCAAyC,EAAEA,MAAM,OAAO,EAAE;YACpE,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAMC,+BAA+BN;IAGxC,YAAYK,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,kCAAkC,EAAEA,MAAM,OAAO,EAAE;YAC7D,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAME,+BAA+BP;IAGxC,YAAYK,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,kCAAkC,EAAEA,MAAM,OAAO,EAAE;YAC7D,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAMO,MAAMG,mCAAmCR;IAO5C,YAAYK,KAAY,EAAEI,OAAiB,EAAEC,cAAuB,CAAE;QAClE,KAAK,CAAC;YACF,SAAS,CAAC,uBAAuB,EAAEL,MAAM,OAAO,CAAC,gCAAgC,EAAEI,QAAQ,IAAI,CAAC,MAAM,+DAA+D,CAAC;YACtK,MAAM;gBAAEJ;gBAAOI;gBAASC;YAAe;QAC3C,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAMC,+BAA+BX;IAGxC,YAAYK,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,oCAAoC,EAAEA,MAAM,OAAO,EAAE;YAC/D,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAMO,6BAA6BZ;IAGtC,YAAYK,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,2CAA2C,EAAEA,MAAM,OAAO,EAAE;YACtE,MAAM;gBAAEA;YAAM;QAClB,SANc,IAAI,GAAG;IAOzB;AACJ;AAMO,MAAMQ,iCAAiCb;IAG1C,YAAYc,EAAU,CAAE;QACpB,KAAK,CAAC;YACF,SAAS;YACT,MAAM;gBAAEA;YAAG;QACf,SANc,IAAI,GAAG;IAOzB;AACJ;AAKO,MAAMC,kCAAkCf;IAG3C,YAAYc,EAAU,CAAE;QACpB,KAAK,CAAC;YACF,SAAS;YACT,MAAM;gBAAEA;YAAG;QACf,SANc,IAAI,GAAG;IAOzB;AACJ"}
@@ -8,6 +8,8 @@ declare class CognitoIdentityProviderImpl implements OidcIdentityProvider.Interf
8
8
  isApplicable(token: OidcIdentityProvider.JwtPayload): boolean;
9
9
  getIdentity(token: OidcIdentityProvider.JwtPayload): Promise<OidcIdentityProvider.IdentityData>;
10
10
  verifyTokenClaims(token: OidcIdentityProvider.JwtPayload): Promise<void>;
11
+ private verifyFederatedCustomId;
12
+ private getFederatedIdentities;
11
13
  }
12
14
  export declare const CognitoIdentityProvider: typeof CognitoIdentityProviderImpl & {
13
15
  __abstraction: import("@webiny/di").Abstraction<import("@webiny/api-core/idp/abstractions.js").IOidcIdentityProvider>;
@@ -44,8 +44,28 @@ class CognitoIdentityProviderImpl {
44
44
  };
45
45
  }
46
46
  async verifyTokenClaims(token) {
47
+ if ("id" !== token.token_use) throw new Error('Invalid token: "token_use" must be "id".');
48
+ if (this.config?.verifyFederatedCustomId !== false) this.verifyFederatedCustomId(token);
47
49
  if (this.config?.verifyTokenClaims) await this.config.verifyTokenClaims(token);
48
50
  }
51
+ verifyFederatedCustomId(token) {
52
+ const identities = this.getFederatedIdentities(token);
53
+ if (!identities) return;
54
+ const customId = token["custom:id"];
55
+ const isMatch = "string" == typeof customId && customId.length > 0 && identities.some((identity)=>String(identity?.userId) === customId);
56
+ if (!isMatch) throw new Error('Invalid token: "custom:id" must match the user ID of the federated identity.');
57
+ }
58
+ getFederatedIdentities(token) {
59
+ let identities = token.identities;
60
+ if (null == identities) return null;
61
+ if ("string" == typeof identities) try {
62
+ identities = JSON.parse(identities);
63
+ } catch {
64
+ throw new Error('Invalid token: "identities" claim is malformed.');
65
+ }
66
+ if (!Array.isArray(identities)) throw new Error('Invalid token: "identities" claim is malformed.');
67
+ return identities.length > 0 ? identities : null;
68
+ }
49
69
  }
50
70
  const CognitoIdentityProvider = OidcIdentityProvider.createImplementation({
51
71
  implementation: CognitoIdentityProviderImpl,
@@ -1 +1 @@
1
- {"version":3,"file":"api/features/CognitoIdp/CognitoIdentityProvider.js","sources":["../../../../src/api/features/CognitoIdp/CognitoIdentityProvider.ts"],"sourcesContent":["import { OidcIdentityProvider } from \"@webiny/api-core/idp\";\nimport { CognitoIdpConfig } from \"./abstractions.js\";\n\nclass CognitoIdentityProviderImpl implements OidcIdentityProvider.Interface {\n public clientId: string;\n public issuer: string;\n\n constructor(private config: CognitoIdpConfig.Interface | undefined) {\n const region = String(process.env.COGNITO_REGION);\n const userPoolId = String(process.env.COGNITO_USER_POOL_ID);\n this.clientId = String(process.env.COGNITO_CLIENT_ID);\n this.issuer = `https://cognito-idp.${region}.amazonaws.com/${userPoolId}`;\n }\n\n isApplicable(token: OidcIdentityProvider.JwtPayload) {\n const issuer = token.iss as string;\n if (!issuer) {\n return false;\n }\n\n return issuer === this.issuer;\n }\n\n async getIdentity(\n token: OidcIdentityProvider.JwtPayload\n ): Promise<OidcIdentityProvider.IdentityData> {\n const isFederated = Array.isArray(token.identities) && token.identities.length > 0;\n\n const customId = token[\"custom:id\"] as string | undefined;\n const givenName = token[\"given_name\"] as string | undefined;\n const familyName = token[\"family_name\"] as string | undefined;\n const email = token[\"email\"] as string | undefined;\n\n const defaultIdentity: OidcIdentityProvider.IdentityData = {\n id: customId || token.sub || \"\",\n displayName: `${givenName || \"\"} ${familyName || \"\"}`.trim() || email || \"Unknown User\",\n type: \"admin\",\n profile: {\n email: email || \"\",\n firstName: givenName || \"\",\n lastName: familyName || \"\",\n external: isFederated\n }\n };\n\n const customIdentity = this.config ? await this.config.getIdentity(token) : null;\n\n if (!customIdentity) {\n return defaultIdentity;\n }\n\n return {\n ...defaultIdentity,\n ...customIdentity,\n type: \"admin\",\n profile: {\n ...defaultIdentity.profile,\n ...customIdentity.profile,\n external: isFederated\n }\n };\n }\n\n async verifyTokenClaims(token: OidcIdentityProvider.JwtPayload): Promise<void> {\n if (this.config?.verifyTokenClaims) {\n await this.config.verifyTokenClaims(token);\n }\n }\n}\n\nexport const CognitoIdentityProvider = OidcIdentityProvider.createImplementation({\n implementation: CognitoIdentityProviderImpl,\n dependencies: [[CognitoIdpConfig, { optional: true }]]\n});\n"],"names":["CognitoIdentityProviderImpl","config","region","String","process","userPoolId","token","issuer","isFederated","Array","customId","givenName","familyName","email","defaultIdentity","customIdentity","CognitoIdentityProvider","OidcIdentityProvider","CognitoIdpConfig"],"mappings":";;AAGA,MAAMA;IAIF,YAAoBC,MAA8C,CAAE;aAAhDA,MAAM,GAANA;QAChB,MAAMC,SAASC,OAAOC,QAAQ,GAAG,CAAC,cAAc;QAChD,MAAMC,aAAaF,OAAOC,QAAQ,GAAG,CAAC,oBAAoB;QAC1D,IAAI,CAAC,QAAQ,GAAGD,OAAOC,QAAQ,GAAG,CAAC,iBAAiB;QACpD,IAAI,CAAC,MAAM,GAAG,CAAC,oBAAoB,EAAEF,OAAO,eAAe,EAAEG,YAAY;IAC7E;IAEA,aAAaC,KAAsC,EAAE;QACjD,MAAMC,SAASD,MAAM,GAAG;QACxB,IAAI,CAACC,QACD,OAAO;QAGX,OAAOA,WAAW,IAAI,CAAC,MAAM;IACjC;IAEA,MAAM,YACFD,KAAsC,EACI;QAC1C,MAAME,cAAcC,MAAM,OAAO,CAACH,MAAM,UAAU,KAAKA,MAAM,UAAU,CAAC,MAAM,GAAG;QAEjF,MAAMI,WAAWJ,KAAK,CAAC,YAAY;QACnC,MAAMK,YAAYL,KAAK,CAAC,aAAa;QACrC,MAAMM,aAAaN,KAAK,CAAC,cAAc;QACvC,MAAMO,QAAQP,KAAK,CAAC,QAAQ;QAE5B,MAAMQ,kBAAqD;YACvD,IAAIJ,YAAYJ,MAAM,GAAG,IAAI;YAC7B,aAAa,GAAGK,aAAa,GAAG,CAAC,EAAEC,cAAc,IAAI,CAAC,IAAI,MAAMC,SAAS;YACzE,MAAM;YACN,SAAS;gBACL,OAAOA,SAAS;gBAChB,WAAWF,aAAa;gBACxB,UAAUC,cAAc;gBACxB,UAAUJ;YACd;QACJ;QAEA,MAAMO,iBAAiB,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,WAAW,CAACT,SAAS;QAE5E,IAAI,CAACS,gBACD,OAAOD;QAGX,OAAO;YACH,GAAGA,eAAe;YAClB,GAAGC,cAAc;YACjB,MAAM;YACN,SAAS;gBACL,GAAGD,gBAAgB,OAAO;gBAC1B,GAAGC,eAAe,OAAO;gBACzB,UAAUP;YACd;QACJ;IACJ;IAEA,MAAM,kBAAkBF,KAAsC,EAAiB;QAC3E,IAAI,IAAI,CAAC,MAAM,EAAE,mBACb,MAAM,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAACA;IAE5C;AACJ;AAEO,MAAMU,0BAA0BC,qBAAqB,oBAAoB,CAAC;IAC7E,gBAAgBjB;IAChB,cAAc;QAAC;YAACkB;YAAkB;gBAAE,UAAU;YAAK;SAAE;KAAC;AAC1D"}
1
+ {"version":3,"file":"api/features/CognitoIdp/CognitoIdentityProvider.js","sources":["../../../../src/api/features/CognitoIdp/CognitoIdentityProvider.ts"],"sourcesContent":["import { OidcIdentityProvider } from \"@webiny/api-core/idp\";\nimport { CognitoIdpConfig } from \"./abstractions.js\";\n\ninterface FederatedIdentity {\n userId?: unknown;\n}\n\nclass CognitoIdentityProviderImpl implements OidcIdentityProvider.Interface {\n public clientId: string;\n public issuer: string;\n\n constructor(private config: CognitoIdpConfig.Interface | undefined) {\n const region = String(process.env.COGNITO_REGION);\n const userPoolId = String(process.env.COGNITO_USER_POOL_ID);\n this.clientId = String(process.env.COGNITO_CLIENT_ID);\n this.issuer = `https://cognito-idp.${region}.amazonaws.com/${userPoolId}`;\n }\n\n isApplicable(token: OidcIdentityProvider.JwtPayload) {\n const issuer = token.iss as string;\n if (!issuer) {\n return false;\n }\n\n return issuer === this.issuer;\n }\n\n async getIdentity(\n token: OidcIdentityProvider.JwtPayload\n ): Promise<OidcIdentityProvider.IdentityData> {\n const isFederated = Array.isArray(token.identities) && token.identities.length > 0;\n\n const customId = token[\"custom:id\"] as string | undefined;\n const givenName = token[\"given_name\"] as string | undefined;\n const familyName = token[\"family_name\"] as string | undefined;\n const email = token[\"email\"] as string | undefined;\n\n const defaultIdentity: OidcIdentityProvider.IdentityData = {\n id: customId || token.sub || \"\",\n displayName: `${givenName || \"\"} ${familyName || \"\"}`.trim() || email || \"Unknown User\",\n type: \"admin\",\n profile: {\n email: email || \"\",\n firstName: givenName || \"\",\n lastName: familyName || \"\",\n external: isFederated\n }\n };\n\n const customIdentity = this.config ? await this.config.getIdentity(token) : null;\n\n if (!customIdentity) {\n return defaultIdentity;\n }\n\n return {\n ...defaultIdentity,\n ...customIdentity,\n type: \"admin\",\n profile: {\n ...defaultIdentity.profile,\n ...customIdentity.profile,\n external: isFederated\n }\n };\n }\n\n async verifyTokenClaims(token: OidcIdentityProvider.JwtPayload): Promise<void> {\n // Security: only Cognito ID tokens identify a user; reject access tokens.\n if (token.token_use !== \"id\") {\n throw new Error(`Invalid token: \"token_use\" must be \"id\".`);\n }\n\n // Security: federated sign-in requires \"custom:id\" to stay writable by the app client, so\n // a user could set their own \"custom:id\" to someone else's ID. The \"identities\" claim is\n // set by Cognito and can't be edited, so \"custom:id\" must match one of its provider user IDs.\n // Projects that map \"custom:id\" to another provider attribute can set\n // `verifyFederatedCustomId: false` on their `CognitoIdpConfig` and verify it themselves.\n if (this.config?.verifyFederatedCustomId !== false) {\n this.verifyFederatedCustomId(token);\n }\n\n if (this.config?.verifyTokenClaims) {\n await this.config.verifyTokenClaims(token);\n }\n }\n\n private verifyFederatedCustomId(token: OidcIdentityProvider.JwtPayload): void {\n const identities = this.getFederatedIdentities(token);\n if (!identities) {\n return;\n }\n\n const customId = token[\"custom:id\"];\n const isMatch =\n typeof customId === \"string\" &&\n customId.length > 0 &&\n identities.some(identity => String(identity?.userId) === customId);\n\n if (!isMatch) {\n throw new Error(\n `Invalid token: \"custom:id\" must match the user ID of the federated identity.`\n );\n }\n }\n\n private getFederatedIdentities(\n token: OidcIdentityProvider.JwtPayload\n ): FederatedIdentity[] | null {\n let identities: unknown = token.identities;\n if (identities === undefined || identities === null) {\n return null;\n }\n\n if (typeof identities === \"string\") {\n try {\n identities = JSON.parse(identities);\n } catch {\n throw new Error(`Invalid token: \"identities\" claim is malformed.`);\n }\n }\n\n if (!Array.isArray(identities)) {\n throw new Error(`Invalid token: \"identities\" claim is malformed.`);\n }\n\n return identities.length > 0 ? identities : null;\n }\n}\n\nexport const CognitoIdentityProvider = OidcIdentityProvider.createImplementation({\n implementation: CognitoIdentityProviderImpl,\n dependencies: [[CognitoIdpConfig, { optional: true }]]\n});\n"],"names":["CognitoIdentityProviderImpl","config","region","String","process","userPoolId","token","issuer","isFederated","Array","customId","givenName","familyName","email","defaultIdentity","customIdentity","Error","identities","isMatch","identity","JSON","CognitoIdentityProvider","OidcIdentityProvider","CognitoIdpConfig"],"mappings":";;AAOA,MAAMA;IAIF,YAAoBC,MAA8C,CAAE;aAAhDA,MAAM,GAANA;QAChB,MAAMC,SAASC,OAAOC,QAAQ,GAAG,CAAC,cAAc;QAChD,MAAMC,aAAaF,OAAOC,QAAQ,GAAG,CAAC,oBAAoB;QAC1D,IAAI,CAAC,QAAQ,GAAGD,OAAOC,QAAQ,GAAG,CAAC,iBAAiB;QACpD,IAAI,CAAC,MAAM,GAAG,CAAC,oBAAoB,EAAEF,OAAO,eAAe,EAAEG,YAAY;IAC7E;IAEA,aAAaC,KAAsC,EAAE;QACjD,MAAMC,SAASD,MAAM,GAAG;QACxB,IAAI,CAACC,QACD,OAAO;QAGX,OAAOA,WAAW,IAAI,CAAC,MAAM;IACjC;IAEA,MAAM,YACFD,KAAsC,EACI;QAC1C,MAAME,cAAcC,MAAM,OAAO,CAACH,MAAM,UAAU,KAAKA,MAAM,UAAU,CAAC,MAAM,GAAG;QAEjF,MAAMI,WAAWJ,KAAK,CAAC,YAAY;QACnC,MAAMK,YAAYL,KAAK,CAAC,aAAa;QACrC,MAAMM,aAAaN,KAAK,CAAC,cAAc;QACvC,MAAMO,QAAQP,KAAK,CAAC,QAAQ;QAE5B,MAAMQ,kBAAqD;YACvD,IAAIJ,YAAYJ,MAAM,GAAG,IAAI;YAC7B,aAAa,GAAGK,aAAa,GAAG,CAAC,EAAEC,cAAc,IAAI,CAAC,IAAI,MAAMC,SAAS;YACzE,MAAM;YACN,SAAS;gBACL,OAAOA,SAAS;gBAChB,WAAWF,aAAa;gBACxB,UAAUC,cAAc;gBACxB,UAAUJ;YACd;QACJ;QAEA,MAAMO,iBAAiB,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,WAAW,CAACT,SAAS;QAE5E,IAAI,CAACS,gBACD,OAAOD;QAGX,OAAO;YACH,GAAGA,eAAe;YAClB,GAAGC,cAAc;YACjB,MAAM;YACN,SAAS;gBACL,GAAGD,gBAAgB,OAAO;gBAC1B,GAAGC,eAAe,OAAO;gBACzB,UAAUP;YACd;QACJ;IACJ;IAEA,MAAM,kBAAkBF,KAAsC,EAAiB;QAE3E,IAAIA,AAAoB,SAApBA,MAAM,SAAS,EACf,MAAM,IAAIU,MAAM;QAQpB,IAAI,IAAI,CAAC,MAAM,EAAE,4BAA4B,OACzC,IAAI,CAAC,uBAAuB,CAACV;QAGjC,IAAI,IAAI,CAAC,MAAM,EAAE,mBACb,MAAM,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAACA;IAE5C;IAEQ,wBAAwBA,KAAsC,EAAQ;QAC1E,MAAMW,aAAa,IAAI,CAAC,sBAAsB,CAACX;QAC/C,IAAI,CAACW,YACD;QAGJ,MAAMP,WAAWJ,KAAK,CAAC,YAAY;QACnC,MAAMY,UACF,AAAoB,YAApB,OAAOR,YACPA,SAAS,MAAM,GAAG,KAClBO,WAAW,IAAI,CAACE,CAAAA,WAAYhB,OAAOgB,UAAU,YAAYT;QAE7D,IAAI,CAACQ,SACD,MAAM,IAAIF,MACN;IAGZ;IAEQ,uBACJV,KAAsC,EACZ;QAC1B,IAAIW,aAAsBX,MAAM,UAAU;QAC1C,IAAIW,QAAAA,YACA,OAAO;QAGX,IAAI,AAAsB,YAAtB,OAAOA,YACP,IAAI;YACAA,aAAaG,KAAK,KAAK,CAACH;QAC5B,EAAE,OAAM;YACJ,MAAM,IAAID,MAAM;QACpB;QAGJ,IAAI,CAACP,MAAM,OAAO,CAACQ,aACf,MAAM,IAAID,MAAM;QAGpB,OAAOC,WAAW,MAAM,GAAG,IAAIA,aAAa;IAChD;AACJ;AAEO,MAAMI,0BAA0BC,qBAAqB,oBAAoB,CAAC;IAC7E,gBAAgBtB;IAChB,cAAc;QAAC;YAACuB;YAAkB;gBAAE,UAAU;YAAK;SAAE;KAAC;AAC1D"}
@@ -6,6 +6,12 @@ export type CognitoIdentity = Omit<IdentityData, "type"> & {
6
6
  export interface ICognitoIdpConfig {
7
7
  getIdentity(token: jwt.JwtPayload): Promise<CognitoIdentity> | CognitoIdentity;
8
8
  verifyTokenClaims?(token: jwt.JwtPayload): Promise<void> | void;
9
+ /**
10
+ * For federated users, the token's "custom:id" must match a user ID in its "identities" claim
11
+ * (default: true). Set to false only if "custom:id" is mapped to a different provider attribute,
12
+ * and then verify "custom:id" in `verifyTokenClaims`: it stays writable by the user.
13
+ */
14
+ verifyFederatedCustomId?: boolean;
9
15
  }
10
16
  export declare const CognitoIdpConfig: import("@webiny/di").Abstraction<ICognitoIdpConfig>;
11
17
  export declare namespace CognitoIdpConfig {
@@ -1 +1 @@
1
- {"version":3,"file":"api/features/CognitoIdp/abstractions.js","sources":["../../../../src/api/features/CognitoIdp/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type jwt from \"jsonwebtoken\";\nimport type { IdentityData } from \"@webiny/api-core/idp\";\n\nexport type CognitoIdentity = Omit<IdentityData, \"type\"> & {\n profile?: Omit<IdentityData[\"profile\"], \"external\">;\n};\n\nexport interface ICognitoIdpConfig {\n getIdentity(token: jwt.JwtPayload): Promise<CognitoIdentity> | CognitoIdentity;\n verifyTokenClaims?(token: jwt.JwtPayload): Promise<void> | void;\n}\n\nexport const CognitoIdpConfig = createAbstraction<ICognitoIdpConfig>(\"CognitoIdpConfig\");\n\nexport namespace CognitoIdpConfig {\n export type Interface = ICognitoIdpConfig;\n export type IdentityData = CognitoIdentity;\n export type JwtPayload = jwt.JwtPayload;\n}\n"],"names":["CognitoIdpConfig","createAbstraction"],"mappings":";AAaO,MAAMA,mBAAmBC,kBAAqC"}
1
+ {"version":3,"file":"api/features/CognitoIdp/abstractions.js","sources":["../../../../src/api/features/CognitoIdp/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type jwt from \"jsonwebtoken\";\nimport type { IdentityData } from \"@webiny/api-core/idp\";\n\nexport type CognitoIdentity = Omit<IdentityData, \"type\"> & {\n profile?: Omit<IdentityData[\"profile\"], \"external\">;\n};\n\nexport interface ICognitoIdpConfig {\n getIdentity(token: jwt.JwtPayload): Promise<CognitoIdentity> | CognitoIdentity;\n verifyTokenClaims?(token: jwt.JwtPayload): Promise<void> | void;\n /**\n * For federated users, the token's \"custom:id\" must match a user ID in its \"identities\" claim\n * (default: true). Set to false only if \"custom:id\" is mapped to a different provider attribute,\n * and then verify \"custom:id\" in `verifyTokenClaims`: it stays writable by the user.\n */\n verifyFederatedCustomId?: boolean;\n}\n\nexport const CognitoIdpConfig = createAbstraction<ICognitoIdpConfig>(\"CognitoIdpConfig\");\n\nexport namespace CognitoIdpConfig {\n export type Interface = ICognitoIdpConfig;\n export type IdentityData = CognitoIdentity;\n export type JwtPayload = jwt.JwtPayload;\n}\n"],"names":["CognitoIdpConfig","createAbstraction"],"mappings":";AAmBO,MAAMA,mBAAmBC,kBAAqC"}
@@ -13,6 +13,7 @@ declare class CognitoServiceImpl implements ServiceAbstraction.Interface {
13
13
  setPermanentPassword(username: string, password: string): Promise<void>;
14
14
  updateUserAttributes(username: string, attributes: Record<string, string>): Promise<void>;
15
15
  deleteUser(username: string): Promise<void>;
16
+ resetMfa(username: string): Promise<void>;
16
17
  }
17
18
  export declare const CognitoService: typeof CognitoServiceImpl & {
18
19
  __abstraction: import("@webiny/di").Abstraction<import("./abstractions.js").ICognitoService>;
@@ -1,5 +1,6 @@
1
1
  import { CognitoIdentityProvider } from "@webiny/aws-sdk/client-cognito-identity-provider/index.js";
2
2
  import { CognitoConfig, CognitoService } from "./abstractions.js";
3
+ import { adminDeleteSoftwareToken } from "./adminDeleteSoftwareToken.js";
3
4
  class CognitoServiceImpl {
4
5
  constructor(config){
5
6
  this.config = config;
@@ -94,6 +95,14 @@ class CognitoServiceImpl {
94
95
  Username: username
95
96
  });
96
97
  }
98
+ async resetMfa(username) {
99
+ await adminDeleteSoftwareToken({
100
+ region: this.config.region,
101
+ userPoolId: this.config.userPoolId,
102
+ username,
103
+ credentials: this.cognito.config.credentials
104
+ });
105
+ }
97
106
  }
98
107
  const CognitoService_CognitoService = CognitoService.createImplementation({
99
108
  implementation: CognitoServiceImpl,
@@ -1 +1 @@
1
- {"version":3,"file":"api/features/CognitoService/CognitoService.js","sources":["../../../../src/api/features/CognitoService/CognitoService.ts"],"sourcesContent":["import type { AdminCreateUserRequest } from \"@webiny/aws-sdk/client-cognito-identity-provider/index.js\";\nimport { CognitoIdentityProvider } from \"@webiny/aws-sdk/client-cognito-identity-provider/index.js\";\nimport { CognitoConfig, CognitoService as ServiceAbstraction } from \"./abstractions.js\";\n\nclass CognitoServiceImpl implements ServiceAbstraction.Interface {\n private cognito: CognitoIdentityProvider;\n\n constructor(private config: CognitoConfig.Interface) {\n this.cognito = new CognitoIdentityProvider({ region: config.region });\n }\n\n async getUser(username: string): Promise<ServiceAbstraction.User | null> {\n try {\n const response = await this.cognito.adminGetUser({\n Username: username,\n UserPoolId: this.config.userPoolId\n });\n\n const attributes: Record<string, string> = {};\n for (const attribute of response.UserAttributes ?? []) {\n if (attribute.Name) {\n attributes[attribute.Name] = attribute.Value ?? \"\";\n }\n }\n\n return { username: response.Username ?? username, attributes };\n } catch (error) {\n if ((error as Error).name === \"UserNotFoundException\") {\n return null;\n }\n throw error;\n }\n }\n\n async createUser(params: {\n username: string;\n temporaryPassword: string;\n attributes: ServiceAbstraction.UserAttributes;\n }): Promise<void> {\n const createUserParams: AdminCreateUserRequest = {\n UserPoolId: this.config.userPoolId,\n Username: params.username,\n DesiredDeliveryMediums: [],\n ForceAliasCreation: false,\n MessageAction: \"SUPPRESS\",\n TemporaryPassword: params.temporaryPassword,\n UserAttributes: [\n {\n Name: \"given_name\",\n Value: params.attributes.givenName || \"\"\n },\n {\n Name: \"family_name\",\n Value: params.attributes.familyName || \"\"\n },\n {\n Name: \"preferred_username\",\n Value: params.attributes.preferredUsername\n },\n {\n Name: \"email\",\n Value: params.attributes.email\n },\n {\n Name: \"custom:id\",\n Value: params.attributes.customId\n }\n ]\n };\n\n await this.cognito.adminCreateUser(createUserParams);\n }\n\n async setEmailVerified(username: string): Promise<void> {\n await this.cognito.adminUpdateUserAttributes({\n UserPoolId: this.config.userPoolId,\n Username: username,\n UserAttributes: [\n {\n Name: \"email_verified\",\n Value: \"true\"\n }\n ]\n });\n }\n\n async setPermanentPassword(username: string, password: string): Promise<void> {\n await this.cognito.adminSetUserPassword({\n Permanent: true,\n Password: password,\n Username: username,\n UserPoolId: this.config.userPoolId\n });\n }\n\n async updateUserAttributes(\n username: string,\n attributes: Record<string, string>\n ): Promise<void> {\n const userAttributes = Object.entries(attributes).map(([name, value]) => ({\n Name: name,\n Value: value\n }));\n\n await this.cognito.adminUpdateUserAttributes({\n UserPoolId: this.config.userPoolId,\n Username: username,\n UserAttributes: userAttributes\n });\n }\n\n async deleteUser(username: string): Promise<void> {\n await this.cognito.adminDeleteUser({\n UserPoolId: this.config.userPoolId,\n Username: username\n });\n }\n}\n\nexport const CognitoService = ServiceAbstraction.createImplementation({\n implementation: CognitoServiceImpl,\n dependencies: [CognitoConfig]\n});\n"],"names":["CognitoServiceImpl","config","CognitoIdentityProvider","username","response","attributes","attribute","error","params","createUserParams","password","userAttributes","Object","name","value","CognitoService","ServiceAbstraction","CognitoConfig"],"mappings":";;AAIA,MAAMA;IAGF,YAAoBC,MAA+B,CAAE;aAAjCA,MAAM,GAANA;QAChB,IAAI,CAAC,OAAO,GAAG,IAAIC,wBAAwB;YAAE,QAAQD,OAAO,MAAM;QAAC;IACvE;IAEA,MAAM,QAAQE,QAAgB,EAA2C;QACrE,IAAI;YACA,MAAMC,WAAW,MAAM,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC;gBAC7C,UAAUD;gBACV,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YACtC;YAEA,MAAME,aAAqC,CAAC;YAC5C,KAAK,MAAMC,aAAaF,SAAS,cAAc,IAAI,EAAE,CACjD,IAAIE,UAAU,IAAI,EACdD,UAAU,CAACC,UAAU,IAAI,CAAC,GAAGA,UAAU,KAAK,IAAI;YAIxD,OAAO;gBAAE,UAAUF,SAAS,QAAQ,IAAID;gBAAUE;YAAW;QACjE,EAAE,OAAOE,OAAO;YACZ,IAAKA,AAAyB,4BAAzBA,MAAgB,IAAI,EACrB,OAAO;YAEX,MAAMA;QACV;IACJ;IAEA,MAAM,WAAWC,MAIhB,EAAiB;QACd,MAAMC,mBAA2C;YAC7C,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUD,OAAO,QAAQ;YACzB,wBAAwB,EAAE;YAC1B,oBAAoB;YACpB,eAAe;YACf,mBAAmBA,OAAO,iBAAiB;YAC3C,gBAAgB;gBACZ;oBACI,MAAM;oBACN,OAAOA,OAAO,UAAU,CAAC,SAAS,IAAI;gBAC1C;gBACA;oBACI,MAAM;oBACN,OAAOA,OAAO,UAAU,CAAC,UAAU,IAAI;gBAC3C;gBACA;oBACI,MAAM;oBACN,OAAOA,OAAO,UAAU,CAAC,iBAAiB;gBAC9C;gBACA;oBACI,MAAM;oBACN,OAAOA,OAAO,UAAU,CAAC,KAAK;gBAClC;gBACA;oBACI,MAAM;oBACN,OAAOA,OAAO,UAAU,CAAC,QAAQ;gBACrC;aACH;QACL;QAEA,MAAM,IAAI,CAAC,OAAO,CAAC,eAAe,CAACC;IACvC;IAEA,MAAM,iBAAiBN,QAAgB,EAAiB;QACpD,MAAM,IAAI,CAAC,OAAO,CAAC,yBAAyB,CAAC;YACzC,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUA;YACV,gBAAgB;gBACZ;oBACI,MAAM;oBACN,OAAO;gBACX;aACH;QACL;IACJ;IAEA,MAAM,qBAAqBA,QAAgB,EAAEO,QAAgB,EAAiB;QAC1E,MAAM,IAAI,CAAC,OAAO,CAAC,oBAAoB,CAAC;YACpC,WAAW;YACX,UAAUA;YACV,UAAUP;YACV,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;QACtC;IACJ;IAEA,MAAM,qBACFA,QAAgB,EAChBE,UAAkC,EACrB;QACb,MAAMM,iBAAiBC,OAAO,OAAO,CAACP,YAAY,GAAG,CAAC,CAAC,CAACQ,MAAMC,MAAM,GAAM;gBACtE,MAAMD;gBACN,OAAOC;YACX;QAEA,MAAM,IAAI,CAAC,OAAO,CAAC,yBAAyB,CAAC;YACzC,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUX;YACV,gBAAgBQ;QACpB;IACJ;IAEA,MAAM,WAAWR,QAAgB,EAAiB;QAC9C,MAAM,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC;YAC/B,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUA;QACd;IACJ;AACJ;AAEO,MAAMY,gCAAiBC,eAAAA,oBAAuC,CAAC;IAClE,gBAAgBhB;IAChB,cAAc;QAACiB;KAAc;AACjC"}
1
+ {"version":3,"file":"api/features/CognitoService/CognitoService.js","sources":["../../../../src/api/features/CognitoService/CognitoService.ts"],"sourcesContent":["import type { AdminCreateUserRequest } from \"@webiny/aws-sdk/client-cognito-identity-provider/index.js\";\nimport { CognitoIdentityProvider } from \"@webiny/aws-sdk/client-cognito-identity-provider/index.js\";\nimport { CognitoConfig, CognitoService as ServiceAbstraction } from \"./abstractions.js\";\nimport { adminDeleteSoftwareToken } from \"./adminDeleteSoftwareToken.js\";\n\nclass CognitoServiceImpl implements ServiceAbstraction.Interface {\n private cognito: CognitoIdentityProvider;\n\n constructor(private config: CognitoConfig.Interface) {\n this.cognito = new CognitoIdentityProvider({ region: config.region });\n }\n\n async getUser(username: string): Promise<ServiceAbstraction.User | null> {\n try {\n const response = await this.cognito.adminGetUser({\n Username: username,\n UserPoolId: this.config.userPoolId\n });\n\n const attributes: Record<string, string> = {};\n for (const attribute of response.UserAttributes ?? []) {\n if (attribute.Name) {\n attributes[attribute.Name] = attribute.Value ?? \"\";\n }\n }\n\n return { username: response.Username ?? username, attributes };\n } catch (error) {\n if ((error as Error).name === \"UserNotFoundException\") {\n return null;\n }\n throw error;\n }\n }\n\n async createUser(params: {\n username: string;\n temporaryPassword: string;\n attributes: ServiceAbstraction.UserAttributes;\n }): Promise<void> {\n const createUserParams: AdminCreateUserRequest = {\n UserPoolId: this.config.userPoolId,\n Username: params.username,\n DesiredDeliveryMediums: [],\n ForceAliasCreation: false,\n MessageAction: \"SUPPRESS\",\n TemporaryPassword: params.temporaryPassword,\n UserAttributes: [\n {\n Name: \"given_name\",\n Value: params.attributes.givenName || \"\"\n },\n {\n Name: \"family_name\",\n Value: params.attributes.familyName || \"\"\n },\n {\n Name: \"preferred_username\",\n Value: params.attributes.preferredUsername\n },\n {\n Name: \"email\",\n Value: params.attributes.email\n },\n {\n Name: \"custom:id\",\n Value: params.attributes.customId\n }\n ]\n };\n\n await this.cognito.adminCreateUser(createUserParams);\n }\n\n async setEmailVerified(username: string): Promise<void> {\n await this.cognito.adminUpdateUserAttributes({\n UserPoolId: this.config.userPoolId,\n Username: username,\n UserAttributes: [\n {\n Name: \"email_verified\",\n Value: \"true\"\n }\n ]\n });\n }\n\n async setPermanentPassword(username: string, password: string): Promise<void> {\n await this.cognito.adminSetUserPassword({\n Permanent: true,\n Password: password,\n Username: username,\n UserPoolId: this.config.userPoolId\n });\n }\n\n async updateUserAttributes(\n username: string,\n attributes: Record<string, string>\n ): Promise<void> {\n const userAttributes = Object.entries(attributes).map(([name, value]) => ({\n Name: name,\n Value: value\n }));\n\n await this.cognito.adminUpdateUserAttributes({\n UserPoolId: this.config.userPoolId,\n Username: username,\n UserAttributes: userAttributes\n });\n }\n\n async deleteUser(username: string): Promise<void> {\n await this.cognito.adminDeleteUser({\n UserPoolId: this.config.userPoolId,\n Username: username\n });\n }\n\n async resetMfa(username: string): Promise<void> {\n // Deletes the user's TOTP software token, so Cognito asks them to set up TOTP again on\n // their next sign-in. Only turning the factor off (`AdminSetUserMFAPreference`) isn't\n // enough: with MFA required in the pool, Cognito keeps asking for the old token.\n // A signed request, not the SDK command: see `adminDeleteSoftwareToken`.\n await adminDeleteSoftwareToken({\n region: this.config.region,\n userPoolId: this.config.userPoolId,\n username,\n credentials: this.cognito.config.credentials\n });\n }\n}\n\nexport const CognitoService = ServiceAbstraction.createImplementation({\n implementation: CognitoServiceImpl,\n dependencies: [CognitoConfig]\n});\n"],"names":["CognitoServiceImpl","config","CognitoIdentityProvider","username","response","attributes","attribute","error","params","createUserParams","password","userAttributes","Object","name","value","adminDeleteSoftwareToken","CognitoService","ServiceAbstraction","CognitoConfig"],"mappings":";;;AAKA,MAAMA;IAGF,YAAoBC,MAA+B,CAAE;aAAjCA,MAAM,GAANA;QAChB,IAAI,CAAC,OAAO,GAAG,IAAIC,wBAAwB;YAAE,QAAQD,OAAO,MAAM;QAAC;IACvE;IAEA,MAAM,QAAQE,QAAgB,EAA2C;QACrE,IAAI;YACA,MAAMC,WAAW,MAAM,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC;gBAC7C,UAAUD;gBACV,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YACtC;YAEA,MAAME,aAAqC,CAAC;YAC5C,KAAK,MAAMC,aAAaF,SAAS,cAAc,IAAI,EAAE,CACjD,IAAIE,UAAU,IAAI,EACdD,UAAU,CAACC,UAAU,IAAI,CAAC,GAAGA,UAAU,KAAK,IAAI;YAIxD,OAAO;gBAAE,UAAUF,SAAS,QAAQ,IAAID;gBAAUE;YAAW;QACjE,EAAE,OAAOE,OAAO;YACZ,IAAKA,AAAyB,4BAAzBA,MAAgB,IAAI,EACrB,OAAO;YAEX,MAAMA;QACV;IACJ;IAEA,MAAM,WAAWC,MAIhB,EAAiB;QACd,MAAMC,mBAA2C;YAC7C,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUD,OAAO,QAAQ;YACzB,wBAAwB,EAAE;YAC1B,oBAAoB;YACpB,eAAe;YACf,mBAAmBA,OAAO,iBAAiB;YAC3C,gBAAgB;gBACZ;oBACI,MAAM;oBACN,OAAOA,OAAO,UAAU,CAAC,SAAS,IAAI;gBAC1C;gBACA;oBACI,MAAM;oBACN,OAAOA,OAAO,UAAU,CAAC,UAAU,IAAI;gBAC3C;gBACA;oBACI,MAAM;oBACN,OAAOA,OAAO,UAAU,CAAC,iBAAiB;gBAC9C;gBACA;oBACI,MAAM;oBACN,OAAOA,OAAO,UAAU,CAAC,KAAK;gBAClC;gBACA;oBACI,MAAM;oBACN,OAAOA,OAAO,UAAU,CAAC,QAAQ;gBACrC;aACH;QACL;QAEA,MAAM,IAAI,CAAC,OAAO,CAAC,eAAe,CAACC;IACvC;IAEA,MAAM,iBAAiBN,QAAgB,EAAiB;QACpD,MAAM,IAAI,CAAC,OAAO,CAAC,yBAAyB,CAAC;YACzC,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUA;YACV,gBAAgB;gBACZ;oBACI,MAAM;oBACN,OAAO;gBACX;aACH;QACL;IACJ;IAEA,MAAM,qBAAqBA,QAAgB,EAAEO,QAAgB,EAAiB;QAC1E,MAAM,IAAI,CAAC,OAAO,CAAC,oBAAoB,CAAC;YACpC,WAAW;YACX,UAAUA;YACV,UAAUP;YACV,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;QACtC;IACJ;IAEA,MAAM,qBACFA,QAAgB,EAChBE,UAAkC,EACrB;QACb,MAAMM,iBAAiBC,OAAO,OAAO,CAACP,YAAY,GAAG,CAAC,CAAC,CAACQ,MAAMC,MAAM,GAAM;gBACtE,MAAMD;gBACN,OAAOC;YACX;QAEA,MAAM,IAAI,CAAC,OAAO,CAAC,yBAAyB,CAAC;YACzC,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUX;YACV,gBAAgBQ;QACpB;IACJ;IAEA,MAAM,WAAWR,QAAgB,EAAiB;QAC9C,MAAM,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC;YAC/B,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUA;QACd;IACJ;IAEA,MAAM,SAASA,QAAgB,EAAiB;QAK5C,MAAMY,yBAAyB;YAC3B,QAAQ,IAAI,CAAC,MAAM,CAAC,MAAM;YAC1B,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClCZ;YACA,aAAa,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW;QAChD;IACJ;AACJ;AAEO,MAAMa,gCAAiBC,eAAAA,oBAAuC,CAAC;IAClE,gBAAgBjB;IAChB,cAAc;QAACkB;KAAc;AACjC"}
@@ -51,6 +51,11 @@ export interface ICognitoService {
51
51
  * Delete a user from Cognito User Pool
52
52
  */
53
53
  deleteUser(username: string): Promise<void>;
54
+ /**
55
+ * Delete the user's TOTP software token, so they set up MFA again on their next sign-in.
56
+ * A user without a token counts as reset.
57
+ */
58
+ resetMfa(username: string): Promise<void>;
54
59
  }
55
60
  export declare const CognitoService: import("@webiny/di").Abstraction<ICognitoService>;
56
61
  export declare namespace CognitoService {
@@ -1 +1 @@
1
- {"version":3,"file":"api/features/CognitoService/abstractions.js","sources":["../../../../src/api/features/CognitoService/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { BaseUserAttributes } from \"@webiny/api-core/types/users.js\";\n\nexport interface AttributeGetter {\n (user: BaseUserAttributes): string;\n}\n\nexport interface ICognitoConfig {\n region: string;\n userPoolId: string;\n}\n\nexport const CognitoConfig = createAbstraction<ICognitoConfig>(\"CognitoConfig\");\n\nexport namespace CognitoConfig {\n export type Interface = ICognitoConfig;\n}\n\n// Cognito Service\n\nexport interface CognitoUserAttributes {\n givenName?: string;\n familyName?: string;\n preferredUsername: string;\n email: string;\n customId: string;\n}\n\nexport interface CognitoUser {\n username: string;\n /** The account's attributes by name: `email`, `given_name`, `custom:id`, ... */\n attributes: Record<string, string>;\n}\n\nexport interface ICognitoService {\n /**\n * Load a user from Cognito User Pool, or `null` if there's no account with this username.\n */\n getUser(username: string): Promise<CognitoUser | null>;\n\n /**\n * Create a new user in Cognito User Pool\n */\n createUser(params: {\n username: string;\n temporaryPassword: string;\n attributes: CognitoUserAttributes;\n }): Promise<void>;\n\n /**\n * Set email as verified for a user\n */\n setEmailVerified(username: string): Promise<void>;\n\n /**\n * Set a permanent password for a user\n */\n setPermanentPassword(username: string, password: string): Promise<void>;\n\n /**\n * Update user attributes in Cognito\n */\n updateUserAttributes(username: string, attributes: Record<string, string>): Promise<void>;\n\n /**\n * Delete a user from Cognito User Pool\n */\n deleteUser(username: string): Promise<void>;\n}\n\nexport const CognitoService = createAbstraction<ICognitoService>(\"CognitoService\");\nexport namespace CognitoService {\n export type Interface = ICognitoService;\n export type UserAttributes = CognitoUserAttributes;\n export type User = CognitoUser;\n}\n"],"names":["CognitoConfig","createAbstraction","CognitoService"],"mappings":";AAYO,MAAMA,gBAAgBC,kBAAkC;AA0DxD,MAAMC,iBAAiBD,kBAAmC"}
1
+ {"version":3,"file":"api/features/CognitoService/abstractions.js","sources":["../../../../src/api/features/CognitoService/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { BaseUserAttributes } from \"@webiny/api-core/types/users.js\";\n\nexport interface AttributeGetter {\n (user: BaseUserAttributes): string;\n}\n\nexport interface ICognitoConfig {\n region: string;\n userPoolId: string;\n}\n\nexport const CognitoConfig = createAbstraction<ICognitoConfig>(\"CognitoConfig\");\n\nexport namespace CognitoConfig {\n export type Interface = ICognitoConfig;\n}\n\n// Cognito Service\n\nexport interface CognitoUserAttributes {\n givenName?: string;\n familyName?: string;\n preferredUsername: string;\n email: string;\n customId: string;\n}\n\nexport interface CognitoUser {\n username: string;\n /** The account's attributes by name: `email`, `given_name`, `custom:id`, ... */\n attributes: Record<string, string>;\n}\n\nexport interface ICognitoService {\n /**\n * Load a user from Cognito User Pool, or `null` if there's no account with this username.\n */\n getUser(username: string): Promise<CognitoUser | null>;\n\n /**\n * Create a new user in Cognito User Pool\n */\n createUser(params: {\n username: string;\n temporaryPassword: string;\n attributes: CognitoUserAttributes;\n }): Promise<void>;\n\n /**\n * Set email as verified for a user\n */\n setEmailVerified(username: string): Promise<void>;\n\n /**\n * Set a permanent password for a user\n */\n setPermanentPassword(username: string, password: string): Promise<void>;\n\n /**\n * Update user attributes in Cognito\n */\n updateUserAttributes(username: string, attributes: Record<string, string>): Promise<void>;\n\n /**\n * Delete a user from Cognito User Pool\n */\n deleteUser(username: string): Promise<void>;\n\n /**\n * Delete the user's TOTP software token, so they set up MFA again on their next sign-in.\n * A user without a token counts as reset.\n */\n resetMfa(username: string): Promise<void>;\n}\n\nexport const CognitoService = createAbstraction<ICognitoService>(\"CognitoService\");\nexport namespace CognitoService {\n export type Interface = ICognitoService;\n export type UserAttributes = CognitoUserAttributes;\n export type User = CognitoUser;\n}\n"],"names":["CognitoConfig","createAbstraction","CognitoService"],"mappings":";AAYO,MAAMA,gBAAgBC,kBAAkC;AAgExD,MAAMC,iBAAiBD,kBAAmC"}
@@ -0,0 +1,16 @@
1
+ import type { AwsCredentialIdentity, Provider } from "@smithy/types";
2
+ /**
3
+ * Calls Cognito's `AdminDeleteSoftwareToken` as a signed HTTP request.
4
+ *
5
+ * Function bundles leave `@aws-sdk/*` out (`createRsbuildConfig.js`), so the API Lambda uses the
6
+ * AWS SDK built into the Lambda runtime, and that SDK doesn't have `AdminDeleteSoftwareTokenCommand`
7
+ * yet. `@smithy/*` is bundled, so this works on any runtime. Switch to the SDK command once the
8
+ * Lambda runtime has it.
9
+ */
10
+ export interface AdminDeleteSoftwareTokenParams {
11
+ region: string;
12
+ userPoolId: string;
13
+ username: string;
14
+ credentials: AwsCredentialIdentity | Provider<AwsCredentialIdentity>;
15
+ }
16
+ export declare const adminDeleteSoftwareToken: (params: AdminDeleteSoftwareTokenParams) => Promise<void>;
@@ -0,0 +1,69 @@
1
+ import { createHash, createHmac } from "node:crypto";
2
+ import { SignatureV4 } from "@smithy/signature-v4";
3
+ const SERVICE = "cognito-idp";
4
+ const TARGET = "AWSCognitoIdentityProviderService.AdminDeleteSoftwareToken";
5
+ const adminDeleteSoftwareToken = async (params)=>{
6
+ const hostname = `${SERVICE}.${params.region}.amazonaws.com`;
7
+ const signer = new SignatureV4({
8
+ service: SERVICE,
9
+ region: params.region,
10
+ credentials: params.credentials,
11
+ sha256: Sha256
12
+ });
13
+ const request = await signer.sign({
14
+ method: "POST",
15
+ protocol: "https:",
16
+ hostname,
17
+ path: "/",
18
+ query: {},
19
+ headers: {
20
+ host: hostname,
21
+ "content-type": "application/x-amz-json-1.1",
22
+ "x-amz-target": TARGET
23
+ },
24
+ body: JSON.stringify({
25
+ UserPoolId: params.userPoolId,
26
+ Username: params.username
27
+ })
28
+ });
29
+ const response = await fetch(`https://${hostname}/`, {
30
+ method: "POST",
31
+ headers: request.headers,
32
+ body: request.body
33
+ });
34
+ if (response.ok) return;
35
+ const error = await toCognitoError(response);
36
+ if (isNoSoftwareTokenError(error)) return;
37
+ throw error;
38
+ };
39
+ const isNoSoftwareTokenError = (error)=>"ResourceNotFoundException" === error.name && /software token mfa has not been configured/i.test(error.message);
40
+ const toCognitoError = async (response)=>{
41
+ const text = await response.text();
42
+ let body = {};
43
+ try {
44
+ body = JSON.parse(text);
45
+ } catch {}
46
+ const type = (body.__type ?? "").split("#").pop() || `HTTP${response.status}`;
47
+ const error = new Error(body.message ?? body.Message ?? (text || response.statusText));
48
+ error.name = type;
49
+ return error;
50
+ };
51
+ const toBuffer = (data)=>{
52
+ if ("string" == typeof data) return Buffer.from(data, "utf8");
53
+ if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
54
+ return Buffer.from(data);
55
+ };
56
+ class Sha256 {
57
+ constructor(secret){
58
+ this.hash = secret ? createHmac("sha256", toBuffer(secret)) : createHash("sha256");
59
+ }
60
+ update(data) {
61
+ this.hash.update(toBuffer(data));
62
+ }
63
+ async digest() {
64
+ return new Uint8Array(this.hash.digest());
65
+ }
66
+ }
67
+ export { adminDeleteSoftwareToken };
68
+
69
+ //# sourceMappingURL=adminDeleteSoftwareToken.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api/features/CognitoService/adminDeleteSoftwareToken.js","sources":["../../../../src/api/features/CognitoService/adminDeleteSoftwareToken.ts"],"sourcesContent":["import { createHash, createHmac } from \"node:crypto\";\nimport type { Hash as HashInterface } from \"@smithy/types\";\nimport type { AwsCredentialIdentity, Provider, SourceData } from \"@smithy/types\";\nimport { SignatureV4 } from \"@smithy/signature-v4\";\n\n/**\n * Calls Cognito's `AdminDeleteSoftwareToken` as a signed HTTP request.\n *\n * Function bundles leave `@aws-sdk/*` out (`createRsbuildConfig.js`), so the API Lambda uses the\n * AWS SDK built into the Lambda runtime, and that SDK doesn't have `AdminDeleteSoftwareTokenCommand`\n * yet. `@smithy/*` is bundled, so this works on any runtime. Switch to the SDK command once the\n * Lambda runtime has it.\n */\nexport interface AdminDeleteSoftwareTokenParams {\n region: string;\n userPoolId: string;\n username: string;\n credentials: AwsCredentialIdentity | Provider<AwsCredentialIdentity>;\n}\n\nconst SERVICE = \"cognito-idp\";\nconst TARGET = \"AWSCognitoIdentityProviderService.AdminDeleteSoftwareToken\";\n\nexport const adminDeleteSoftwareToken = async (\n params: AdminDeleteSoftwareTokenParams\n): Promise<void> => {\n const hostname = `${SERVICE}.${params.region}.amazonaws.com`;\n\n const signer = new SignatureV4({\n service: SERVICE,\n region: params.region,\n credentials: params.credentials,\n sha256: Sha256\n });\n\n const request = await signer.sign({\n method: \"POST\",\n protocol: \"https:\",\n hostname,\n path: \"/\",\n query: {},\n headers: {\n host: hostname,\n \"content-type\": \"application/x-amz-json-1.1\",\n \"x-amz-target\": TARGET\n },\n body: JSON.stringify({ UserPoolId: params.userPoolId, Username: params.username })\n });\n\n const response = await fetch(`https://${hostname}/`, {\n method: \"POST\",\n headers: request.headers,\n body: request.body\n });\n\n if (response.ok) {\n return;\n }\n\n const error = await toCognitoError(response);\n if (isNoSoftwareTokenError(error)) {\n // The user never set up TOTP, so there's no token to delete. That's already the state a\n // delete leads to: they set up TOTP on their next sign-in.\n return;\n }\n throw error;\n};\n\n/**\n * Cognito's answer for a user without a TOTP token:\n * `ResourceNotFoundException: Software token MFA has not been configured for this user.`\n * The name alone also covers a missing user pool, so the message must match too.\n */\nconst isNoSoftwareTokenError = (error: Error): boolean => {\n return (\n error.name === \"ResourceNotFoundException\" &&\n /software token mfa has not been configured/i.test(error.message)\n );\n};\n\n/**\n * Cognito answers a failed call with `{ \"__type\": \"...#UserNotFoundException\", \"message\": \"...\" }`.\n * The error gets the exception's name, as the SDK would give it.\n */\nconst toCognitoError = async (response: Response): Promise<Error> => {\n const text = await response.text();\n\n let body: { __type?: string; message?: string; Message?: string } = {};\n try {\n body = JSON.parse(text);\n } catch {\n // Not JSON: keep the raw text as the message.\n }\n\n const type = (body.__type ?? \"\").split(\"#\").pop() || `HTTP${response.status}`;\n const error = new Error(body.message ?? body.Message ?? (text || response.statusText));\n error.name = type;\n return error;\n};\n\nconst toBuffer = (data: SourceData): Buffer => {\n if (typeof data === \"string\") {\n return Buffer.from(data, \"utf8\");\n }\n if (ArrayBuffer.isView(data)) {\n return Buffer.from(data.buffer, data.byteOffset, data.byteLength);\n }\n return Buffer.from(data);\n};\n\n/**\n * SHA-256 (or HMAC-SHA-256 with a secret) for the signer, on Node's own crypto.\n */\nclass Sha256 implements HashInterface {\n private readonly hash;\n\n constructor(secret?: SourceData) {\n this.hash = secret ? createHmac(\"sha256\", toBuffer(secret)) : createHash(\"sha256\");\n }\n\n update(data: SourceData): void {\n this.hash.update(toBuffer(data));\n }\n\n async digest(): Promise<Uint8Array> {\n return new Uint8Array(this.hash.digest());\n }\n}\n"],"names":["SERVICE","TARGET","adminDeleteSoftwareToken","params","hostname","signer","SignatureV4","Sha256","request","JSON","response","fetch","error","toCognitoError","isNoSoftwareTokenError","text","body","type","Error","toBuffer","data","Buffer","ArrayBuffer","secret","createHmac","createHash","Uint8Array"],"mappings":";;AAoBA,MAAMA,UAAU;AAChB,MAAMC,SAAS;AAER,MAAMC,2BAA2B,OACpCC;IAEA,MAAMC,WAAW,GAAGJ,QAAQ,CAAC,EAAEG,OAAO,MAAM,CAAC,cAAc,CAAC;IAE5D,MAAME,SAAS,IAAIC,YAAY;QAC3B,SAASN;QACT,QAAQG,OAAO,MAAM;QACrB,aAAaA,OAAO,WAAW;QAC/B,QAAQI;IACZ;IAEA,MAAMC,UAAU,MAAMH,OAAO,IAAI,CAAC;QAC9B,QAAQ;QACR,UAAU;QACVD;QACA,MAAM;QACN,OAAO,CAAC;QACR,SAAS;YACL,MAAMA;YACN,gBAAgB;YAChB,gBAAgBH;QACpB;QACA,MAAMQ,KAAK,SAAS,CAAC;YAAE,YAAYN,OAAO,UAAU;YAAE,UAAUA,OAAO,QAAQ;QAAC;IACpF;IAEA,MAAMO,WAAW,MAAMC,MAAM,CAAC,QAAQ,EAAEP,SAAS,CAAC,CAAC,EAAE;QACjD,QAAQ;QACR,SAASI,QAAQ,OAAO;QACxB,MAAMA,QAAQ,IAAI;IACtB;IAEA,IAAIE,SAAS,EAAE,EACX;IAGJ,MAAME,QAAQ,MAAMC,eAAeH;IACnC,IAAII,uBAAuBF,QAGvB;IAEJ,MAAMA;AACV;AAOA,MAAME,yBAAyB,CAACF,QAExBA,AAAe,gCAAfA,MAAM,IAAI,IACV,8CAA8C,IAAI,CAACA,MAAM,OAAO;AAQxE,MAAMC,iBAAiB,OAAOH;IAC1B,MAAMK,OAAO,MAAML,SAAS,IAAI;IAEhC,IAAIM,OAAgE,CAAC;IACrE,IAAI;QACAA,OAAOP,KAAK,KAAK,CAACM;IACtB,EAAE,OAAM,CAER;IAEA,MAAME,OAAQD,AAAAA,CAAAA,KAAK,MAAM,IAAI,EAAC,EAAG,KAAK,CAAC,KAAK,GAAG,MAAM,CAAC,IAAI,EAAEN,SAAS,MAAM,EAAE;IAC7E,MAAME,QAAQ,IAAIM,MAAMF,KAAK,OAAO,IAAIA,KAAK,OAAO,IAAKD,CAAAA,QAAQL,SAAS,UAAS;IACnFE,MAAM,IAAI,GAAGK;IACb,OAAOL;AACX;AAEA,MAAMO,WAAW,CAACC;IACd,IAAI,AAAgB,YAAhB,OAAOA,MACP,OAAOC,OAAO,IAAI,CAACD,MAAM;IAE7B,IAAIE,YAAY,MAAM,CAACF,OACnB,OAAOC,OAAO,IAAI,CAACD,KAAK,MAAM,EAAEA,KAAK,UAAU,EAAEA,KAAK,UAAU;IAEpE,OAAOC,OAAO,IAAI,CAACD;AACvB;AAKA,MAAMb;IAGF,YAAYgB,MAAmB,CAAE;QAC7B,IAAI,CAAC,IAAI,GAAGA,SAASC,WAAW,UAAUL,SAASI,WAAWE,WAAW;IAC7E;IAEA,OAAOL,IAAgB,EAAQ;QAC3B,IAAI,CAAC,IAAI,CAAC,MAAM,CAACD,SAASC;IAC9B;IAEA,MAAM,SAA8B;QAChC,OAAO,IAAIM,WAAW,IAAI,CAAC,IAAI,CAAC,MAAM;IAC1C;AACJ"}
@@ -0,0 +1,91 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { adminDeleteSoftwareToken } from "./adminDeleteSoftwareToken.js";
3
+ const params = {
4
+ region: "eu-central-1",
5
+ userPoolId: "eu-central-1_pool",
6
+ username: "user-1",
7
+ credentials: async ()=>({
8
+ accessKeyId: "AKIDEXAMPLE",
9
+ secretAccessKey: "secret",
10
+ sessionToken: "session-token"
11
+ })
12
+ };
13
+ describe("adminDeleteSoftwareToken", ()=>{
14
+ const fetchMock = vi.fn();
15
+ beforeEach(()=>{
16
+ vi.useFakeTimers({
17
+ now: new Date("2026-11-07T10:00:00Z"),
18
+ toFake: [
19
+ "Date"
20
+ ]
21
+ });
22
+ fetchMock.mockReset();
23
+ vi.stubGlobal("fetch", fetchMock);
24
+ });
25
+ afterEach(()=>{
26
+ vi.useRealTimers();
27
+ vi.unstubAllGlobals();
28
+ });
29
+ it("sends a signed AdminDeleteSoftwareToken request to the pool's region", async ()=>{
30
+ fetchMock.mockResolvedValue(new Response("{}", {
31
+ status: 200
32
+ }));
33
+ await adminDeleteSoftwareToken(params);
34
+ expect(fetchMock).toHaveBeenCalledTimes(1);
35
+ const [url, init] = fetchMock.mock.calls[0];
36
+ expect(url).toBe("https://cognito-idp.eu-central-1.amazonaws.com/");
37
+ expect(init.method).toBe("POST");
38
+ expect(JSON.parse(init.body)).toEqual({
39
+ UserPoolId: "eu-central-1_pool",
40
+ Username: "user-1"
41
+ });
42
+ const headers = init.headers;
43
+ expect(headers["x-amz-target"]).toBe("AWSCognitoIdentityProviderService.AdminDeleteSoftwareToken");
44
+ expect(headers["content-type"]).toBe("application/x-amz-json-1.1");
45
+ expect(headers["x-amz-date"]).toBe("20261107T100000Z");
46
+ expect(headers["x-amz-security-token"]).toBe("session-token");
47
+ expect(headers["authorization"]).toMatch(/^AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE\/20261107\/eu-central-1\/cognito-idp\/aws4_request, SignedHeaders=[^,]*x-amz-target[^,]*, Signature=[0-9a-f]{64}$/);
48
+ });
49
+ it("throws Cognito's error with the exception's name and message", async ()=>{
50
+ fetchMock.mockResolvedValue(new Response(JSON.stringify({
51
+ __type: "com.amazonaws.cognito#UserNotFoundException",
52
+ message: "User does not exist."
53
+ }), {
54
+ status: 400
55
+ }));
56
+ const error = await adminDeleteSoftwareToken(params).catch((e)=>e);
57
+ expect(error).toBeInstanceOf(Error);
58
+ expect(error.name).toBe("UserNotFoundException");
59
+ expect(error.message).toBe("User does not exist.");
60
+ });
61
+ it("treats a user without a TOTP token as done", async ()=>{
62
+ fetchMock.mockResolvedValue(new Response(JSON.stringify({
63
+ __type: "ResourceNotFoundException",
64
+ message: "Software token MFA has not been configured for this user."
65
+ }), {
66
+ status: 400
67
+ }));
68
+ await expect(adminDeleteSoftwareToken(params)).resolves.toBeUndefined();
69
+ });
70
+ it("still throws other ResourceNotFoundException errors", async ()=>{
71
+ fetchMock.mockResolvedValue(new Response(JSON.stringify({
72
+ __type: "ResourceNotFoundException",
73
+ message: "User pool eu-central-1_pool does not exist."
74
+ }), {
75
+ status: 400
76
+ }));
77
+ const error = await adminDeleteSoftwareToken(params).catch((e)=>e);
78
+ expect(error.name).toBe("ResourceNotFoundException");
79
+ expect(error.message).toBe("User pool eu-central-1_pool does not exist.");
80
+ });
81
+ it("keeps the raw text when Cognito's error isn't JSON", async ()=>{
82
+ fetchMock.mockResolvedValue(new Response("Service Unavailable", {
83
+ status: 503
84
+ }));
85
+ const error = await adminDeleteSoftwareToken(params).catch((e)=>e);
86
+ expect(error.name).toBe("HTTP503");
87
+ expect(error.message).toBe("Service Unavailable");
88
+ });
89
+ });
90
+
91
+ //# sourceMappingURL=adminDeleteSoftwareToken.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api/features/CognitoService/adminDeleteSoftwareToken.test.js","sources":["../../../../src/api/features/CognitoService/adminDeleteSoftwareToken.test.ts"],"sourcesContent":["import { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\nimport { adminDeleteSoftwareToken } from \"./adminDeleteSoftwareToken.js\";\n\nconst params = {\n region: \"eu-central-1\",\n userPoolId: \"eu-central-1_pool\",\n username: \"user-1\",\n credentials: async () => ({\n accessKeyId: \"AKIDEXAMPLE\",\n secretAccessKey: \"secret\",\n sessionToken: \"session-token\"\n })\n};\n\ndescribe(\"adminDeleteSoftwareToken\", () => {\n const fetchMock = vi.fn();\n\n beforeEach(() => {\n vi.useFakeTimers({ now: new Date(\"2026-11-07T10:00:00Z\"), toFake: [\"Date\"] });\n fetchMock.mockReset();\n vi.stubGlobal(\"fetch\", fetchMock);\n });\n\n afterEach(() => {\n vi.useRealTimers();\n vi.unstubAllGlobals();\n });\n\n it(\"sends a signed AdminDeleteSoftwareToken request to the pool's region\", async () => {\n fetchMock.mockResolvedValue(new Response(\"{}\", { status: 200 }));\n\n await adminDeleteSoftwareToken(params);\n\n expect(fetchMock).toHaveBeenCalledTimes(1);\n const [url, init] = fetchMock.mock.calls[0];\n expect(url).toBe(\"https://cognito-idp.eu-central-1.amazonaws.com/\");\n expect(init.method).toBe(\"POST\");\n expect(JSON.parse(init.body)).toEqual({\n UserPoolId: \"eu-central-1_pool\",\n Username: \"user-1\"\n });\n\n const headers = init.headers as Record<string, string>;\n expect(headers[\"x-amz-target\"]).toBe(\n \"AWSCognitoIdentityProviderService.AdminDeleteSoftwareToken\"\n );\n expect(headers[\"content-type\"]).toBe(\"application/x-amz-json-1.1\");\n expect(headers[\"x-amz-date\"]).toBe(\"20261107T100000Z\");\n expect(headers[\"x-amz-security-token\"]).toBe(\"session-token\");\n expect(headers[\"authorization\"]).toMatch(\n /^AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE\\/20261107\\/eu-central-1\\/cognito-idp\\/aws4_request, SignedHeaders=[^,]*x-amz-target[^,]*, Signature=[0-9a-f]{64}$/\n );\n });\n\n it(\"throws Cognito's error with the exception's name and message\", async () => {\n fetchMock.mockResolvedValue(\n new Response(\n JSON.stringify({\n __type: \"com.amazonaws.cognito#UserNotFoundException\",\n message: \"User does not exist.\"\n }),\n { status: 400 }\n )\n );\n\n const error = await adminDeleteSoftwareToken(params).catch(e => e);\n\n expect(error).toBeInstanceOf(Error);\n expect(error.name).toBe(\"UserNotFoundException\");\n expect(error.message).toBe(\"User does not exist.\");\n });\n\n it(\"treats a user without a TOTP token as done\", async () => {\n fetchMock.mockResolvedValue(\n new Response(\n JSON.stringify({\n __type: \"ResourceNotFoundException\",\n message: \"Software token MFA has not been configured for this user.\"\n }),\n { status: 400 }\n )\n );\n\n await expect(adminDeleteSoftwareToken(params)).resolves.toBeUndefined();\n });\n\n it(\"still throws other ResourceNotFoundException errors\", async () => {\n fetchMock.mockResolvedValue(\n new Response(\n JSON.stringify({\n __type: \"ResourceNotFoundException\",\n message: \"User pool eu-central-1_pool does not exist.\"\n }),\n { status: 400 }\n )\n );\n\n const error = await adminDeleteSoftwareToken(params).catch(e => e);\n\n expect(error.name).toBe(\"ResourceNotFoundException\");\n expect(error.message).toBe(\"User pool eu-central-1_pool does not exist.\");\n });\n\n it(\"keeps the raw text when Cognito's error isn't JSON\", async () => {\n fetchMock.mockResolvedValue(new Response(\"Service Unavailable\", { status: 503 }));\n\n const error = await adminDeleteSoftwareToken(params).catch(e => e);\n\n expect(error.name).toBe(\"HTTP503\");\n expect(error.message).toBe(\"Service Unavailable\");\n });\n});\n"],"names":["params","describe","fetchMock","vi","beforeEach","Date","afterEach","it","Response","adminDeleteSoftwareToken","expect","url","init","JSON","headers","error","e","Error"],"mappings":";;AAGA,MAAMA,SAAS;IACX,QAAQ;IACR,YAAY;IACZ,UAAU;IACV,aAAa,UAAa;YACtB,aAAa;YACb,iBAAiB;YACjB,cAAc;QAClB;AACJ;AAEAC,SAAS,4BAA4B;IACjC,MAAMC,YAAYC,GAAG,EAAE;IAEvBC,WAAW;QACPD,GAAG,aAAa,CAAC;YAAE,KAAK,IAAIE,KAAK;YAAyB,QAAQ;gBAAC;aAAO;QAAC;QAC3EH,UAAU,SAAS;QACnBC,GAAG,UAAU,CAAC,SAASD;IAC3B;IAEAI,UAAU;QACNH,GAAG,aAAa;QAChBA,GAAG,gBAAgB;IACvB;IAEAI,GAAG,wEAAwE;QACvEL,UAAU,iBAAiB,CAAC,IAAIM,SAAS,MAAM;YAAE,QAAQ;QAAI;QAE7D,MAAMC,yBAAyBT;QAE/BU,OAAOR,WAAW,qBAAqB,CAAC;QACxC,MAAM,CAACS,KAAKC,KAAK,GAAGV,UAAU,IAAI,CAAC,KAAK,CAAC,EAAE;QAC3CQ,OAAOC,KAAK,IAAI,CAAC;QACjBD,OAAOE,KAAK,MAAM,EAAE,IAAI,CAAC;QACzBF,OAAOG,KAAK,KAAK,CAACD,KAAK,IAAI,GAAG,OAAO,CAAC;YAClC,YAAY;YACZ,UAAU;QACd;QAEA,MAAME,UAAUF,KAAK,OAAO;QAC5BF,OAAOI,OAAO,CAAC,eAAe,EAAE,IAAI,CAChC;QAEJJ,OAAOI,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC;QACrCJ,OAAOI,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC;QACnCJ,OAAOI,OAAO,CAAC,uBAAuB,EAAE,IAAI,CAAC;QAC7CJ,OAAOI,OAAO,CAAC,gBAAgB,EAAE,OAAO,CACpC;IAER;IAEAP,GAAG,gEAAgE;QAC/DL,UAAU,iBAAiB,CACvB,IAAIM,SACAK,KAAK,SAAS,CAAC;YACX,QAAQ;YACR,SAAS;QACb,IACA;YAAE,QAAQ;QAAI;QAItB,MAAME,QAAQ,MAAMN,yBAAyBT,QAAQ,KAAK,CAACgB,CAAAA,IAAKA;QAEhEN,OAAOK,OAAO,cAAc,CAACE;QAC7BP,OAAOK,MAAM,IAAI,EAAE,IAAI,CAAC;QACxBL,OAAOK,MAAM,OAAO,EAAE,IAAI,CAAC;IAC/B;IAEAR,GAAG,8CAA8C;QAC7CL,UAAU,iBAAiB,CACvB,IAAIM,SACAK,KAAK,SAAS,CAAC;YACX,QAAQ;YACR,SAAS;QACb,IACA;YAAE,QAAQ;QAAI;QAItB,MAAMH,OAAOD,yBAAyBT,SAAS,QAAQ,CAAC,aAAa;IACzE;IAEAO,GAAG,uDAAuD;QACtDL,UAAU,iBAAiB,CACvB,IAAIM,SACAK,KAAK,SAAS,CAAC;YACX,QAAQ;YACR,SAAS;QACb,IACA;YAAE,QAAQ;QAAI;QAItB,MAAME,QAAQ,MAAMN,yBAAyBT,QAAQ,KAAK,CAACgB,CAAAA,IAAKA;QAEhEN,OAAOK,MAAM,IAAI,EAAE,IAAI,CAAC;QACxBL,OAAOK,MAAM,OAAO,EAAE,IAAI,CAAC;IAC/B;IAEAR,GAAG,sDAAsD;QACrDL,UAAU,iBAAiB,CAAC,IAAIM,SAAS,uBAAuB;YAAE,QAAQ;QAAI;QAE9E,MAAMO,QAAQ,MAAMN,yBAAyBT,QAAQ,KAAK,CAACgB,CAAAA,IAAKA;QAEhEN,OAAOK,MAAM,IAAI,EAAE,IAAI,CAAC;QACxBL,OAAOK,MAAM,OAAO,EAAE,IAAI,CAAC;IAC/B;AACJ"}
@@ -0,0 +1,14 @@
1
+ import { Result } from "@webiny/feature/api";
2
+ import { GetUserUseCase } from "@webiny/api-core/features/users/GetUser/index.js";
3
+ import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
4
+ import { ResetUserMfaUseCase as UseCaseAbstraction } from "./abstractions.js";
5
+ import { CognitoService } from "../CognitoService/abstractions.js";
6
+ declare class ResetUserMfaUseCaseImpl implements UseCaseAbstraction.Interface {
7
+ private identityContext;
8
+ private cognitoService;
9
+ private getUserUseCase;
10
+ constructor(identityContext: IdentityContext.Interface, cognitoService: CognitoService.Interface, getUserUseCase: GetUserUseCase.Interface);
11
+ execute(id: string): Promise<Result<void, UseCaseAbstraction.Error>>;
12
+ }
13
+ export declare const ResetUserMfaUseCase: import("@webiny/di").Implementation<typeof ResetUserMfaUseCaseImpl>;
14
+ export {};
@@ -0,0 +1,43 @@
1
+ import { Result, createImplementation } from "@webiny/feature/api";
2
+ import { GetUserUseCase } from "@webiny/api-core/features/users/GetUser/index.js";
3
+ import { NotAuthorizedError } from "@webiny/api-core/features/users/shared/errors.js";
4
+ import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
5
+ import { ResetUserMfaUseCase } from "./abstractions.js";
6
+ import { Username } from "../../domain/Username.js";
7
+ import { CognitoExternalUserError, CognitoResetMfaError } from "../../domain/errors.js";
8
+ import { CognitoService } from "../CognitoService/abstractions.js";
9
+ class ResetUserMfaUseCaseImpl {
10
+ constructor(identityContext, cognitoService, getUserUseCase){
11
+ this.identityContext = identityContext;
12
+ this.cognitoService = cognitoService;
13
+ this.getUserUseCase = getUserUseCase;
14
+ }
15
+ async execute(id) {
16
+ const permission = await this.identityContext.getPermission("adminUsers.user");
17
+ if (!permission) return Result.fail(new NotAuthorizedError());
18
+ const getUserResult = await this.getUserUseCase.execute({
19
+ id
20
+ });
21
+ if (getUserResult.isFail()) return Result.fail(getUserResult.error);
22
+ const user = getUserResult.value;
23
+ if (user.external) return Result.fail(new CognitoExternalUserError(id));
24
+ try {
25
+ await this.cognitoService.resetMfa(Username.fromUser(user));
26
+ return Result.ok();
27
+ } catch (cognitoError) {
28
+ return Result.fail(new CognitoResetMfaError(cognitoError));
29
+ }
30
+ }
31
+ }
32
+ const ResetUserMfaUseCase_ResetUserMfaUseCase = createImplementation({
33
+ abstraction: ResetUserMfaUseCase,
34
+ implementation: ResetUserMfaUseCaseImpl,
35
+ dependencies: [
36
+ IdentityContext,
37
+ CognitoService,
38
+ GetUserUseCase
39
+ ]
40
+ });
41
+ export { ResetUserMfaUseCase_ResetUserMfaUseCase as ResetUserMfaUseCase };
42
+
43
+ //# sourceMappingURL=ResetUserMfaUseCase.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api/features/ResetUserMfa/ResetUserMfaUseCase.js","sources":["../../../../src/api/features/ResetUserMfa/ResetUserMfaUseCase.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { Result } from \"@webiny/feature/api\";\nimport { GetUserUseCase } from \"@webiny/api-core/features/users/GetUser/index.js\";\nimport { NotAuthorizedError } from \"@webiny/api-core/features/users/shared/errors.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { ResetUserMfaUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { Username } from \"~/api/domain/Username.js\";\nimport { CognitoExternalUserError, CognitoResetMfaError } from \"~/api/domain/errors.js\";\nimport { CognitoService } from \"../CognitoService/abstractions.js\";\n\nclass ResetUserMfaUseCaseImpl implements UseCaseAbstraction.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private cognitoService: CognitoService.Interface,\n private getUserUseCase: GetUserUseCase.Interface\n ) {}\n\n async execute(id: string): Promise<Result<void, UseCaseAbstraction.Error>> {\n const permission = await this.identityContext.getPermission(\"adminUsers.user\");\n if (!permission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n const getUserResult = await this.getUserUseCase.execute({ id });\n if (getUserResult.isFail()) {\n return Result.fail(getUserResult.error);\n }\n\n const user = getUserResult.value;\n\n // A federated user signs in through their own identity provider, which handles their MFA.\n if (user.external) {\n return Result.fail(new CognitoExternalUserError(id));\n }\n\n // Unlike changing a shared account's name, email or password, any administrator of one of\n // the person's tenants may reset its MFA: the person can't do it themselves when they can't\n // sign in, and the reset doesn't give the administrator access to the account.\n try {\n await this.cognitoService.resetMfa(Username.fromUser(user));\n\n return Result.ok();\n } catch (cognitoError) {\n return Result.fail(new CognitoResetMfaError(cognitoError as Error));\n }\n }\n}\n\nexport const ResetUserMfaUseCase = createImplementation({\n abstraction: UseCaseAbstraction,\n implementation: ResetUserMfaUseCaseImpl,\n dependencies: [IdentityContext, CognitoService, GetUserUseCase]\n});\n"],"names":["ResetUserMfaUseCaseImpl","identityContext","cognitoService","getUserUseCase","id","permission","Result","NotAuthorizedError","getUserResult","user","CognitoExternalUserError","Username","cognitoError","CognitoResetMfaError","ResetUserMfaUseCase","createImplementation","UseCaseAbstraction","IdentityContext","CognitoService","GetUserUseCase"],"mappings":";;;;;;;;AAUA,MAAMA;IACF,YACYC,eAA0C,EAC1CC,cAAwC,EACxCC,cAAwC,CAClD;aAHUF,eAAe,GAAfA;aACAC,cAAc,GAAdA;aACAC,cAAc,GAAdA;IACT;IAEH,MAAM,QAAQC,EAAU,EAAmD;QACvE,MAAMC,aAAa,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC;QAC5D,IAAI,CAACA,YACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAG3B,MAAMC,gBAAgB,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC;YAAEJ;QAAG;QAC7D,IAAII,cAAc,MAAM,IACpB,OAAOF,OAAO,IAAI,CAACE,cAAc,KAAK;QAG1C,MAAMC,OAAOD,cAAc,KAAK;QAGhC,IAAIC,KAAK,QAAQ,EACb,OAAOH,OAAO,IAAI,CAAC,IAAII,yBAAyBN;QAMpD,IAAI;YACA,MAAM,IAAI,CAAC,cAAc,CAAC,QAAQ,CAACO,SAAS,QAAQ,CAACF;YAErD,OAAOH,OAAO,EAAE;QACpB,EAAE,OAAOM,cAAc;YACnB,OAAON,OAAO,IAAI,CAAC,IAAIO,qBAAqBD;QAChD;IACJ;AACJ;AAEO,MAAME,0CAAsBC,qBAAqB;IACpD,aAAaC;IACb,gBAAgBhB;IAChB,cAAc;QAACiB;QAAiBC;QAAgBC;KAAe;AACnE"}
@@ -0,0 +1,24 @@
1
+ import type { Result } from "@webiny/feature/api";
2
+ import type { NotAuthorizedError } from "@webiny/api-core/features/users/shared/errors.js";
3
+ import type { GetUserUseCase } from "@webiny/api-core/features/users/GetUser/index.js";
4
+ import type { CognitoExternalUserError, CognitoResetMfaError } from "../../../api/domain/errors.js";
5
+ export interface IResetUserMfaUseCaseErrors {
6
+ authorization: NotAuthorizedError;
7
+ getUser: GetUserUseCase.Error;
8
+ externalUser: CognitoExternalUserError;
9
+ cognitoResetMfa: CognitoResetMfaError;
10
+ }
11
+ type IResetUserMfaError = IResetUserMfaUseCaseErrors[keyof IResetUserMfaUseCaseErrors];
12
+ export interface IResetUserMfaUseCase {
13
+ /**
14
+ * Deletes the user's TOTP software token, so they set up MFA again on their next sign-in.
15
+ * The account is shared by all of the person's tenants, so this applies in all of them.
16
+ */
17
+ execute(id: string): Promise<Result<void, IResetUserMfaError>>;
18
+ }
19
+ export declare const ResetUserMfaUseCase: import("@webiny/di").Abstraction<IResetUserMfaUseCase>;
20
+ export declare namespace ResetUserMfaUseCase {
21
+ type Interface = IResetUserMfaUseCase;
22
+ type Error = IResetUserMfaError;
23
+ }
24
+ export {};
@@ -0,0 +1,5 @@
1
+ import { createAbstraction } from "@webiny/feature/api";
2
+ const ResetUserMfaUseCase = createAbstraction("ResetUserMfaUseCase");
3
+ export { ResetUserMfaUseCase };
4
+
5
+ //# sourceMappingURL=abstractions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api/features/ResetUserMfa/abstractions.js","sources":["../../../../src/api/features/ResetUserMfa/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { Result } from \"@webiny/feature/api\";\nimport type { NotAuthorizedError } from \"@webiny/api-core/features/users/shared/errors.js\";\nimport type { GetUserUseCase } from \"@webiny/api-core/features/users/GetUser/index.js\";\nimport type { CognitoExternalUserError, CognitoResetMfaError } from \"~/api/domain/errors.js\";\n\nexport interface IResetUserMfaUseCaseErrors {\n authorization: NotAuthorizedError;\n getUser: GetUserUseCase.Error;\n externalUser: CognitoExternalUserError;\n cognitoResetMfa: CognitoResetMfaError;\n}\n\ntype IResetUserMfaError = IResetUserMfaUseCaseErrors[keyof IResetUserMfaUseCaseErrors];\n\nexport interface IResetUserMfaUseCase {\n /**\n * Deletes the user's TOTP software token, so they set up MFA again on their next sign-in.\n * The account is shared by all of the person's tenants, so this applies in all of them.\n */\n execute(id: string): Promise<Result<void, IResetUserMfaError>>;\n}\n\nexport const ResetUserMfaUseCase = createAbstraction<IResetUserMfaUseCase>(\"ResetUserMfaUseCase\");\n\nexport namespace ResetUserMfaUseCase {\n export type Interface = IResetUserMfaUseCase;\n export type Error = IResetUserMfaError;\n}\n"],"names":["ResetUserMfaUseCase","createAbstraction"],"mappings":";AAuBO,MAAMA,sBAAsBC,kBAAwC"}
@@ -0,0 +1,4 @@
1
+ export declare const ResetUserMfaFeature: {
2
+ name: string;
3
+ register(container: import("@webiny/di").Container): void;
4
+ };
@@ -0,0 +1,11 @@
1
+ import { createFeature } from "@webiny/feature/api";
2
+ import { ResetUserMfaUseCase } from "./ResetUserMfaUseCase.js";
3
+ const ResetUserMfaFeature = createFeature({
4
+ name: "ResetUserMfaFeature",
5
+ register (container) {
6
+ container.register(ResetUserMfaUseCase);
7
+ }
8
+ });
9
+ export { ResetUserMfaFeature };
10
+
11
+ //# sourceMappingURL=feature.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api/features/ResetUserMfa/feature.js","sources":["../../../../src/api/features/ResetUserMfa/feature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { ResetUserMfaUseCase } from \"./ResetUserMfaUseCase.js\";\n\nexport const ResetUserMfaFeature = createFeature({\n name: \"ResetUserMfaFeature\",\n register(container) {\n container.register(ResetUserMfaUseCase);\n }\n});\n"],"names":["ResetUserMfaFeature","createFeature","container","ResetUserMfaUseCase"],"mappings":";;AAGO,MAAMA,sBAAsBC,cAAc;IAC7C,MAAM;IACN,UAASC,SAAS;QACdA,UAAU,QAAQ,CAACC;IACvB;AACJ"}