@webiny/cognito 6.6.0-alpha.12 → 6.6.0-alpha.13

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 (103) hide show
  1. package/admin/Cognito.js +7 -1
  2. package/admin/Cognito.js.map +1 -1
  3. package/admin/presentation/Cognito/CognitoLoginScreen.js +9 -1
  4. package/admin/presentation/Cognito/CognitoLoginScreen.js.map +1 -1
  5. package/admin/presentation/Cognito/CognitoPresenter.d.ts +10 -1
  6. package/admin/presentation/Cognito/CognitoPresenter.js +50 -4
  7. package/admin/presentation/Cognito/CognitoPresenter.js.map +1 -1
  8. package/admin/presentation/Cognito/CognitoPresenter.test.d.ts +1 -0
  9. package/admin/presentation/Cognito/CognitoPresenter.test.js +180 -0
  10. package/admin/presentation/Cognito/CognitoPresenter.test.js.map +1 -0
  11. package/admin/presentation/Cognito/abstractions.d.ts +8 -1
  12. package/admin/presentation/Cognito/abstractions.js.map +1 -1
  13. package/admin/presentation/Cognito/components/FederatedProviders.js +1 -1
  14. package/admin/presentation/Cognito/components/FederatedProviders.js.map +1 -1
  15. package/admin/presentation/Cognito/components/NoTenantAccess.d.ts +23 -0
  16. package/admin/presentation/Cognito/components/NoTenantAccess.js +10 -0
  17. package/admin/presentation/Cognito/components/NoTenantAccess.js.map +1 -0
  18. package/admin/presentation/Cognito/components/SelectTenant.d.ts +26 -0
  19. package/admin/presentation/Cognito/components/SelectTenant.js +15 -0
  20. package/admin/presentation/Cognito/components/SelectTenant.js.map +1 -0
  21. package/admin/presentation/Cognito/components/SetNewPassword.js.map +1 -1
  22. package/admin/presentation/Cognito/components/SetupTotp.js +6 -5
  23. package/admin/presentation/Cognito/components/SetupTotp.js.map +1 -1
  24. package/admin/presentation/Cognito/components/View.js +5 -5
  25. package/admin/presentation/Cognito/components/View.js.map +1 -1
  26. package/admin/presentation/Cognito/components/index.d.ts +38 -0
  27. package/admin/presentation/Cognito/components/index.js +4 -0
  28. package/admin/presentation/Cognito/components/index.js.map +1 -1
  29. package/api/CognitoApiFeature.js +6 -0
  30. package/api/CognitoApiFeature.js.map +1 -1
  31. package/api/domain/errors.d.ts +68 -0
  32. package/api/domain/errors.js +73 -1
  33. package/api/domain/errors.js.map +1 -1
  34. package/api/features/CheckEmail/CheckEmailUseCase.d.ts +16 -0
  35. package/api/features/CheckEmail/CheckEmailUseCase.js +47 -0
  36. package/api/features/CheckEmail/CheckEmailUseCase.js.map +1 -0
  37. package/api/features/CheckEmail/abstractions.d.ts +29 -0
  38. package/api/features/CheckEmail/abstractions.js +5 -0
  39. package/api/features/CheckEmail/abstractions.js.map +1 -0
  40. package/api/features/CheckEmail/feature.d.ts +4 -0
  41. package/api/features/CheckEmail/feature.js +11 -0
  42. package/api/features/CheckEmail/feature.js.map +1 -0
  43. package/api/features/CheckEmail/index.d.ts +2 -0
  44. package/api/features/CheckEmail/index.js +2 -0
  45. package/api/features/CognitoIdp/CognitoIdentityProvider.d.ts +2 -0
  46. package/api/features/CognitoIdp/CognitoIdentityProvider.js +20 -0
  47. package/api/features/CognitoIdp/CognitoIdentityProvider.js.map +1 -1
  48. package/api/features/CognitoIdp/abstractions.d.ts +6 -0
  49. package/api/features/CognitoIdp/abstractions.js.map +1 -1
  50. package/api/features/CognitoService/CognitoService.d.ts +2 -1
  51. package/api/features/CognitoService/CognitoService.js +20 -5
  52. package/api/features/CognitoService/CognitoService.js.map +1 -1
  53. package/api/features/CognitoService/abstractions.d.ts +13 -2
  54. package/api/features/CognitoService/abstractions.js.map +1 -1
  55. package/api/features/CognitoService/adminDeleteSoftwareToken.d.ts +16 -0
  56. package/api/features/CognitoService/adminDeleteSoftwareToken.js +69 -0
  57. package/api/features/CognitoService/adminDeleteSoftwareToken.js.map +1 -0
  58. package/api/features/CognitoService/adminDeleteSoftwareToken.test.d.ts +1 -0
  59. package/api/features/CognitoService/adminDeleteSoftwareToken.test.js +91 -0
  60. package/api/features/CognitoService/adminDeleteSoftwareToken.test.js.map +1 -0
  61. package/api/features/CreateUser/CreateUserUseCase.d.ts +1 -2
  62. package/api/features/CreateUser/CreateUserUseCase.js +3 -3
  63. package/api/features/CreateUser/CreateUserUseCase.js.map +1 -1
  64. package/api/features/CreateUser/abstractions.d.ts +3 -1
  65. package/api/features/CreateUser/abstractions.js.map +1 -1
  66. package/api/features/DeleteUser/DeleteUserUseCase.d.ts +3 -1
  67. package/api/features/DeleteUser/DeleteUserUseCase.js +11 -2
  68. package/api/features/DeleteUser/DeleteUserUseCase.js.map +1 -1
  69. package/api/features/DeleteUser/abstractions.d.ts +2 -0
  70. package/api/features/DeleteUser/abstractions.js.map +1 -1
  71. package/api/features/LinkUser/LinkUserUseCase.d.ts +22 -0
  72. package/api/features/LinkUser/LinkUserUseCase.js +83 -0
  73. package/api/features/LinkUser/LinkUserUseCase.js.map +1 -0
  74. package/api/features/LinkUser/abstractions.d.ts +36 -0
  75. package/api/features/LinkUser/abstractions.js +5 -0
  76. package/api/features/LinkUser/abstractions.js.map +1 -0
  77. package/api/features/LinkUser/feature.d.ts +4 -0
  78. package/api/features/LinkUser/feature.js +11 -0
  79. package/api/features/LinkUser/feature.js.map +1 -0
  80. package/api/features/LinkUser/index.d.ts +2 -0
  81. package/api/features/LinkUser/index.js +2 -0
  82. package/api/features/ResetUserMfa/ResetUserMfaUseCase.d.ts +18 -0
  83. package/api/features/ResetUserMfa/ResetUserMfaUseCase.js +59 -0
  84. package/api/features/ResetUserMfa/ResetUserMfaUseCase.js.map +1 -0
  85. package/api/features/ResetUserMfa/abstractions.d.ts +24 -0
  86. package/api/features/ResetUserMfa/abstractions.js +5 -0
  87. package/api/features/ResetUserMfa/abstractions.js.map +1 -0
  88. package/api/features/ResetUserMfa/feature.d.ts +4 -0
  89. package/api/features/ResetUserMfa/feature.js +11 -0
  90. package/api/features/ResetUserMfa/feature.js.map +1 -0
  91. package/api/features/ResetUserMfa/index.d.ts +2 -0
  92. package/api/features/ResetUserMfa/index.js +2 -0
  93. package/api/features/UpdateUser/UpdateUserUseCase.d.ts +24 -1
  94. package/api/features/UpdateUser/UpdateUserUseCase.js +97 -4
  95. package/api/features/UpdateUser/UpdateUserUseCase.js.map +1 -1
  96. package/api/features/UpdateUser/abstractions.d.ts +7 -1
  97. package/api/features/UpdateUser/abstractions.js.map +1 -1
  98. package/api/features/UserInstaller/UserInstaller.d.ts +3 -1
  99. package/api/features/UserInstaller/UserInstaller.js +18 -3
  100. package/api/features/UserInstaller/UserInstaller.js.map +1 -1
  101. package/api/graphql/user.gql.js +87 -0
  102. package/api/graphql/user.gql.js.map +1 -1
  103. package/package.json +24 -19
