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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/lib/commonjs/client/generated/wallet-provider.js +126 -0
  2. package/lib/commonjs/client/generated/wallet-provider.js.map +1 -0
  3. package/lib/commonjs/client/index.js +40 -0
  4. package/lib/commonjs/client/index.js.map +1 -0
  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 +10 -1
  24. package/lib/commonjs/index.js.map +1 -1
  25. package/lib/commonjs/pid/sd-jwt/converters.js +5 -9
  26. package/lib/commonjs/pid/sd-jwt/converters.js.map +1 -1
  27. package/lib/commonjs/pid/sd-jwt/types.js +3 -3
  28. package/lib/commonjs/pid/sd-jwt/types.js.map +1 -1
  29. package/lib/commonjs/sd-jwt/__test__/converters.test.js +1 -1
  30. package/lib/commonjs/sd-jwt/__test__/converters.test.js.map +1 -1
  31. package/lib/commonjs/sd-jwt/__test__/index.test.js +30 -43
  32. package/lib/commonjs/sd-jwt/__test__/index.test.js.map +1 -1
  33. package/lib/commonjs/sd-jwt/__test__/types.test.js +16 -24
  34. package/lib/commonjs/sd-jwt/__test__/types.test.js.map +1 -1
  35. package/lib/commonjs/sd-jwt/index.js +3 -9
  36. package/lib/commonjs/sd-jwt/index.js.map +1 -1
  37. package/lib/commonjs/sd-jwt/types.js +11 -16
  38. package/lib/commonjs/sd-jwt/types.js.map +1 -1
  39. package/lib/commonjs/trust/types.js +70 -29
  40. package/lib/commonjs/trust/types.js.map +1 -1
  41. package/lib/commonjs/utils/auth.js +44 -0
  42. package/lib/commonjs/utils/auth.js.map +1 -0
  43. package/lib/commonjs/utils/errors.js +104 -1
  44. package/lib/commonjs/utils/errors.js.map +1 -1
  45. package/lib/commonjs/utils/integrity.js +2 -0
  46. package/lib/commonjs/utils/integrity.js.map +1 -0
  47. package/lib/commonjs/utils/misc.js +34 -1
  48. package/lib/commonjs/utils/misc.js.map +1 -1
  49. package/lib/commonjs/utils/par.js +23 -15
  50. package/lib/commonjs/utils/par.js.map +1 -1
  51. package/lib/commonjs/utils/pop.js +33 -0
  52. package/lib/commonjs/utils/pop.js.map +1 -0
  53. package/lib/commonjs/wallet-instance/index.js +29 -0
  54. package/lib/commonjs/wallet-instance/index.js.map +1 -0
  55. package/lib/commonjs/wallet-instance-attestation/issuing.js +62 -65
  56. package/lib/commonjs/wallet-instance-attestation/issuing.js.map +1 -1
  57. package/lib/commonjs/wallet-instance-attestation/types.js +8 -8
  58. package/lib/commonjs/wallet-instance-attestation/types.js.map +1 -1
  59. package/lib/module/client/generated/wallet-provider.js +102 -0
  60. package/lib/module/client/generated/wallet-provider.js.map +1 -0
  61. package/lib/module/client/index.js +33 -0
  62. package/lib/module/client/index.js.map +1 -0
  63. package/lib/module/credential/issuance/02-evaluate-issuer-trust.js +2 -1
  64. package/lib/module/credential/issuance/02-evaluate-issuer-trust.js.map +1 -1
  65. package/lib/module/credential/issuance/03-start-credential-issuance.js +276 -0
  66. package/lib/module/credential/issuance/03-start-credential-issuance.js.map +1 -0
  67. package/lib/module/credential/issuance/03-start-user-authorization.js +56 -80
  68. package/lib/module/credential/issuance/03-start-user-authorization.js.map +1 -1
  69. package/lib/module/credential/issuance/04-complete-user-authorization.js +85 -1
  70. package/lib/module/credential/issuance/04-complete-user-authorization.js.map +1 -1
  71. package/lib/module/credential/issuance/05-authorize-access.js +54 -33
  72. package/lib/module/credential/issuance/05-authorize-access.js.map +1 -1
  73. package/lib/module/credential/issuance/06-obtain-credential.js +50 -75
  74. package/lib/module/credential/issuance/06-obtain-credential.js.map +1 -1
  75. package/lib/module/credential/issuance/07-verify-and-parse-credential.js +21 -44
  76. package/lib/module/credential/issuance/07-verify-and-parse-credential.js.map +1 -1
  77. package/lib/module/credential/issuance/index.js +2 -1
  78. package/lib/module/credential/issuance/index.js.map +1 -1
  79. package/lib/module/credential/issuance/types.js +18 -0
  80. package/lib/module/credential/issuance/types.js.map +1 -0
  81. package/lib/module/index.js +3 -1
  82. package/lib/module/index.js.map +1 -1
  83. package/lib/module/pid/sd-jwt/converters.js +5 -9
  84. package/lib/module/pid/sd-jwt/converters.js.map +1 -1
  85. package/lib/module/pid/sd-jwt/types.js +3 -3
  86. package/lib/module/pid/sd-jwt/types.js.map +1 -1
  87. package/lib/module/sd-jwt/__test__/converters.test.js +1 -1
  88. package/lib/module/sd-jwt/__test__/converters.test.js.map +1 -1
  89. package/lib/module/sd-jwt/__test__/index.test.js +30 -43
  90. package/lib/module/sd-jwt/__test__/index.test.js.map +1 -1
  91. package/lib/module/sd-jwt/__test__/types.test.js +16 -24
  92. package/lib/module/sd-jwt/__test__/types.test.js.map +1 -1
  93. package/lib/module/sd-jwt/index.js +3 -9
  94. package/lib/module/sd-jwt/index.js.map +1 -1
  95. package/lib/module/sd-jwt/types.js +11 -16
  96. package/lib/module/sd-jwt/types.js.map +1 -1
  97. package/lib/module/trust/types.js +70 -29
  98. package/lib/module/trust/types.js.map +1 -1
  99. package/lib/module/utils/auth.js +35 -0
  100. package/lib/module/utils/auth.js.map +1 -0
  101. package/lib/module/utils/errors.js +98 -0
  102. package/lib/module/utils/errors.js.map +1 -1
  103. package/lib/module/utils/integrity.js +2 -0
  104. package/lib/module/utils/integrity.js.map +1 -0
  105. package/lib/module/utils/misc.js +31 -0
  106. package/lib/module/utils/misc.js.map +1 -1
  107. package/lib/module/utils/par.js +24 -16
  108. package/lib/module/utils/par.js.map +1 -1
  109. package/lib/module/utils/pop.js +24 -0
  110. package/lib/module/utils/pop.js.map +1 -0
  111. package/lib/module/wallet-instance/index.js +23 -0
  112. package/lib/module/wallet-instance/index.js.map +1 -0
  113. package/lib/module/wallet-instance-attestation/issuing.js +63 -67
  114. package/lib/module/wallet-instance-attestation/issuing.js.map +1 -1
  115. package/lib/module/wallet-instance-attestation/types.js +8 -8
  116. package/lib/module/wallet-instance-attestation/types.js.map +1 -1
  117. package/lib/typescript/client/generated/wallet-provider.d.ts +264 -0
  118. package/lib/typescript/client/generated/wallet-provider.d.ts.map +1 -0
  119. package/lib/typescript/client/index.d.ts +7 -0
  120. package/lib/typescript/client/index.d.ts.map +1 -0
  121. package/lib/typescript/credential/issuance/01-start-flow.d.ts +1 -0
  122. package/lib/typescript/credential/issuance/01-start-flow.d.ts.map +1 -1
  123. package/lib/typescript/credential/issuance/02-evaluate-issuer-trust.d.ts +2 -1
  124. package/lib/typescript/credential/issuance/02-evaluate-issuer-trust.d.ts.map +1 -1
  125. package/lib/typescript/credential/issuance/03-start-credential-issuance.d.ts +41 -0
  126. package/lib/typescript/credential/issuance/03-start-credential-issuance.d.ts.map +1 -0
  127. package/lib/typescript/credential/issuance/03-start-user-authorization.d.ts +23 -18
  128. package/lib/typescript/credential/issuance/03-start-user-authorization.d.ts.map +1 -1
  129. package/lib/typescript/credential/issuance/04-complete-user-authorization.d.ts +24 -12
  130. package/lib/typescript/credential/issuance/04-complete-user-authorization.d.ts.map +1 -1
  131. package/lib/typescript/credential/issuance/05-authorize-access.d.ts +22 -16
  132. package/lib/typescript/credential/issuance/05-authorize-access.d.ts.map +1 -1
  133. package/lib/typescript/credential/issuance/06-obtain-credential.d.ts +19 -26
  134. package/lib/typescript/credential/issuance/06-obtain-credential.d.ts.map +1 -1
  135. package/lib/typescript/credential/issuance/07-verify-and-parse-credential.d.ts +10 -15
  136. package/lib/typescript/credential/issuance/07-verify-and-parse-credential.d.ts.map +1 -1
  137. package/lib/typescript/credential/issuance/index.d.ts +3 -4
  138. package/lib/typescript/credential/issuance/index.d.ts.map +1 -1
  139. package/lib/typescript/credential/issuance/types.d.ts +63 -0
  140. package/lib/typescript/credential/issuance/types.d.ts.map +1 -0
  141. package/lib/typescript/credential/presentation/types.d.ts +6 -6
  142. package/lib/typescript/index.d.ts +6 -1
  143. package/lib/typescript/index.d.ts.map +1 -1
  144. package/lib/typescript/pid/sd-jwt/converters.d.ts.map +1 -1
  145. package/lib/typescript/pid/sd-jwt/types.d.ts +36 -36
  146. package/lib/typescript/pid/sd-jwt/types.d.ts.map +1 -1
  147. package/lib/typescript/sd-jwt/index.d.ts +40 -68
  148. package/lib/typescript/sd-jwt/index.d.ts.map +1 -1
  149. package/lib/typescript/sd-jwt/types.d.ts +64 -121
  150. package/lib/typescript/sd-jwt/types.d.ts.map +1 -1
  151. package/lib/typescript/trust/index.d.ts +150 -48
  152. package/lib/typescript/trust/index.d.ts.map +1 -1
  153. package/lib/typescript/trust/types.d.ts +2838 -1740
  154. package/lib/typescript/trust/types.d.ts.map +1 -1
  155. package/lib/typescript/utils/auth.d.ts +52 -0
  156. package/lib/typescript/utils/auth.d.ts.map +1 -0
  157. package/lib/typescript/utils/errors.d.ts +48 -0
  158. package/lib/typescript/utils/errors.d.ts.map +1 -1
  159. package/lib/typescript/utils/integrity.d.ts +21 -0
  160. package/lib/typescript/utils/integrity.d.ts.map +1 -0
  161. package/lib/typescript/utils/misc.d.ts +18 -0
  162. package/lib/typescript/utils/misc.d.ts.map +1 -1
  163. package/lib/typescript/utils/par.d.ts +8 -31
  164. package/lib/typescript/utils/par.d.ts.map +1 -1
  165. package/lib/typescript/utils/pop.d.ts +26 -0
  166. package/lib/typescript/utils/pop.d.ts.map +1 -0
  167. package/lib/typescript/wallet-instance/index.d.ts +7 -0
  168. package/lib/typescript/wallet-instance/index.d.ts.map +1 -0
  169. package/lib/typescript/wallet-instance-attestation/issuing.d.ts +17 -4
  170. package/lib/typescript/wallet-instance-attestation/issuing.d.ts.map +1 -1
  171. package/lib/typescript/wallet-instance-attestation/types.d.ts +64 -64
  172. package/lib/typescript/wallet-instance-attestation/types.d.ts.map +1 -1
  173. package/package.json +9 -5
  174. package/src/client/generated/wallet-provider.ts +173 -0
  175. package/src/client/index.ts +53 -0
  176. package/src/credential/issuance/01-start-flow.ts +1 -0
  177. package/src/credential/issuance/02-evaluate-issuer-trust.ts +2 -1
  178. package/src/credential/issuance/03-start-credential-issuance.ts +407 -0
  179. package/src/credential/issuance/03-start-user-authorization.ts +91 -92
  180. package/src/credential/issuance/04-complete-user-authorization.ts +114 -13
  181. package/src/credential/issuance/05-authorize-access.ts +74 -49
  182. package/src/credential/issuance/06-obtain-credential.ts +77 -111
  183. package/src/credential/issuance/07-verify-and-parse-credential.ts +30 -67
  184. package/src/credential/issuance/index.ts +6 -4
  185. package/src/credential/issuance/types.ts +25 -0
  186. package/src/index.ts +8 -0
  187. package/src/pid/sd-jwt/converters.ts +5 -11
  188. package/src/pid/sd-jwt/types.ts +8 -6
  189. package/src/sd-jwt/__test__/converters.test.ts +1 -1
  190. package/src/sd-jwt/__test__/index.test.ts +45 -74
  191. package/src/sd-jwt/__test__/types.test.ts +21 -33
  192. package/src/sd-jwt/index.ts +3 -12
  193. package/src/sd-jwt/types.ts +17 -22
  194. package/src/trust/types.ts +64 -32
  195. package/src/utils/auth.ts +37 -0
  196. package/src/utils/errors.ts +112 -0
  197. package/src/utils/integrity.ts +23 -0
  198. package/src/utils/misc.ts +43 -0
  199. package/src/utils/par.ts +29 -17
  200. package/src/utils/pop.ts +34 -0
  201. package/src/wallet-instance/index.ts +29 -0
  202. package/src/wallet-instance-attestation/issuing.ts +101 -97
  203. package/src/wallet-instance-attestation/types.ts +12 -8
  204. package/lib/commonjs/credential/issuance/07-confirm-credential.js +0 -6
  205. package/lib/commonjs/credential/issuance/07-confirm-credential.js.map +0 -1
  206. package/lib/commonjs/credential/issuance/08-confirm-credential.js +0 -6
  207. package/lib/commonjs/credential/issuance/08-confirm-credential.js.map +0 -1
  208. package/lib/module/credential/issuance/07-confirm-credential.js +0 -2
  209. package/lib/module/credential/issuance/07-confirm-credential.js.map +0 -1
  210. package/lib/module/credential/issuance/08-confirm-credential.js +0 -2
  211. package/lib/module/credential/issuance/08-confirm-credential.js.map +0 -1
  212. package/lib/typescript/credential/issuance/07-confirm-credential.d.ts +0 -11
  213. package/lib/typescript/credential/issuance/07-confirm-credential.d.ts.map +0 -1
  214. package/lib/typescript/credential/issuance/08-confirm-credential.d.ts +0 -11
  215. package/lib/typescript/credential/issuance/08-confirm-credential.d.ts.map +0 -1
  216. package/src/credential/issuance/07-confirm-credential.ts +0 -14
  217. package/src/credential/issuance/08-confirm-credential.ts +0 -14
