@pagopa/io-react-native-wallet 0.12.0 → 0.13.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (205) hide show
  1. package/lib/commonjs/client/generated/wallet-provider.js +22 -22
  2. package/lib/commonjs/client/generated/wallet-provider.js.map +1 -1
  3. package/lib/commonjs/client/index.js +1 -2
  4. package/lib/commonjs/client/index.js.map +1 -1
  5. package/lib/commonjs/credential/issuance/02-evaluate-issuer-trust.js +2 -1
  6. package/lib/commonjs/credential/issuance/02-evaluate-issuer-trust.js.map +1 -1
  7. package/lib/commonjs/credential/issuance/03-start-credential-issuance.js +287 -0
  8. package/lib/commonjs/credential/issuance/03-start-credential-issuance.js.map +1 -0
  9. package/lib/commonjs/credential/issuance/03-start-user-authorization.js +56 -83
  10. package/lib/commonjs/credential/issuance/03-start-user-authorization.js.map +1 -1
  11. package/lib/commonjs/credential/issuance/04-complete-user-authorization.js +88 -0
  12. package/lib/commonjs/credential/issuance/04-complete-user-authorization.js.map +1 -1
  13. package/lib/commonjs/credential/issuance/05-authorize-access.js +56 -33
  14. package/lib/commonjs/credential/issuance/05-authorize-access.js.map +1 -1
  15. package/lib/commonjs/credential/issuance/06-obtain-credential.js +51 -78
  16. package/lib/commonjs/credential/issuance/06-obtain-credential.js.map +1 -1
  17. package/lib/commonjs/credential/issuance/07-verify-and-parse-credential.js +21 -44
  18. package/lib/commonjs/credential/issuance/07-verify-and-parse-credential.js.map +1 -1
  19. package/lib/commonjs/credential/issuance/index.js +7 -0
  20. package/lib/commonjs/credential/issuance/index.js.map +1 -1
  21. package/lib/commonjs/credential/issuance/types.js +28 -0
  22. package/lib/commonjs/credential/issuance/types.js.map +1 -0
  23. package/lib/commonjs/index.js.map +1 -1
  24. package/lib/commonjs/pid/sd-jwt/converters.js +5 -9
  25. package/lib/commonjs/pid/sd-jwt/converters.js.map +1 -1
  26. package/lib/commonjs/pid/sd-jwt/types.js +3 -3
  27. package/lib/commonjs/pid/sd-jwt/types.js.map +1 -1
  28. package/lib/commonjs/sd-jwt/__test__/converters.test.js +1 -1
  29. package/lib/commonjs/sd-jwt/__test__/converters.test.js.map +1 -1
  30. package/lib/commonjs/sd-jwt/__test__/index.test.js +30 -43
  31. package/lib/commonjs/sd-jwt/__test__/index.test.js.map +1 -1
  32. package/lib/commonjs/sd-jwt/__test__/types.test.js +16 -24
  33. package/lib/commonjs/sd-jwt/__test__/types.test.js.map +1 -1
  34. package/lib/commonjs/sd-jwt/index.js +3 -9
  35. package/lib/commonjs/sd-jwt/index.js.map +1 -1
  36. package/lib/commonjs/sd-jwt/types.js +11 -16
  37. package/lib/commonjs/sd-jwt/types.js.map +1 -1
  38. package/lib/commonjs/trust/types.js +70 -29
  39. package/lib/commonjs/trust/types.js.map +1 -1
  40. package/lib/commonjs/utils/auth.js +44 -0
  41. package/lib/commonjs/utils/auth.js.map +1 -0
  42. package/lib/commonjs/utils/errors.js +77 -2
  43. package/lib/commonjs/utils/errors.js.map +1 -1
  44. package/lib/commonjs/utils/misc.js +34 -1
  45. package/lib/commonjs/utils/misc.js.map +1 -1
  46. package/lib/commonjs/utils/par.js +23 -15
  47. package/lib/commonjs/utils/par.js.map +1 -1
  48. package/lib/commonjs/utils/pop.js +33 -0
  49. package/lib/commonjs/utils/pop.js.map +1 -0
  50. package/lib/commonjs/wallet-instance-attestation/issuing.js +17 -2
  51. package/lib/commonjs/wallet-instance-attestation/issuing.js.map +1 -1
  52. package/lib/commonjs/wallet-instance-attestation/types.js +7 -7
  53. package/lib/commonjs/wallet-instance-attestation/types.js.map +1 -1
  54. package/lib/module/client/generated/wallet-provider.js +16 -19
  55. package/lib/module/client/generated/wallet-provider.js.map +1 -1
  56. package/lib/module/client/index.js +1 -2
  57. package/lib/module/client/index.js.map +1 -1
  58. package/lib/module/credential/issuance/02-evaluate-issuer-trust.js +2 -1
  59. package/lib/module/credential/issuance/02-evaluate-issuer-trust.js.map +1 -1
  60. package/lib/module/credential/issuance/03-start-credential-issuance.js +276 -0
  61. package/lib/module/credential/issuance/03-start-credential-issuance.js.map +1 -0
  62. package/lib/module/credential/issuance/03-start-user-authorization.js +56 -80
  63. package/lib/module/credential/issuance/03-start-user-authorization.js.map +1 -1
  64. package/lib/module/credential/issuance/04-complete-user-authorization.js +85 -1
  65. package/lib/module/credential/issuance/04-complete-user-authorization.js.map +1 -1
  66. package/lib/module/credential/issuance/05-authorize-access.js +54 -33
  67. package/lib/module/credential/issuance/05-authorize-access.js.map +1 -1
  68. package/lib/module/credential/issuance/06-obtain-credential.js +50 -75
  69. package/lib/module/credential/issuance/06-obtain-credential.js.map +1 -1
  70. package/lib/module/credential/issuance/07-verify-and-parse-credential.js +21 -44
  71. package/lib/module/credential/issuance/07-verify-and-parse-credential.js.map +1 -1
  72. package/lib/module/credential/issuance/index.js +2 -1
  73. package/lib/module/credential/issuance/index.js.map +1 -1
  74. package/lib/module/credential/issuance/types.js +18 -0
  75. package/lib/module/credential/issuance/types.js.map +1 -0
  76. package/lib/module/index.js.map +1 -1
  77. package/lib/module/pid/sd-jwt/converters.js +5 -9
  78. package/lib/module/pid/sd-jwt/converters.js.map +1 -1
  79. package/lib/module/pid/sd-jwt/types.js +3 -3
  80. package/lib/module/pid/sd-jwt/types.js.map +1 -1
  81. package/lib/module/sd-jwt/__test__/converters.test.js +1 -1
  82. package/lib/module/sd-jwt/__test__/converters.test.js.map +1 -1
  83. package/lib/module/sd-jwt/__test__/index.test.js +30 -43
  84. package/lib/module/sd-jwt/__test__/index.test.js.map +1 -1
  85. package/lib/module/sd-jwt/__test__/types.test.js +16 -24
  86. package/lib/module/sd-jwt/__test__/types.test.js.map +1 -1
  87. package/lib/module/sd-jwt/index.js +3 -9
  88. package/lib/module/sd-jwt/index.js.map +1 -1
  89. package/lib/module/sd-jwt/types.js +11 -16
  90. package/lib/module/sd-jwt/types.js.map +1 -1
  91. package/lib/module/sd-jwt/verifier.js.map +1 -1
  92. package/lib/module/trust/types.js +70 -29
  93. package/lib/module/trust/types.js.map +1 -1
  94. package/lib/module/utils/auth.js +35 -0
  95. package/lib/module/utils/auth.js.map +1 -0
  96. package/lib/module/utils/errors.js +71 -0
  97. package/lib/module/utils/errors.js.map +1 -1
  98. package/lib/module/utils/misc.js +31 -0
  99. package/lib/module/utils/misc.js.map +1 -1
  100. package/lib/module/utils/par.js +24 -16
  101. package/lib/module/utils/par.js.map +1 -1
  102. package/lib/module/utils/pop.js +24 -0
  103. package/lib/module/utils/pop.js.map +1 -0
  104. package/lib/module/wallet-instance-attestation/issuing.js +17 -2
  105. package/lib/module/wallet-instance-attestation/issuing.js.map +1 -1
  106. package/lib/module/wallet-instance-attestation/types.js +7 -7
  107. package/lib/module/wallet-instance-attestation/types.js.map +1 -1
  108. package/lib/typescript/client/generated/wallet-provider.d.ts +35 -13
  109. package/lib/typescript/client/generated/wallet-provider.d.ts.map +1 -1
  110. package/lib/typescript/client/index.d.ts.map +1 -1
  111. package/lib/typescript/credential/issuance/01-start-flow.d.ts +1 -0
  112. package/lib/typescript/credential/issuance/01-start-flow.d.ts.map +1 -1
  113. package/lib/typescript/credential/issuance/02-evaluate-issuer-trust.d.ts +2 -1
  114. package/lib/typescript/credential/issuance/02-evaluate-issuer-trust.d.ts.map +1 -1
  115. package/lib/typescript/credential/issuance/03-start-credential-issuance.d.ts +41 -0
  116. package/lib/typescript/credential/issuance/03-start-credential-issuance.d.ts.map +1 -0
  117. package/lib/typescript/credential/issuance/03-start-user-authorization.d.ts +23 -18
  118. package/lib/typescript/credential/issuance/03-start-user-authorization.d.ts.map +1 -1
  119. package/lib/typescript/credential/issuance/04-complete-user-authorization.d.ts +24 -12
  120. package/lib/typescript/credential/issuance/04-complete-user-authorization.d.ts.map +1 -1
  121. package/lib/typescript/credential/issuance/05-authorize-access.d.ts +22 -16
  122. package/lib/typescript/credential/issuance/05-authorize-access.d.ts.map +1 -1
  123. package/lib/typescript/credential/issuance/06-obtain-credential.d.ts +19 -26
  124. package/lib/typescript/credential/issuance/06-obtain-credential.d.ts.map +1 -1
  125. package/lib/typescript/credential/issuance/07-verify-and-parse-credential.d.ts +10 -15
  126. package/lib/typescript/credential/issuance/07-verify-and-parse-credential.d.ts.map +1 -1
  127. package/lib/typescript/credential/issuance/index.d.ts +3 -4
  128. package/lib/typescript/credential/issuance/index.d.ts.map +1 -1
  129. package/lib/typescript/credential/issuance/types.d.ts +63 -0
  130. package/lib/typescript/credential/issuance/types.d.ts.map +1 -0
  131. package/lib/typescript/credential/presentation/types.d.ts +6 -6
  132. package/lib/typescript/index.d.ts +2 -1
  133. package/lib/typescript/index.d.ts.map +1 -1
  134. package/lib/typescript/pid/sd-jwt/converters.d.ts.map +1 -1
  135. package/lib/typescript/pid/sd-jwt/types.d.ts +36 -36
  136. package/lib/typescript/pid/sd-jwt/types.d.ts.map +1 -1
  137. package/lib/typescript/sd-jwt/index.d.ts +40 -68
  138. package/lib/typescript/sd-jwt/index.d.ts.map +1 -1
  139. package/lib/typescript/sd-jwt/types.d.ts +64 -121
  140. package/lib/typescript/sd-jwt/types.d.ts.map +1 -1
  141. package/lib/typescript/trust/index.d.ts +150 -48
  142. package/lib/typescript/trust/index.d.ts.map +1 -1
  143. package/lib/typescript/trust/types.d.ts +2838 -1740
  144. package/lib/typescript/trust/types.d.ts.map +1 -1
  145. package/lib/typescript/utils/auth.d.ts +52 -0
  146. package/lib/typescript/utils/auth.d.ts.map +1 -0
  147. package/lib/typescript/utils/errors.d.ts +36 -1
  148. package/lib/typescript/utils/errors.d.ts.map +1 -1
  149. package/lib/typescript/utils/integrity.d.ts +1 -1
  150. package/lib/typescript/utils/misc.d.ts +18 -0
  151. package/lib/typescript/utils/misc.d.ts.map +1 -1
  152. package/lib/typescript/utils/par.d.ts +8 -31
  153. package/lib/typescript/utils/par.d.ts.map +1 -1
  154. package/lib/typescript/utils/pop.d.ts +26 -0
  155. package/lib/typescript/utils/pop.d.ts.map +1 -0
  156. package/lib/typescript/wallet-instance-attestation/issuing.d.ts +2 -1
  157. package/lib/typescript/wallet-instance-attestation/issuing.d.ts.map +1 -1
  158. package/lib/typescript/wallet-instance-attestation/types.d.ts +59 -59
  159. package/lib/typescript/wallet-instance-attestation/types.d.ts.map +1 -1
  160. package/package.json +2 -1
  161. package/src/client/generated/wallet-provider.ts +24 -21
  162. package/src/client/index.ts +3 -8
  163. package/src/credential/issuance/01-start-flow.ts +1 -0
  164. package/src/credential/issuance/02-evaluate-issuer-trust.ts +2 -1
  165. package/src/credential/issuance/03-start-credential-issuance.ts +407 -0
  166. package/src/credential/issuance/03-start-user-authorization.ts +91 -92
  167. package/src/credential/issuance/04-complete-user-authorization.ts +114 -13
  168. package/src/credential/issuance/05-authorize-access.ts +74 -49
  169. package/src/credential/issuance/06-obtain-credential.ts +77 -111
  170. package/src/credential/issuance/07-verify-and-parse-credential.ts +30 -67
  171. package/src/credential/issuance/index.ts +6 -4
  172. package/src/credential/issuance/types.ts +25 -0
  173. package/src/index.ts +2 -1
  174. package/src/pid/sd-jwt/converters.ts +5 -11
  175. package/src/pid/sd-jwt/types.ts +8 -6
  176. package/src/sd-jwt/__test__/converters.test.ts +1 -1
  177. package/src/sd-jwt/__test__/index.test.ts +45 -74
  178. package/src/sd-jwt/__test__/types.test.ts +21 -33
  179. package/src/sd-jwt/index.ts +3 -12
  180. package/src/sd-jwt/types.ts +17 -22
  181. package/src/trust/types.ts +64 -32
  182. package/src/utils/auth.ts +37 -0
  183. package/src/utils/errors.ts +85 -1
  184. package/src/utils/integrity.ts +1 -1
  185. package/src/utils/misc.ts +43 -0
  186. package/src/utils/par.ts +29 -17
  187. package/src/utils/pop.ts +34 -0
  188. package/src/wallet-instance-attestation/issuing.ts +39 -2
  189. package/src/wallet-instance-attestation/types.ts +11 -7
  190. package/lib/commonjs/credential/issuance/07-confirm-credential.js +0 -6
  191. package/lib/commonjs/credential/issuance/07-confirm-credential.js.map +0 -1
  192. package/lib/commonjs/credential/issuance/08-confirm-credential.js +0 -6
  193. package/lib/commonjs/credential/issuance/08-confirm-credential.js.map +0 -1
  194. package/lib/module/credential/issuance/07-confirm-credential.js +0 -2
  195. package/lib/module/credential/issuance/07-confirm-credential.js.map +0 -1
  196. package/lib/module/credential/issuance/08-confirm-credential.js +0 -2
  197. package/lib/module/credential/issuance/08-confirm-credential.js.map +0 -1
  198. package/lib/typescript/credential/issuance/07-confirm-credential.d.ts +0 -11
  199. package/lib/typescript/credential/issuance/07-confirm-credential.d.ts.map +0 -1
  200. package/lib/typescript/credential/issuance/08-confirm-credential.d.ts +0 -11
  201. package/lib/typescript/credential/issuance/08-confirm-credential.d.ts.map +0 -1
  202. package/src/credential/issuance/07-confirm-credential.ts +0 -14
  203. package/src/credential/issuance/08-confirm-credential.ts +0 -14
  204. package/src/sd-jwt/__test__/converters.test.js +0 -24
  205. package/src/sd-jwt/verifier.js +0 -12