@@ -0,0 +1,47 @@
1
+ import { z } from "zod";
2
+ import { Result } from "@webiny/feature/api";
3
+ import { AdminUsersRepository } from "@webiny/api-core/features/users/shared/abstractions.js";
4
+ import { NotAuthorizedError, UserValidationError } from "@webiny/api-core/features/users/shared/errors.js";
5
+ import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
6
+ import { CheckEmailUseCase } from "./abstractions.js";
7
+ import { Username } from "../../domain/Username.js";
8
+ import { CognitoGetUserError } from "../../domain/errors.js";
9
+ import { CognitoService } from "../CognitoService/index.js";
10
+ const emailValidation = z.string().email();
11
+ class CheckEmailUseCaseImpl {
12
+ constructor(identityContext, cognitoService, repository){
13
+ this.identityContext = identityContext;
14
+ this.cognitoService = cognitoService;
15
+ this.repository = repository;
16
+ }
17
+ async execute(email) {
18
+ const permission = await this.identityContext.getPermission("adminUsers.user");
19
+ if (!permission) return Result.fail(new NotAuthorizedError());
20
+ const validation = emailValidation.safeParse(email);
21
+ if (!validation.success) return Result.fail(new UserValidationError(validation.error.issues[0].message));
22
+ const existingUserResult = await this.repository.get({
23
+ email
24
+ });
25
+ if (existingUserResult.isOk()) return Result.ok("EXISTS_HERE");
26
+ try {
27
+ const cognitoUser = await this.cognitoService.getUser(Username.fromUser({
28
+ email
29
+ }));
30
+ if (cognitoUser?.attributes["custom:id"]) return Result.ok("EXISTS_ELSEWHERE");
31
+ } catch (error) {
32
+ return Result.fail(new CognitoGetUserError(error));
33
+ }
34
+ return Result.ok("AVAILABLE");
35
+ }
36
+ }
37
+ const CheckEmailUseCase_CheckEmailUseCase = CheckEmailUseCase.createImplementation({
38
+ implementation: CheckEmailUseCaseImpl,
39
+ dependencies: [
40
+ IdentityContext,
41
+ CognitoService,
42
+ AdminUsersRepository
43
+ ]
44
+ });
45
+ export { CheckEmailUseCase_CheckEmailUseCase as CheckEmailUseCase };
46
+
47
+ //# sourceMappingURL=CheckEmailUseCase.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api/features/CheckEmail/CheckEmailUseCase.js","sources":["../../../../src/api/features/CheckEmail/CheckEmailUseCase.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { Result } from \"@webiny/feature/api\";\nimport { AdminUsersRepository } from \"@webiny/api-core/features/users/shared/abstractions.js\";\nimport {\n NotAuthorizedError,\n UserValidationError\n} from \"@webiny/api-core/features/users/shared/errors.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { CheckEmailUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { Username } from \"~/api/domain/Username.js\";\nimport { CognitoGetUserError } from \"~/api/domain/errors.js\";\nimport { CognitoService } from \"~/api/features/CognitoService/index.js\";\n\nconst emailValidation = z.string().email();\n\nclass CheckEmailUseCaseImpl implements UseCaseAbstraction.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private cognitoService: CognitoService.Interface,\n private repository: AdminUsersRepository.Interface\n ) {}\n\n async execute(\n email: string\n ): Promise<Result<UseCaseAbstraction.Status, UseCaseAbstraction.Error>> {\n const permission = await this.identityContext.getPermission(\"adminUsers.user\");\n if (!permission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n const validation = emailValidation.safeParse(email);\n if (!validation.success) {\n return Result.fail(new UserValidationError(validation.error.issues[0].message));\n }\n\n const existingUserResult = await this.repository.get({ email });\n if (existingUserResult.isOk()) {\n return Result.ok(\"EXISTS_HERE\");\n }\n\n try {\n const cognitoUser = await this.cognitoService.getUser(Username.fromUser({ email }));\n // Only an account with a user ID can be linked. Any other account makes\n // creating the user fail, as it always has.\n if (cognitoUser?.attributes[\"custom:id\"]) {\n return Result.ok(\"EXISTS_ELSEWHERE\");\n }\n } catch (error) {\n return Result.fail(new CognitoGetUserError(error as Error));\n }\n\n return Result.ok(\"AVAILABLE\");\n }\n}\n\nexport const CheckEmailUseCase = UseCaseAbstraction.createImplementation({\n implementation: CheckEmailUseCaseImpl,\n dependencies: [IdentityContext, CognitoService, AdminUsersRepository]\n});\n"],"names":["emailValidation","z","CheckEmailUseCaseImpl","identityContext","cognitoService","repository","email","permission","Result","NotAuthorizedError","validation","UserValidationError","existingUserResult","cognitoUser","Username","error","CognitoGetUserError","CheckEmailUseCase","UseCaseAbstraction","IdentityContext","CognitoService","AdminUsersRepository"],"mappings":";;;;;;;;;AAaA,MAAMA,kBAAkBC,EAAE,MAAM,GAAG,KAAK;AAExC,MAAMC;IACF,YACYC,eAA0C,EAC1CC,cAAwC,EACxCC,UAA0C,CACpD;aAHUF,eAAe,GAAfA;aACAC,cAAc,GAAdA;aACAC,UAAU,GAAVA;IACT;IAEH,MAAM,QACFC,KAAa,EACuD;QACpE,MAAMC,aAAa,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC;QAC5D,IAAI,CAACA,YACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAG3B,MAAMC,aAAaV,gBAAgB,SAAS,CAACM;QAC7C,IAAI,CAACI,WAAW,OAAO,EACnB,OAAOF,OAAO,IAAI,CAAC,IAAIG,oBAAoBD,WAAW,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO;QAGjF,MAAME,qBAAqB,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;YAAEN;QAAM;QAC7D,IAAIM,mBAAmB,IAAI,IACvB,OAAOJ,OAAO,EAAE,CAAC;QAGrB,IAAI;YACA,MAAMK,cAAc,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAACC,SAAS,QAAQ,CAAC;gBAAER;YAAM;YAGhF,IAAIO,aAAa,UAAU,CAAC,YAAY,EACpC,OAAOL,OAAO,EAAE,CAAC;QAEzB,EAAE,OAAOO,OAAO;YACZ,OAAOP,OAAO,IAAI,CAAC,IAAIQ,oBAAoBD;QAC/C;QAEA,OAAOP,OAAO,EAAE,CAAC;IACrB;AACJ;AAEO,MAAMS,sCAAoBC,kBAAAA,oBAAuC,CAAC;IACrE,gBAAgBhB;IAChB,cAAc;QAACiB;QAAiBC;QAAgBC;KAAqB;AACzE"}
@@ -0,0 +1,29 @@
1
+ import type { Result } from "@webiny/feature/api";
2
+ import type { NotAuthorizedError, UserValidationError } from "@webiny/api-core/features/users/shared/errors.js";
3
+ import type { CognitoGetUserError } from "../../../api/domain/errors.js";
4
+ /**
5
+ * - `AVAILABLE`: a new user can be created with this email.
6
+ * - `EXISTS_HERE`: the current tenant already has a user with this email.
7
+ * - `EXISTS_ELSEWHERE`: the email has an account in another tenant, which can be linked here.
8
+ */
9
+ export type EmailStatus = "AVAILABLE" | "EXISTS_HERE" | "EXISTS_ELSEWHERE";
10
+ export interface ICheckEmailUseCaseErrors {
11
+ authorization: NotAuthorizedError;
12
+ validation: UserValidationError;
13
+ cognito: CognitoGetUserError;
14
+ }
15
+ type CheckEmailError = ICheckEmailUseCaseErrors[keyof ICheckEmailUseCaseErrors];
16
+ /**
17
+ * Tells an administrator whether an email can be used for a new user in the current tenant.
18
+ * It only says whether an account exists elsewhere, never in which tenants.
19
+ */
20
+ export interface ICheckEmailUseCase {
21
+ execute(email: string): Promise<Result<EmailStatus, CheckEmailError>>;
22
+ }
23
+ export declare const CheckEmailUseCase: import("@webiny/di").Abstraction<ICheckEmailUseCase>;
24
+ export declare namespace CheckEmailUseCase {
25
+ type Interface = ICheckEmailUseCase;
26
+ type Status = EmailStatus;
27
+ type Error = CheckEmailError;
28
+ }
29
+ export {};
@@ -0,0 +1,5 @@
1
+ import { createAbstraction } from "@webiny/feature/api";
2
+ const CheckEmailUseCase = createAbstraction("CheckEmailUseCase");
3
+ export { CheckEmailUseCase };
4
+
5
+ //# sourceMappingURL=abstractions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api/features/CheckEmail/abstractions.js","sources":["../../../../src/api/features/CheckEmail/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { Result } from \"@webiny/feature/api\";\nimport type {\n NotAuthorizedError,\n UserValidationError\n} from \"@webiny/api-core/features/users/shared/errors.js\";\nimport type { CognitoGetUserError } from \"~/api/domain/errors.js\";\n\n/**\n * - `AVAILABLE`: a new user can be created with this email.\n * - `EXISTS_HERE`: the current tenant already has a user with this email.\n * - `EXISTS_ELSEWHERE`: the email has an account in another tenant, which can be linked here.\n */\nexport type EmailStatus = \"AVAILABLE\" | \"EXISTS_HERE\" | \"EXISTS_ELSEWHERE\";\n\nexport interface ICheckEmailUseCaseErrors {\n authorization: NotAuthorizedError;\n validation: UserValidationError;\n cognito: CognitoGetUserError;\n}\n\ntype CheckEmailError = ICheckEmailUseCaseErrors[keyof ICheckEmailUseCaseErrors];\n\n/**\n * Tells an administrator whether an email can be used for a new user in the current tenant.\n * It only says whether an account exists elsewhere, never in which tenants.\n */\nexport interface ICheckEmailUseCase {\n execute(email: string): Promise<Result<EmailStatus, CheckEmailError>>;\n}\n\nexport const CheckEmailUseCase = createAbstraction<ICheckEmailUseCase>(\"CheckEmailUseCase\");\n\nexport namespace CheckEmailUseCase {\n export type Interface = ICheckEmailUseCase;\n export type Status = EmailStatus;\n export type Error = CheckEmailError;\n}\n"],"names":["CheckEmailUseCase","createAbstraction"],"mappings":";AA+BO,MAAMA,oBAAoBC,kBAAsC"}
@@ -0,0 +1,4 @@
1
+ export declare const CheckEmailFeature: {
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 { CheckEmailUseCase } from "./CheckEmailUseCase.js";
3
+ const CheckEmailFeature = createFeature({
4
+ name: "CheckEmailFeature",
5
+ register (container) {
6
+ container.register(CheckEmailUseCase);
7
+ }
8
+ });
9
+ export { CheckEmailFeature };
10
+
11
+ //# sourceMappingURL=feature.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api/features/CheckEmail/feature.js","sources":["../../../../src/api/features/CheckEmail/feature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { CheckEmailUseCase } from \"./CheckEmailUseCase.js\";\n\nexport const CheckEmailFeature = createFeature({\n name: \"CheckEmailFeature\",\n register(container) {\n container.register(CheckEmailUseCase);\n }\n});\n"],"names":["CheckEmailFeature","createFeature","container","CheckEmailUseCase"],"mappings":";;AAGO,MAAMA,oBAAoBC,cAAc;IAC3C,MAAM;IACN,UAASC,SAAS;QACdA,UAAU,QAAQ,CAACC;IACvB;AACJ"}
@@ -0,0 +1,2 @@
1
+ export * from "./abstractions.js";
2
+ export * from "./feature.js";
@@ -0,0 +1,2 @@
1
+ export * from "./abstractions.js";
2
+ export * from "./feature.js";
@@ -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,MA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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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,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"}
@@ -3,7 +3,7 @@ declare class CognitoServiceImpl implements ServiceAbstraction.Interface {
3
3
  private config;
4
4
  private cognito;
5
5
  constructor(config: CognitoConfig.Interface);
6
- userExists(username: string): Promise<boolean>;
6
+ getUser(username: string): Promise<ServiceAbstraction.User | null>;
7
7
  createUser(params: {
8
8
  username: string;
9
9
  temporaryPassword: string;
@@ -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;
@@ -7,15 +8,21 @@ class CognitoServiceImpl {
7
8
  region: config.region
8
9
  });
9
10
  }
10
- async userExists(username) {
11
+ async getUser(username) {
11
12
  try {
12
- await this.cognito.adminGetUser({
13
+ const response = await this.cognito.adminGetUser({
13
14
  Username: username,
14
15
  UserPoolId: this.config.userPoolId
15
16
  });
16
- return true;
17
- } catch {
18
- return false;
17
+ const attributes = {};
18
+ for (const attribute of response.UserAttributes ?? [])if (attribute.Name) attributes[attribute.Name] = attribute.Value ?? "";
19
+ return {
20
+ username: response.Username ?? username,
21
+ attributes
22
+ };
23
+ } catch (error) {
24
+ if ("UserNotFoundException" === error.name) return null;
25
+ throw error;
19
26
  }
20
27
  }
21
28
  async createUser(params) {
@@ -88,6 +95,14 @@ class CognitoServiceImpl {
88
95
  Username: username
89
96
  });
90
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
+ }
91
106
  }
92
107
  const CognitoService_CognitoService = CognitoService.createImplementation({
93
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 userExists(username: string): Promise<boolean> {\n try {\n await this.cognito.adminGetUser({\n Username: username,\n UserPoolId: this.config.userPoolId\n });\n return true;\n } catch {\n // User does not exist\n return false;\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","params","createUserParams","password","attributes","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,QAAQ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AU;QACtC;IACJ;IAEA,MAAM,qBACFA,QAAgB,EAChBI,UAAkC,EACrB;QACb,MAAMC,iBAAiBC,OAAO,OAAO,CAACF,YAAY,GAAG,CAAC,CAAC,CAACG,MAAMC,MAAM,GAAM;gBACtE,MAAMD;gBACN,OAAOC;YACX;QAEA,MAAM,IAAI,CAAC,OAAO,CAAC,yBAAyB,CAAC;YACzC,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUR;YACV,gBAAgBK;QACpB;IACJ;IAEA,MAAM,WAAWL,QAAgB,EAAiB;QAC9C,MAAM,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC;YAC/B,YAAY,IAAI,CAAC,MAAM,CAAC,UAAU;YAClC,UAAUA;QACd;IACJ;AACJ;AAEO,MAAMS,gCAAiBC,eAAAA,oBAAuC,CAAC;IAClE,gBAAgBb;IAChB,cAAc;QAACc;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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AASA,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"}
@@ -17,11 +17,16 @@ export interface CognitoUserAttributes {
17
17
  email: string;
18
18
  customId: string;
19
19
  }
20
+ export interface CognitoUser {
21
+ username: string;
22
+ /** The account's attributes by name: `email`, `given_name`, `custom:id`, ... */
23
+ attributes: Record<string, string>;
24
+ }
20
25
  export interface ICognitoService {
21
26
  /**
22
- * Check if a user exists in Cognito User Pool
27
+ * Load a user from Cognito User Pool, or `null` if there's no account with this username.
23
28
  */
24
- userExists(username: string): Promise<boolean>;
29
+ getUser(username: string): Promise<CognitoUser | null>;
25
30
  /**
26
31
  * Create a new user in Cognito User Pool
27
32
  */
@@ -46,9 +51,15 @@ export interface ICognitoService {
46
51
  * Delete a user from Cognito User Pool
47
52
  */
48
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>;
49
59
  }
50
60
  export declare const CognitoService: import("@webiny/di").Abstraction<ICognitoService>;
51
61
  export declare namespace CognitoService {
52
62
  type Interface = ICognitoService;
53
63
  type UserAttributes = CognitoUserAttributes;
64
+ type User = CognitoUser;
54
65
  }
@@ -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 ICognitoService {\n /**\n * Check if a user exists in Cognito User Pool\n */\n userExists(username: string): Promise<boolean>;\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}\n"],"names":["CognitoConfig","createAbstraction","CognitoService"],"mappings":";AAYO,MAAMA,gBAAgBC,kBAAkC;AAoDxD,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;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AAM,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"}
@@ -1,6 +1,5 @@
1
1
  import { Result } from "@webiny/feature/api";
2
2
  import { AdminUsersRepository } from "@webiny/api-core/features/users/shared/abstractions.js";
3
- import type { AdminUser } from "@webiny/api-core/types/users.js";
4
3
  import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
5
4
  import { CreateUserUseCase as CoreCreateUser } from "@webiny/api-core/features/users/CreateUser/index.js";
6
5
  import { ListUsersUseCase } from "@webiny/api-core/features/users/ListUsers/index.js";
@@ -14,7 +13,7 @@ declare class CreateUserUseCaseImpl implements UseCaseAbstraction.Interface {
14
13
  private listUsersUseCase;
15
14
  private repository;
16
15
  constructor(identityContext: IdentityContext.Interface, cognitoService: CognitoService.Interface, createUserUseCase: CoreCreateUser.Interface, listUsersUseCase: ListUsersUseCase.Interface, repository: AdminUsersRepository.Interface);
17
- execute(input: CreateAdminUserInput): Promise<Result<AdminUser, UseCaseAbstraction.Error>>;
16
+ execute(input: CreateAdminUserInput): Promise<Result<UseCaseAbstraction.Output, UseCaseAbstraction.Error>>;
18
17
  }
19
18
  export declare const CreateUserUseCase: typeof CreateUserUseCaseImpl & {
20
19
  __abstraction: import("@webiny/di").Abstraction<import("./abstractions.js").ICreateUserUseCase>;