@@ -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
+ };
@@ -1,24 +1,54 @@
1
- import * as z from "zod";
2
- import uuid from "react-native-uuid";
3
- import { AuthorizationDetail, makeParRequest } from "../../utils/par";
4
1
  import type { CryptoContext } from "@pagopa/io-react-native-jwt";
5
- import { getJwtFromFormPost } from "../../utils/decoder";
6
- import { hasStatus, type Out } from "../../utils/misc";
7
- import type { StartFlow } from "./01-start-flow";
2
+ import type { ResponseMode } from "./types";
3
+ import {
4
+ generateRandomAlphaNumericString,
5
+ type Out,
6
+ } from "../../../src/utils/misc";
7
+
8
8
  import type { EvaluateIssuerTrust } from "./02-evaluate-issuer-trust";
9
+ import type { StartFlow } from "./01-start-flow";
10
+ import { AuthorizationDetail, makeParRequest } from "../../../src/utils/par";
9
11
  import { ASSERTION_TYPE } from "./const";
10
12
 
13
+ export type StartUserAuthorization = (
14
+ issuerConf: Out<EvaluateIssuerTrust>["issuerConf"],
15
+ credentialType: Out<StartFlow>["credentialType"],
16
+ context: {
17
+ wiaCryptoContext: CryptoContext;
18
+ walletInstanceAttestation: string;
19
+ redirectUri: string;
20
+ appFetch?: GlobalFetch["fetch"];
21
+ }
22
+ ) => Promise<{
23
+ issuerRequestUri: string;
24
+ clientId: string;
25
+ codeVerifier: string;
26
+ credentialDefinition: AuthorizationDetail;
27
+ }>;
28
+
29
+ /**
30
+ * Ensures that the credential type requested is supported by the issuer and contained in the
31
+ * issuer configuration.
32
+ * @param issuerConf The issuer configuration returned by {@link evaluateIssuerTrust}
33
+ * @param credentialType The type of the credential to be requested returned by {@link startFlow}
34
+ * @param context.wiaCryptoContext The Wallet Instance's crypto context
35
+ * @param context.walletInstanceAttestation The Wallet Instance's attestation
36
+ * @param context.redirectUri The redirect URI which is the custom URL scheme that the Wallet Instance is registered to handle
37
+ * @param context.appFetch (optional) fetch api implementation. Default: built-in fetch
38
+ * @returns The credential definition to be used in the request which includes the format and the type and its type
39
+ */
11
40
  const selectCredentialDefinition = (
12
41
  issuerConf: Out<EvaluateIssuerTrust>["issuerConf"],
13
42
  credentialType: Out<StartFlow>["credentialType"]
14
43
  ): AuthorizationDetail => {
15
- const { credentials_supported } = issuerConf.openid_credential_issuer;
44
+ const credential_configurations_supported =
45
+ issuerConf.openid_credential_issuer.credential_configurations_supported;
16
46
 
17
- const [result] = credentials_supported
18
- .filter((e) => e.credential_definition.type.includes(credentialType))
47
+ const [result] = Object.keys(credential_configurations_supported)
48
+ .filter((e) => e.includes(credentialType))
19
49
  .map((e) => ({
20
- credential_definition: { type: credentialType },
21
- format: e.format,
50
+ credential_configuration_id: credentialType,
51
+ format: credential_configurations_supported[e]!.format,
22
52
  type: "openid_credential" as const,
23
53
  }));
24
54
 
@@ -28,69 +58,46 @@ const selectCredentialDefinition = (
28
58
  return result;
29
59
  };
30
60
 
31
- const decodeAuthorizationResponse = async (
32
- raw: string
33
- ): Promise<{ request_uri: string }> => {
34
- const {
35
- decodedJwt: { payload },
36
- } = await getJwtFromFormPost(raw);
37
-
38
- /**
39
- * FIXME: [SIW-628] This step must not make any difference on the credential
40
- * we are authorizing for, being a PID or any other (Q)EAA.
41
- *
42
- * Currently, PID issuer is implemented to skip the CompleteUserAuthorization step
43
- * thus returning a stubbed (code, state) pair.
44
- *
45
- * This is a workaround to proceeed the flow anyway.
46
- * If the response does not map what expected (CorrectShape),
47
- * we try parse into (code, state) to check if we are in the PID scenario.
48
- * In that case, a stub value is returned (will not be evaluated anyway).
49
- *
50
- * This workaround will be obsolete once the PID issuer fixes its implementation
51
- */
52
- const CorrectShape = z.object({ request_uri: z.string() });
53
- const WrongShapeForPID = z.object({ code: z.string(), state: z.string() });
61
+ /**
62
+ * Ensures that the response mode requested is supported by the issuer and contained in the issuer configuration.
63
+ * @param issuerConf The issuer configuration
64
+ * @param credentialType The type of the credential to be requested
65
+ * @returns The response mode to be used in the request, "query" for PersonIdentificationData and "form_post.jwt" for all other types.
66
+ */
67
+ const selectResponseMode = (
68
+ issuerConf: Out<EvaluateIssuerTrust>["issuerConf"],
69
+ credentialType: Out<StartFlow>["credentialType"]
70
+ ): ResponseMode => {
71
+ const responseModeSupported =
72
+ issuerConf.oauth_authorization_server.response_modes_supported;
54
73
 
55
- const [correct, wrong] = [
56
- CorrectShape.safeParse(payload),
57
- WrongShapeForPID.safeParse(payload),
58
- ];
74
+ const responseMode =
75
+ credentialType === "PersonIdentificationData" ? "query" : "form_post.jwt";
59
76
 
60
- if (correct.success) {
61
- return correct.data;
62
- } else if (wrong.success) {
63
- return { request_uri: "https://fake-request-uri" };
77
+ if (!responseModeSupported.includes(responseMode)) {
78
+ throw new Error(`No response mode support the type '${credentialType}'`);
64
79
  }
65
- throw correct.error;
66
- };
67
80
 
68
- export type StartUserAuthorization = (
69
- issuerConf: Out<EvaluateIssuerTrust>["issuerConf"],
70
- credentialType: Out<StartFlow>["credentialType"],
71
- context: {
72
- wiaCryptoContext: CryptoContext;
73
- walletInstanceAttestation: string;
74
- walletProviderBaseUrl: string;
75
- additionalParams?: Record<string, string>;
76
- appFetch?: GlobalFetch["fetch"];
77
- }
78
- ) => Promise<{ requestUri: string; clientId: string }>;
81
+ return responseMode;
82
+ };
79
83
 
80
84
  /**
81
- * Start the User authorization phase.
82
- * Perform the Pushed Authorization Request as defined in OAuth 2.0 protocol.
83
- *
84
- * @param issuerConf The Issuer configuration
85
- * @param credentialType The type of the credential to be requested
86
- * @param context.wiaCryptoContext The context to access the key associated with the Wallet Instance Attestation
87
- * @param context.walletInstanceAttestation The Wallet Instance Attestation token
88
- * @param context.walletProviderBaseUrl The base url of the Wallet Provider
89
- * @param context.additionalParams Hash set of parameters to be passed to the authorization endpoint
90
- * (used as a temporary fix until we have a proper User identity in the PID token provider)
91
- * TODO: [SIW-630]
92
- * @param context.appFetch (optional) fetch api implementation. Default: built-in fetch
93
- * @returns The request uri to continue the authorization to
85
+ * WARNING: This function must be called after {@link evaluateIssuerTrust} and {@link startFlow}. The next steam is {@link compeUserAuthorizationWithQueryMode} or {@link compeUserAuthorizationWithFormPostJwtMode}
86
+ * Creates and sends a PAR request to the /as/par endpoint of the authroization server.
87
+ * This starts the authentication flow to obtain an access token.
88
+ * This token enables the Wallet Instance to request a digital credential from the Credential Endpoint of the Credential Issuer.
89
+ * 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
90
+ * along with the WTE and its proof of possession (WTE-PoP).
91
+ * Additionally, it includes a request object, which is a signed JWT encapsulating the type of digital credential requested (authorization_details),
92
+ * the application session identifier on the Wallet Instance side (state),
93
+ * the method (query or form_post.jwt) by which the Authorization Server
94
+ * should transmit the Authorization Response containing the authorization code issued upon the end user's authentication (response_mode)
95
+ * to the Wallet Instance's Token Endpoint to obtain the Access Token, and the redirect_uri of the Wallet Instance where the Authorization Response
96
+ * should be delivered. The redirect is achived by using a custom URL scheme that the Wallet Instance is registered to handle.
97
+ * @param issuerConf The issuer configuration
98
+ * @param credentialType The type of the credential to be requested returned by {@link selectCredentialDefinition}
99
+ * @param ctx The context object containing the Wallet Instance's cryptographic context, the Wallet Instance's attestation, the redirect URI and the fetch implementation
100
+ * @returns The URI to which the end user should be redirected to start the authentication flow, along with the client id, the code verifier and the credential definition
94
101
  */
95
102
  export const startUserAuthorization: StartUserAuthorization = async (
96
103
  issuerConf,
@@ -100,39 +107,31 @@ export const startUserAuthorization: StartUserAuthorization = async (
100
107
  const {
101
108
  wiaCryptoContext,
102
109
  walletInstanceAttestation,
103
- walletProviderBaseUrl,
104
- additionalParams = {},
110
+ redirectUri,
105
111
  appFetch = fetch,
106
112
  } = ctx;
113
+
107
114
  const clientId = await wiaCryptoContext.getPublicKey().then((_) => _.kid);
108
- const codeVerifier = `${uuid.v4()}`;
109
- // Make a PAR request to the credential issuer and return the response url
110
- const parUrl =
111
- issuerConf.openid_credential_issuer.pushed_authorization_request_endpoint;
115
+ const codeVerifier = generateRandomAlphaNumericString(64);
116
+ const parEndpoint =
117
+ issuerConf.oauth_authorization_server.pushed_authorization_request_endpoint;
118
+ const credentialDefinition = selectCredentialDefinition(
119
+ issuerConf,
120
+ credentialType
121
+ );
122
+ const responseMode = selectResponseMode(issuerConf, credentialType);
123
+
112
124
  const getPar = makeParRequest({ wiaCryptoContext, appFetch });
113
125
  const issuerRequestUri = await getPar(
114
126
  clientId,
115
127
  codeVerifier,
116
- walletProviderBaseUrl,
117
- parUrl,
128
+ redirectUri,
129
+ responseMode,
130
+ parEndpoint,
118
131
  walletInstanceAttestation,
119
- [selectCredentialDefinition(issuerConf, credentialType)],
132
+ [credentialDefinition],
120
133
  ASSERTION_TYPE
121
134
  );
122
135
 
123
- // Initialize authorization by requesting the authz request uri
124
- const authzRequestEndpoint =
125
- issuerConf.openid_credential_issuer.authorization_endpoint;
126
- const params = new URLSearchParams({
127
- client_id: clientId,
128
- request_uri: issuerRequestUri,
129
- ...additionalParams,
130
- });
131
-
132
- const { request_uri } = await appFetch(`${authzRequestEndpoint}?${params}`)
133
- .then(hasStatus(200))
134
- .then((res) => res.text())
135
- .then(decodeAuthorizationResponse);
136
-
137
- return { requestUri: request_uri, clientId };
136
+ return { issuerRequestUri, clientId, codeVerifier, credentialDefinition };
138
137
  };