@@ -1,5 +1,26 @@
1
1
  import z from "zod";
2
2
 
3
+ export type NonceDetailView = z.infer<typeof NonceDetailView>;
4
+ export const NonceDetailView = z.object({
5
+ nonce: z.string(),
6
+ });
7
+
8
+ export type WalletAttestationView = z.infer<typeof WalletAttestationView>;
9
+ export const WalletAttestationView = z.string();
10
+
11
+ export type CreateWalletInstanceBody = z.infer<typeof CreateWalletInstanceBody>;
12
+ export const CreateWalletInstanceBody = z.object({
13
+ challenge: z.string(),
14
+ key_attestation: z.string(),
15
+ hardware_key_tag: z.string(),
16
+ });
17
+
18
+ export type CreateWalletAttestationBody = z.infer<typeof CreateWalletAttestationBody>;
19
+ export const CreateWalletAttestationBody = z.object({
20
+ grant_type: z.literal("urn:ietf:params:oauth:grant-type:jwt-bearer"),
21
+ assertion: z.string(),
22
+ });
23
+
3
24
  export type ProblemDetail = z.infer<typeof ProblemDetail>;
4
25
  export const ProblemDetail = z.object({
5
26
  type: z.string().optional(),
@@ -15,22 +36,12 @@ export const FiscalCode = z.string();
15
36
  export type Id = z.infer<typeof Id>;
16
37
  export const Id = z.string();
17
38
 
18
- export type get_GetEntityConfiguration = typeof get_GetEntityConfiguration;
19
- export const get_GetEntityConfiguration = {
20
- method: z.literal("GET"),
21
- path: z.literal("/.well-known/openid-federation"),
22
- parameters: z.never(),
23
- response: z.unknown(),
24
- };
25
-
26
39
  export type get_GetNonce = typeof get_GetNonce;
27
40
  export const get_GetNonce = {
28
41
  method: z.literal("GET"),
29
42
  path: z.literal("/nonce"),
30
43
  parameters: z.never(),
31
- response: z.object({
32
- nonce: z.string(),
33
- }),
44
+ response: NonceDetailView,
34
45
  };
35
46
 
36
47
  export type post_CreateWalletInstance = typeof post_CreateWalletInstance;
@@ -38,11 +49,7 @@ export const post_CreateWalletInstance = {
38
49
  method: z.literal("POST"),
39
50
  path: z.literal("/wallet-instances"),
40
51
  parameters: z.object({
41
- body: z.object({
42
- challenge: z.string(),
43
- key_attestation: z.string(),
44
- hardware_key_tag: z.string(),
45
- }),
52
+ body: CreateWalletInstanceBody,
46
53
  }),
47
54
  response: z.unknown(),
48
55
  };
@@ -52,10 +59,7 @@ export const post_CreateWalletAttestation = {
52
59
  method: z.literal("POST"),
53
60
  path: z.literal("/token"),
54
61
  parameters: z.object({
55
- body: z.object({
56
- grant_type: z.literal("urn:ietf:params:oauth:grant-type:jwt-bearer"),
57
- assertion: z.string(),
58
- }),
62
+ body: CreateWalletAttestationBody,
59
63
  }),
60
64
  response: z.unknown(),
61
65
  };
@@ -63,7 +67,6 @@ export const post_CreateWalletAttestation = {
63
67
  // <EndpointByMethod>
64
68
  export const EndpointByMethod = {
65
69
  get: {
66
- "/.well-known/openid-federation": get_GetEntityConfiguration,
67
70
  "/nonce": get_GetNonce,
68
71
  },
69
72
  post: {
@@ -18,16 +18,11 @@ const validateResponse = async (response: Response) => {
18
18
  };
19
19
  }
20
20
 
21
- let statusResponse = `Response status code: ${response.status}`;
22
-
23
21
  throw new WalletProviderResponseError(
24
- problemDetail.title
25
- ? problemDetail.title
26
- : "Invalid response from Wallet Provider",
22
+ problemDetail.title ?? "Invalid response from Wallet Provider",
27
23
  problemDetail.type,
28
- problemDetail.detail
29
- ? statusResponse
30
- : `${statusResponse} with detail: ${problemDetail.detail}`
24
+ problemDetail.detail,
25
+ response.status
31
26
  );
32
27
  }
33
28
  return response;
@@ -1,4 +1,5 @@
1
1
  /**
2
+ * WARNING: This is the first function to be called in the issuing flow. The next function to be called is {@link evaluateIssuerTrust}.
2
3
  * The beginning of the issuing flow.
3
4
  * To be implemented accordind to the user touchpoint
4
5
  *
@@ -13,10 +13,11 @@ export type EvaluateIssuerTrust = (
13
13
  }>;
14
14
 
15
15
  /**
16
+ * WARNING: This function must be called after {@link startFlow}. The next function to be called is {@link startUserAuthorization}.
16
17
  * The Issuer trust evaluation phase.
17
18
  * Fetch the Issuer's configuration and verify trust.
18
19
  *
19
- * @param issuerUrl The base url of the Issuer
20
+ * @param issuerUrl The base url of the Issuer returned by {@link startFlow}
20
21
  * @param context.appFetch (optional) fetch api implementation. Default: built-in fetch
21
22
  * @returns The Issuer's configuration
22
23
  */
@@ -0,0 +1,407 @@
1
+ import uuid from "react-native-uuid";
2
+ import { AuthorizationDetail, makeParRequest } from "../../utils/par";
3
+ import { SignJWT, type CryptoContext } from "@pagopa/io-react-native-jwt";
4
+ import {
5
+ generateRandomAlphaNumericString,
6
+ hasStatus,
7
+ until,
8
+ type Out,
9
+ } from "../../utils/misc";
10
+ import type { StartFlow } from "./01-start-flow";
11
+ import type { EvaluateIssuerTrust } from "./02-evaluate-issuer-trust";
12
+ import { ASSERTION_TYPE } from "./const";
13
+ import parseUrl from "parse-url";
14
+ import {
15
+ AuthorizationError,
16
+ AuthorizationIdpError,
17
+ ValidationFailed,
18
+ } from "../../utils/errors";
19
+ import {
20
+ AuthorizationErrorShape,
21
+ AuthorizationResultShape,
22
+ type AuthorizationContext,
23
+ type AuthorizationResult,
24
+ } from "../../utils/auth";
25
+ import { withEphemeralKey } from "../../utils/crypto";
26
+ import { createDPopToken } from "../../utils/dpop";
27
+ import { createPopToken } from "../../utils/pop";
28
+ import { CredentialResponse, TokenResponse, type ResponseMode } from "./types";
29
+ import * as WalletInstanceAttestation from "../../wallet-instance-attestation";
30
+ import { Linking } from "react-native";
31
+
32
+ /**
33
+ * Ensures that the credential type requested is supported by the issuer and contained in the
34
+ * issuer configuration.
35
+ * @param issuerConf The issuer configuration
36
+ * @param credentialType The type of the credential to be requested
37
+ * @returns The credential definition to be used in the request which includes the format and the type and its type
38
+ */
39
+ const selectCredentialDefinition = (
40
+ issuerConf: Out<EvaluateIssuerTrust>["issuerConf"],
41
+ credentialType: Out<StartFlow>["credentialType"]
42
+ ): AuthorizationDetail => {
43
+ const credential_configurations_supported =
44
+ issuerConf.openid_credential_issuer.credential_configurations_supported;
45
+
46
+ const [result] = Object.keys(credential_configurations_supported)
47
+ .filter((e) => e.includes(credentialType))
48
+ .map((e) => ({
49
+ credential_configuration_id: credentialType,
50
+ format: credential_configurations_supported[e]!.format,
51
+ type: "openid_credential" as const,
52
+ }));
53
+
54
+ if (!result) {
55
+ throw new Error(`No credential support the type '${credentialType}'`);
56
+ }
57
+ return result;
58
+ };
59
+
60
+ /**
61
+ * Ensures that the response mode requested is supported by the issuer and contained in the issuer configuration.
62
+ * @param issuerConf The issuer configuration
63
+ * @param credentialType The type of the credential to be requested
64
+ * @returns The response mode to be used in the request, "query" for PersonIdentificationData and "form_post.jwt" for all other types.
65
+ */
66
+ const selectResponseMode = (
67
+ issuerConf: Out<EvaluateIssuerTrust>["issuerConf"],
68
+ credentialType: Out<StartFlow>["credentialType"]
69
+ ): ResponseMode => {
70
+ const responseModeSupported =
71
+ issuerConf.oauth_authorization_server.response_modes_supported;
72
+
73
+ const responseMode =
74
+ credentialType === "PersonIdentificationData" ? "query" : "form_post.jwt";
75
+
76
+ if (!responseModeSupported.includes(responseMode)) {
77
+ throw new Error(`No response mode support the type '${credentialType}'`);
78
+ }
79
+
80
+ return responseMode;
81
+ };
82
+
83
+ export type StartCredentialIssuance = (
84
+ issuerConf: Out<EvaluateIssuerTrust>["issuerConf"],
85
+ credentialType: Out<StartFlow>["credentialType"],
86
+ context: {
87
+ wiaCryptoContext: CryptoContext;
88
+ credentialCryptoContext: CryptoContext;
89
+ authorizationContext?: AuthorizationContext;
90
+ walletInstanceAttestation: string;
91
+ redirectUri: string;
92
+ idphint: string;
93
+ appFetch?: GlobalFetch["fetch"];
94
+ }
95
+ ) => Promise<CredentialResponse>;
96
+
97
+ /**
98
+ * Starts the credential issuance flow to obtain a credential from the issuer.
99
+ * @param issuerConf The Issuer configuration
100
+ * @param credentialType The type of the credential to be requested
101
+ * @param context.wiaCryptoContext The context to access the key associated with the Wallet Instance Attestation
102
+ * @param context.credentialCryptoContext The context to access the key to associat with credential
103
+ * @param context.walletInstanceAttestation The Wallet Instance Attestation token
104
+ * @param context.authorizationContext The context to identify the user which will be used to start the authorization. It's needed only when requesting a PersonalIdentificationData credential. The implementantion should open an in-app browser capable of catching the redirectSchema. If not specified, the default browser is used.
105
+ * @param context.redirectUri The internal URL to which to redirect has passed the in-app browser login phase. If you don't use authorizationContext remember to register this URL as customUrl or deepLink. See https://reactnative.dev/docs/linking
106
+ * @param context.idphint Unique identifier of the SPID IDP
107
+ * @param context.appFetch (optional) fetch api implementation. Default: built-in fetch
108
+ * @throws {AuthorizationError} When the response from the authorization response is not parsable
109
+ * @returns The credential obtained
110
+ */
111
+
112
+ export const startCredentialIssuance: StartCredentialIssuance = async (
113
+ issuerConf,
114
+ credentialType,
115
+ ctx
116
+ ) => {
117
+ const {
118
+ wiaCryptoContext,
119
+ credentialCryptoContext,
120
+ walletInstanceAttestation,
121
+ authorizationContext,
122
+ redirectUri,
123
+ idphint,
124
+ appFetch = fetch,
125
+ } = ctx;
126
+
127
+ /**
128
+ * Creates and sends a PAR request to the /as/par endpoint of the authroization server.
129
+ * This starts the authentication flow to obtain an access token.
130
+ * This token enables the Wallet Instance to request a digital credential from the Credential Endpoint of the Credential Issuer.
131
+ * This is an HTTP POST request containing the Wallet Instance identifier (client id), the code challenge and challenge method as specified by PKCE according to RFC 9126
132
+ * along with the WTE and its proof of possession (WTE-PoP).
133
+ * Additionally, it includes a request object, which is a signed JWT encapsulating the type of digital credential requested (authorization_details),
134
+ * the application session identifier on the Wallet Instance side (state),
135
+ * the method (query or form_post.jwt) by which the Authorization Server
136
+ * should transmit the Authorization Response containing the authorization code issued upon the end user's authentication (response_mode)
137
+ * to the Wallet Instance's Token Endpoint to obtain the Access Token, and the redirect_uri of the Wallet Instance where the Authorization Response
138
+ * should be delivered. The redirect is achived by using a custom URL scheme that the Wallet Instance is registered to handle.
139
+ */
140
+ const clientId = await wiaCryptoContext.getPublicKey().then((_) => _.kid);
141
+ const codeVerifier = generateRandomAlphaNumericString(64);
142
+ const parEndpoint =
143
+ issuerConf.oauth_authorization_server.pushed_authorization_request_endpoint;
144
+ const parUrl = new URL(parEndpoint);
145
+ const aud = `${parUrl.protocol}//${parUrl.hostname}`;
146
+ const iss = WalletInstanceAttestation.decode(walletInstanceAttestation)
147
+ .payload.cnf.jwk.kid;
148
+ const credentialDefinition = selectCredentialDefinition(
149
+ issuerConf,
150
+ credentialType
151
+ );
152
+ const responseMode = selectResponseMode(issuerConf, credentialType);
153
+
154
+ const getPar = makeParRequest({ wiaCryptoContext, appFetch });
155
+ const issuerRequestUri = await getPar(
156
+ clientId,
157
+ codeVerifier,
158
+ redirectUri,
159
+ responseMode,
160
+ parEndpoint,
161
+ walletInstanceAttestation,
162
+ [credentialDefinition],
163
+ ASSERTION_TYPE
164
+ );
165
+
166
+ /**
167
+ * Starts the authorization flow which dependes on the response mode and the request credential.
168
+ * If the response mode is "query" the authorization flow is handled differently via the authorization context which opens an in-app browser capable of catching the redirectSchema.
169
+ * The form_post.jwt mode is not currently supported.
170
+ */
171
+ const authorizeFlowResult = await (async () => {
172
+ const authzRequestEndpoint =
173
+ issuerConf.oauth_authorization_server.authorization_endpoint;
174
+ if (responseMode === "query") {
175
+ const params = new URLSearchParams({
176
+ client_id: clientId,
177
+ request_uri: issuerRequestUri,
178
+ idphint,
179
+ });
180
+
181
+ /**
182
+ * Starts the authorization flow to obtain an authorization code by performing a GET request to the /authorize endpoint of the authorization server.
183
+ */
184
+ return await authorizeUserWithQueryMode(
185
+ authzRequestEndpoint,
186
+ params,
187
+ redirectUri,
188
+ authorizationContext
189
+ );
190
+ } else {
191
+ throw new AuthorizationError(
192
+ "Response mode not supported for this type of credential"
193
+ );
194
+ }
195
+ })();
196
+
197
+ /**
198
+ * Creates and sends the DPoP Proof JWT to be presented with the authorization code to the /token endpoint of the authorization server
199
+ * for requesting the issuance of an access token bound to the public key of the Wallet Instance contained within the DPoP.
200
+ * This enables the Wallet Instance to request a digital credential.
201
+ * The DPoP Proof JWT is generated according to the section 4.3 of the DPoP RFC 9449 specification.
202
+ */
203
+
204
+ const { code } = authorizeFlowResult;
205
+ const tokenUrl = issuerConf.oauth_authorization_server.token_endpoint;
206
+ // Use an ephemeral key to be destroyed after use
207
+ const tokenRequestSignedDPop = await withEphemeralKey(
208
+ async (ephimeralContext) => {
209
+ return await createDPopToken(
210
+ {
211
+ htm: "POST",
212
+ htu: tokenUrl,
213
+ jti: `${uuid.v4()}`,
214
+ },
215
+ ephimeralContext
216
+ );
217
+ }
218
+ );
219
+
220
+ const signedWiaPoP = await createPopToken(
221
+ {
222
+ jti: `${uuid.v4()}`,
223
+ aud,
224
+ iss,
225
+ },
226
+ wiaCryptoContext
227
+ );
228
+
229
+ const requestBody = {
230
+ grant_type: "authorization_code",
231
+ client_id: clientId,
232
+ code,
233
+ redirect_uri: redirectUri,
234
+ code_verifier: codeVerifier,
235
+ client_assertion_type: ASSERTION_TYPE,
236
+ client_assertion: walletInstanceAttestation + "~" + signedWiaPoP,
237
+ };
238
+
239
+ const authorizationRequestFormBody = new URLSearchParams(requestBody);
240
+ const tokenRes = await appFetch(tokenUrl, {
241
+ method: "POST",
242
+ headers: {
243
+ "Content-Type": "application/x-www-form-urlencoded",
244
+ DPoP: tokenRequestSignedDPop,
245
+ },
246
+ body: authorizationRequestFormBody.toString(),
247
+ })
248
+ .then(hasStatus(200))
249
+ .then((res) => res.json())
250
+ .then((body) => TokenResponse.safeParse(body));
251
+
252
+ if (!tokenRes.success) {
253
+ throw new ValidationFailed(tokenRes.error.message);
254
+ }
255
+
256
+ /**
257
+ * Validates the token response and extracts the access token, c_nonce and c_nonce_expires_in.
258
+ */
259
+ const accessTokenResponse = tokenRes.data;
260
+ const credentialUrl = issuerConf.openid_credential_issuer.credential_endpoint;
261
+
262
+ /**
263
+ * JWT proof token to bind the request nonce to the key that will bind the holder User with the Credential
264
+ * This is presented along with the access token to the Credential Endpoint as proof of possession of the private key used to sign the Access Token.
265
+ * @see https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html#name-proof-types
266
+ */
267
+ const signedNonceProof = await createNonceProof(
268
+ accessTokenResponse.c_nonce,
269
+ clientId,
270
+ credentialUrl,
271
+ credentialCryptoContext
272
+ );
273
+
274
+ // Validation of accessTokenResponse.authorization_details if contain credentialDefinition
275
+ const constainsCredentialDefinition =
276
+ accessTokenResponse.authorization_details.some(
277
+ (c) =>
278
+ c.credential_configuration_id ===
279
+ credentialDefinition.credential_configuration_id &&
280
+ c.format === credentialDefinition.format &&
281
+ c.type === credentialDefinition.type
282
+ );
283
+
284
+ if (!constainsCredentialDefinition) {
285
+ throw new ValidationFailed(
286
+ "The access token response does not contain the requested credential"
287
+ );
288
+ }
289
+
290
+ /** The credential request body */
291
+ const credentialRequestFormBody = {
292
+ credential_definition: {
293
+ type: [credentialDefinition.credential_configuration_id],
294
+ },
295
+ format: credentialDefinition.format,
296
+ proof: {
297
+ jwt: signedNonceProof,
298
+ proof_type: "jwt",
299
+ },
300
+ };
301
+
302
+ const credentialRes = await appFetch(credentialUrl, {
303
+ method: "POST",
304
+ headers: {
305
+ "Content-Type": "application/json",
306
+ DPoP: tokenRequestSignedDPop,
307
+ Authorization: `${accessTokenResponse.token_type} ${accessTokenResponse.access_token}`,
308
+ },
309
+ body: JSON.stringify(credentialRequestFormBody),
310
+ })
311
+ .then(hasStatus(200))
312
+ .then((res) => res.json())
313
+ .then((body) => CredentialResponse.safeParse(body));
314
+
315
+ if (!credentialRes.success) {
316
+ throw new ValidationFailed(credentialRes.error.message);
317
+ }
318
+
319
+ return credentialRes.data;
320
+ };
321
+
322
+ /**
323
+ * Authorizes the user using the query mode and the authorization context.
324
+ * @param authzRequestEndpoint The authorization endpoint of the authorization server
325
+ * @param params The query parameters to be used in the request
326
+ * @param redirectUri The URL to which the redirect is made is usually a custom URL or deeplink
327
+ * @param authorizationContext The AuthorizationContext to manage the internal webview. If not specified, the default browser is used
328
+ * @returns The authrozation result containing the authorization code, state and issuer
329
+ */
330
+ export const authorizeUserWithQueryMode = async (
331
+ authzRequestEndpoint: string,
332
+ params: URLSearchParams,
333
+ redirectUri: string,
334
+ authorizationContext?: AuthorizationContext
335
+ ): Promise<AuthorizationResult> => {
336
+ const authUrl = `${authzRequestEndpoint}?${params}`;
337
+ var authRedirectUrl: string | undefined;
338
+
339
+ if (authorizationContext) {
340
+ const redirectSchema = new URL(redirectUri).protocol.replace(":", "");
341
+ authRedirectUrl = await authorizationContext
342
+ .authorize(authUrl, redirectSchema)
343
+ .catch((e) => {
344
+ throw new AuthorizationError(e.message);
345
+ });
346
+ } else {
347
+ // handler for redirectUri
348
+ Linking.addEventListener("url", ({ url }) => {
349
+ if (url.includes(redirectUri)) {
350
+ authRedirectUrl = url;
351
+ }
352
+ });
353
+
354
+ const openAuthUrlInBrowser = Linking.openURL(authUrl);
355
+
356
+ /*
357
+ * Waits for 120 seconds for the identificationRedirectUrl variable to be set
358
+ * by the custom url handler. If the timeout is exceeded, throw an exception
359
+ */
360
+ const unitAuthRedirectIsNotUndefined = until(
361
+ () => authRedirectUrl !== undefined,
362
+ 120
363
+ );
364
+
365
+ await Promise.all([openAuthUrlInBrowser, unitAuthRedirectIsNotUndefined]);
366
+
367
+ if (authRedirectUrl === undefined) {
368
+ throw new AuthorizationError("Invalid authentication redirect url");
369
+ }
370
+ }
371
+
372
+ const urlParse = parseUrl(authRedirectUrl);
373
+ const authRes = AuthorizationResultShape.safeParse(urlParse.query);
374
+ if (!authRes.success) {
375
+ const authErr = AuthorizationErrorShape.safeParse(urlParse.query);
376
+ if (!authErr.success) {
377
+ throw new AuthorizationError(authRes.error.message); // an error occured while parsing the result and the error
378
+ }
379
+ throw new AuthorizationIdpError(
380
+ authErr.data.error,
381
+ authErr.data.error_description
382
+ );
383
+ }
384
+ return authRes.data;
385
+ };
386
+
387
+ export const createNonceProof = async (
388
+ nonce: string,
389
+ issuer: string,
390
+ audience: string,
391
+ ctx: CryptoContext
392
+ ): Promise<string> => {
393
+ const jwk = await ctx.getPublicKey();
394
+ return new SignJWT(ctx)
395
+ .setPayload({
396
+ nonce,
397
+ })
398
+ .setProtectedHeader({
399
+ typ: "openid4vci-proof+jwt",
400
+ jwk,
401
+ })
402
+ .setAudience(audience)
403
+ .setIssuer(issuer)
404
+ .setIssuedAt()
405
+ .setExpirationTime("5min")
406
+ .sign();
407
+ };