@pagopa/io-react-native-wallet 0.27.1 → 0.28.1

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 (153) hide show
  1. package/lib/commonjs/client/generated/wallet-provider.js +27 -19
  2. package/lib/commonjs/client/generated/wallet-provider.js.map +1 -1
  3. package/lib/commonjs/credential/issuance/03-start-user-authorization.js +3 -0
  4. package/lib/commonjs/credential/issuance/03-start-user-authorization.js.map +1 -1
  5. package/lib/commonjs/credential/presentation/01-start-flow.js +14 -24
  6. package/lib/commonjs/credential/presentation/01-start-flow.js.map +1 -1
  7. package/lib/commonjs/credential/presentation/03-get-request-object.js +30 -42
  8. package/lib/commonjs/credential/presentation/03-get-request-object.js.map +1 -1
  9. package/lib/commonjs/credential/presentation/04-retrieve-rp-jwks.js +32 -0
  10. package/lib/commonjs/credential/presentation/04-retrieve-rp-jwks.js.map +1 -0
  11. package/lib/commonjs/credential/presentation/05-verify-request-object.js +53 -0
  12. package/lib/commonjs/credential/presentation/05-verify-request-object.js.map +1 -0
  13. package/lib/commonjs/credential/presentation/06-fetch-presentation-definition.js +39 -0
  14. package/lib/commonjs/credential/presentation/06-fetch-presentation-definition.js.map +1 -0
  15. package/lib/commonjs/credential/presentation/07-evaluate-dcql-query.js +125 -0
  16. package/lib/commonjs/credential/presentation/07-evaluate-dcql-query.js.map +1 -0
  17. package/lib/commonjs/credential/presentation/07-evaluate-input-descriptor.js +289 -0
  18. package/lib/commonjs/credential/presentation/07-evaluate-input-descriptor.js.map +1 -0
  19. package/lib/commonjs/credential/presentation/08-send-authorization-response.js +170 -0
  20. package/lib/commonjs/credential/presentation/08-send-authorization-response.js.map +1 -0
  21. package/lib/commonjs/credential/presentation/errors.js +69 -1
  22. package/lib/commonjs/credential/presentation/errors.js.map +1 -1
  23. package/lib/commonjs/credential/presentation/index.js +29 -1
  24. package/lib/commonjs/credential/presentation/index.js.map +1 -1
  25. package/lib/commonjs/credential/presentation/types.js +124 -3
  26. package/lib/commonjs/credential/presentation/types.js.map +1 -1
  27. package/lib/commonjs/sd-jwt/index.js +41 -1
  28. package/lib/commonjs/sd-jwt/index.js.map +1 -1
  29. package/lib/commonjs/trust/chain.js +35 -50
  30. package/lib/commonjs/trust/chain.js.map +1 -1
  31. package/lib/commonjs/trust/index.js +139 -16
  32. package/lib/commonjs/trust/index.js.map +1 -1
  33. package/lib/commonjs/trust/types.js +36 -12
  34. package/lib/commonjs/trust/types.js.map +1 -1
  35. package/lib/commonjs/trust/utils.js +41 -0
  36. package/lib/commonjs/trust/utils.js.map +1 -0
  37. package/lib/commonjs/utils/jwk.js +5 -1
  38. package/lib/commonjs/utils/jwk.js.map +1 -1
  39. package/lib/commonjs/wallet-instance/index.js +10 -0
  40. package/lib/commonjs/wallet-instance/index.js.map +1 -1
  41. package/lib/module/client/generated/wallet-provider.js +22 -15
  42. package/lib/module/client/generated/wallet-provider.js.map +1 -1
  43. package/lib/module/credential/issuance/03-start-user-authorization.js +3 -0
  44. package/lib/module/credential/issuance/03-start-user-authorization.js.map +1 -1
  45. package/lib/module/credential/presentation/01-start-flow.js +14 -24
  46. package/lib/module/credential/presentation/01-start-flow.js.map +1 -1
  47. package/lib/module/credential/presentation/03-get-request-object.js +31 -43
  48. package/lib/module/credential/presentation/03-get-request-object.js.map +1 -1
  49. package/lib/module/credential/presentation/04-retrieve-rp-jwks.js +25 -0
  50. package/lib/module/credential/presentation/04-retrieve-rp-jwks.js.map +1 -0
  51. package/lib/module/credential/presentation/05-verify-request-object.js +46 -0
  52. package/lib/module/credential/presentation/05-verify-request-object.js.map +1 -0
  53. package/lib/module/credential/presentation/06-fetch-presentation-definition.js +32 -0
  54. package/lib/module/credential/presentation/06-fetch-presentation-definition.js.map +1 -0
  55. package/lib/module/credential/presentation/07-evaluate-dcql-query.js +117 -0
  56. package/lib/module/credential/presentation/07-evaluate-dcql-query.js.map +1 -0
  57. package/lib/module/credential/presentation/07-evaluate-input-descriptor.js +278 -0
  58. package/lib/module/credential/presentation/07-evaluate-input-descriptor.js.map +1 -0
  59. package/lib/module/credential/presentation/08-send-authorization-response.js +158 -0
  60. package/lib/module/credential/presentation/08-send-authorization-response.js.map +1 -0
  61. package/lib/module/credential/presentation/errors.js +64 -0
  62. package/lib/module/credential/presentation/errors.js.map +1 -1
  63. package/lib/module/credential/presentation/index.js +6 -2
  64. package/lib/module/credential/presentation/index.js.map +1 -1
  65. package/lib/module/credential/presentation/types.js +121 -2
  66. package/lib/module/credential/presentation/types.js.map +1 -1
  67. package/lib/module/sd-jwt/index.js +40 -1
  68. package/lib/module/sd-jwt/index.js.map +1 -1
  69. package/lib/module/trust/chain.js +32 -46
  70. package/lib/module/trust/chain.js.map +1 -1
  71. package/lib/module/trust/index.js +139 -18
  72. package/lib/module/trust/index.js.map +1 -1
  73. package/lib/module/trust/types.js +34 -11
  74. package/lib/module/trust/types.js.map +1 -1
  75. package/lib/module/trust/utils.js +33 -0
  76. package/lib/module/trust/utils.js.map +1 -0
  77. package/lib/module/utils/jwk.js +3 -0
  78. package/lib/module/utils/jwk.js.map +1 -1
  79. package/lib/module/wallet-instance/index.js +9 -0
  80. package/lib/module/wallet-instance/index.js.map +1 -1
  81. package/lib/typescript/client/generated/wallet-provider.d.ts +91 -54
  82. package/lib/typescript/client/generated/wallet-provider.d.ts.map +1 -1
  83. package/lib/typescript/credential/issuance/03-start-user-authorization.d.ts.map +1 -1
  84. package/lib/typescript/credential/presentation/01-start-flow.d.ts +26 -5
  85. package/lib/typescript/credential/presentation/01-start-flow.d.ts.map +1 -1
  86. package/lib/typescript/credential/presentation/03-get-request-object.d.ts +7 -10
  87. package/lib/typescript/credential/presentation/03-get-request-object.d.ts.map +1 -1
  88. package/lib/typescript/credential/presentation/04-retrieve-rp-jwks.d.ts +23 -0
  89. package/lib/typescript/credential/presentation/04-retrieve-rp-jwks.d.ts.map +1 -0
  90. package/lib/typescript/credential/presentation/05-verify-request-object.d.ts +18 -0
  91. package/lib/typescript/credential/presentation/05-verify-request-object.d.ts.map +1 -0
  92. package/lib/typescript/credential/presentation/06-fetch-presentation-definition.d.ts +21 -0
  93. package/lib/typescript/credential/presentation/06-fetch-presentation-definition.d.ts.map +1 -0
  94. package/lib/typescript/credential/presentation/07-evaluate-dcql-query.d.ts +20 -0
  95. package/lib/typescript/credential/presentation/07-evaluate-dcql-query.d.ts.map +1 -0
  96. package/lib/typescript/credential/presentation/07-evaluate-input-descriptor.d.ts +88 -0
  97. package/lib/typescript/credential/presentation/07-evaluate-input-descriptor.d.ts.map +1 -0
  98. package/lib/typescript/credential/presentation/08-send-authorization-response.d.ts +70 -0
  99. package/lib/typescript/credential/presentation/08-send-authorization-response.d.ts.map +1 -0
  100. package/lib/typescript/credential/presentation/errors.d.ts +44 -0
  101. package/lib/typescript/credential/presentation/errors.d.ts.map +1 -1
  102. package/lib/typescript/credential/presentation/index.d.ts +7 -3
  103. package/lib/typescript/credential/presentation/index.d.ts.map +1 -1
  104. package/lib/typescript/credential/presentation/types.d.ts +747 -10
  105. package/lib/typescript/credential/presentation/types.d.ts.map +1 -1
  106. package/lib/typescript/credential/status/types.d.ts +6 -6
  107. package/lib/typescript/sd-jwt/index.d.ts +31 -12
  108. package/lib/typescript/sd-jwt/index.d.ts.map +1 -1
  109. package/lib/typescript/sd-jwt/types.d.ts +6 -6
  110. package/lib/typescript/trust/chain.d.ts +4 -9
  111. package/lib/typescript/trust/chain.d.ts.map +1 -1
  112. package/lib/typescript/trust/index.d.ts +337 -61
  113. package/lib/typescript/trust/index.d.ts.map +1 -1
  114. package/lib/typescript/trust/types.d.ts +4074 -407
  115. package/lib/typescript/trust/types.d.ts.map +1 -1
  116. package/lib/typescript/trust/utils.d.ts +12 -0
  117. package/lib/typescript/trust/utils.d.ts.map +1 -0
  118. package/lib/typescript/utils/decoder.d.ts +1 -1
  119. package/lib/typescript/utils/decoder.d.ts.map +1 -1
  120. package/lib/typescript/utils/jwk.d.ts +137 -0
  121. package/lib/typescript/utils/jwk.d.ts.map +1 -1
  122. package/lib/typescript/wallet-instance/index.d.ts +8 -0
  123. package/lib/typescript/wallet-instance/index.d.ts.map +1 -1
  124. package/lib/typescript/wallet-instance-attestation/types.d.ts +36 -36
  125. package/package.json +5 -2
  126. package/src/client/generated/wallet-provider.ts +28 -19
  127. package/src/credential/issuance/03-start-user-authorization.ts +3 -0
  128. package/src/credential/presentation/01-start-flow.ts +19 -26
  129. package/src/credential/presentation/03-get-request-object.ts +35 -58
  130. package/src/credential/presentation/04-retrieve-rp-jwks.ts +34 -0
  131. package/src/credential/presentation/05-verify-request-object.ts +52 -0
  132. package/src/credential/presentation/06-fetch-presentation-definition.ts +48 -0
  133. package/src/credential/presentation/07-evaluate-dcql-query.ts +166 -0
  134. package/src/credential/presentation/07-evaluate-input-descriptor.ts +391 -0
  135. package/src/credential/presentation/08-send-authorization-response.ts +220 -0
  136. package/src/credential/presentation/errors.ts +64 -0
  137. package/src/credential/presentation/index.ts +22 -1
  138. package/src/credential/presentation/types.ts +133 -2
  139. package/src/sd-jwt/index.ts +49 -1
  140. package/src/trust/chain.ts +46 -66
  141. package/src/trust/index.ts +185 -20
  142. package/src/trust/types.ts +34 -10
  143. package/src/trust/utils.ts +35 -0
  144. package/src/utils/decoder.ts +1 -1
  145. package/src/utils/jwk.ts +8 -1
  146. package/src/wallet-instance/index.ts +13 -0
  147. package/lib/commonjs/credential/presentation/04-send-authorization-response.js +0 -138
  148. package/lib/commonjs/credential/presentation/04-send-authorization-response.js.map +0 -1
  149. package/lib/module/credential/presentation/04-send-authorization-response.js +0 -128
  150. package/lib/module/credential/presentation/04-send-authorization-response.js.map +0 -1
  151. package/lib/typescript/credential/presentation/04-send-authorization-response.d.ts +0 -34
  152. package/lib/typescript/credential/presentation/04-send-authorization-response.d.ts.map +0 -1
  153. package/src/credential/presentation/04-send-authorization-response.ts +0 -168
@@ -0,0 +1,391 @@
1
+ import { InputDescriptor, type LegacyRemotePresentation } from "./types";
2
+ import { SdJwt4VC, type DisclosureWithEncoded } from "../../sd-jwt/types";
3
+ import { decode, prepareVpToken } from "../../sd-jwt";
4
+ import { createCryptoContextFor } from "../../utils/crypto";
5
+ import { JSONPath } from "jsonpath-plus";
6
+ import { CredentialNotFoundError, MissingDataError } from "./errors";
7
+ import Ajv from "ajv";
8
+
9
+ const ajv = new Ajv({ allErrors: true });
10
+ const INDEX_CLAIM_NAME = 1;
11
+
12
+ export type EvaluatedDisclosures = {
13
+ requiredDisclosures: DisclosureWithEncoded[];
14
+ optionalDisclosures: DisclosureWithEncoded[];
15
+ unrequestedDisclosures: DisclosureWithEncoded[];
16
+ };
17
+
18
+ export type EvaluateInputDescriptorSdJwt4VC = (
19
+ inputDescriptor: InputDescriptor,
20
+ payloadCredential: SdJwt4VC["payload"],
21
+ disclosures: DisclosureWithEncoded[]
22
+ ) => EvaluatedDisclosures;
23
+
24
+ export type EvaluateInputDescriptors = (
25
+ descriptors: InputDescriptor[],
26
+ credentialsSdJwt: [string /* keyTag */, string /* credential */][]
27
+ ) => Promise<
28
+ {
29
+ evaluatedDisclosure: EvaluatedDisclosures;
30
+ inputDescriptor: InputDescriptor;
31
+ credential: string;
32
+ keyTag: string;
33
+ }[]
34
+ >;
35
+
36
+ export type PrepareRemotePresentations = (
37
+ credentialAndDescriptors: {
38
+ requestedClaims: string[];
39
+ inputDescriptor: InputDescriptor;
40
+ credential: string;
41
+ keyTag: string;
42
+ }[],
43
+ nonce: string,
44
+ client_id: string
45
+ ) => Promise<LegacyRemotePresentation[]>;
46
+
47
+ /**
48
+ * Transforms an array of DisclosureWithEncoded objects into a key-value map.
49
+ * @param disclosures - An array of DisclosureWithEncoded, each containing a decoded property with [?, claimName, claimValue].
50
+ * @returns An object mapping claim names to their corresponding values.
51
+ */
52
+ const mapDisclosuresToObject = (
53
+ disclosures: DisclosureWithEncoded[]
54
+ ): Record<string, unknown> => {
55
+ return disclosures.reduce(
56
+ (obj, { decoded }) => {
57
+ const [, claimName, claimValue] = decoded;
58
+ obj[claimName] = claimValue;
59
+ return obj;
60
+ },
61
+ {} as Record<string, unknown>
62
+ );
63
+ };
64
+
65
+ /**
66
+ * Finds a claim within the payload based on provided JSONPath expressions.
67
+ * @param paths - An array of JSONPath expressions to search for in the payload.
68
+ * @param payload - The object to search within using JSONPath.
69
+ * @returns A tuple with the first matched JSONPath and its corresponding value, or [undefined, undefined] if not found.
70
+ */
71
+ const findMatchedClaim = (
72
+ paths: string[],
73
+ payload: any
74
+ ): [string?, string?] => {
75
+ let matchedPath;
76
+ let matchedValue;
77
+ paths.some((singlePath) => {
78
+ try {
79
+ const result = JSONPath({ path: singlePath, json: payload });
80
+ if (result.length > 0) {
81
+ matchedPath = singlePath;
82
+ matchedValue = result[0];
83
+ return true;
84
+ }
85
+ } catch (error) {
86
+ throw new MissingDataError(
87
+ `JSONPath for "${singlePath}" does not match the provided payload.`
88
+ );
89
+ }
90
+ return false;
91
+ });
92
+
93
+ return [matchedPath, matchedValue];
94
+ };
95
+
96
+ /**
97
+ * Extracts the claim name from a path that can be in one of the following formats:
98
+ * 1. $.propertyName
99
+ * 2. $["propertyName"] or $['propertyName']
100
+ *
101
+ * @param path - The path string containing the claim reference.
102
+ * @returns The extracted claim name if matched; otherwise, throws an exception.
103
+ */
104
+ const extractClaimName = (path: string): string | undefined => {
105
+ // Define a regular expression that matches both formats:
106
+ // 1. $.propertyName
107
+ // 2. $["propertyName"] or $['propertyName']
108
+ const regex = /^\$\.(\w+)$|^\$\[(?:'|")(\w+)(?:'|")\]$/;
109
+
110
+ const match = path.match(regex);
111
+ if (match) {
112
+ // match[1] corresponds to the first capture group (\w+) after $.
113
+ // match[2] corresponds to the second capture group (\w+) inside [""] or ['']
114
+ return match[1] || match[2];
115
+ }
116
+
117
+ // If the input doesn't match any of the expected formats, return null
118
+
119
+ throw new Error(
120
+ `Invalid input format: "${path}". Expected formats are "$.propertyName", "$['propertyName']", or '$["propertyName"]'.`
121
+ );
122
+ };
123
+
124
+ /**
125
+ * Evaluates an InputDescriptor for an SD-JWT-based verifiable credential.
126
+ *
127
+ * - Checks each field in the InputDescriptor against the provided `payloadCredential`
128
+ * and `disclosures` (selectively disclosed claims).
129
+ * - Validates whether required fields are present (unless marked optional)
130
+ * and match any specified JSONPath.
131
+ * - If a field includes a JSON Schema filter, validates the claim value against that schema.
132
+ * - Enforces `limit_disclosure` rules by returning only disclosures, required and optional, matching the specified fields
133
+ * if set to "required". Otherwise also return the array unrequestedDisclosures with disclosures which can be passed for a particular use case.
134
+ * - Throws an error if a required field is invalid or missing.
135
+ *
136
+ * @param inputDescriptor - Describes constraints (fields, filters, etc.) that must be satisfied.
137
+ * @param payloadCredential - The credential payload to check against.
138
+ * @param disclosures - An array of DisclosureWithEncoded objects representing selective disclosures.
139
+ * @returns A filtered list of disclosures satisfying the descriptor constraints, or throws an error if not.
140
+ * @throws Will throw an error if any required constraint fails or if JSONPath lookups are invalid.
141
+ */
142
+ export const evaluateInputDescriptorForSdJwt4VC: EvaluateInputDescriptorSdJwt4VC =
143
+ (inputDescriptor, payloadCredential, disclosures) => {
144
+ if (!inputDescriptor?.constraints?.fields) {
145
+ // No validation, all field are optional
146
+ return {
147
+ requiredDisclosures: [],
148
+ optionalDisclosures: [],
149
+ unrequestedDisclosures: disclosures,
150
+ };
151
+ }
152
+ const requiredClaimNames: string[] = [];
153
+ const optionalClaimNames: string[] = [];
154
+
155
+ // Transform disclosures to find claim using JSONPath
156
+ const disclosuresAsPayload = mapDisclosuresToObject(disclosures);
157
+
158
+ // For each field, we need at least one matching path
159
+ // If we succeed, we push the matched disclosure in matchedDisclosures and stop checking further paths
160
+ const allFieldsValid = inputDescriptor.constraints.fields.every((field) => {
161
+ // For Potential profile, selectively disclosed claims will always be built as an individual object property, by using a name-value pair.
162
+ // Hence that selective claim for array element and recursive disclosures are not supported by Potential for the first iteration of Piloting.
163
+ // We need to check inside disclosures or inside credential payload. Example path: "$.given_name"
164
+ let [matchedPath, matchedValue] = findMatchedClaim(
165
+ field.path,
166
+ disclosuresAsPayload
167
+ );
168
+
169
+ if (!matchedPath) {
170
+ [matchedPath, matchedValue] = findMatchedClaim(
171
+ field.path,
172
+ payloadCredential
173
+ );
174
+
175
+ if (!matchedPath) {
176
+ // Path could be optional, in this case no need to validate! continue to next field
177
+ return field?.optional;
178
+ }
179
+ } else {
180
+ // if match a disclouse we save which is required or optional
181
+ const claimName = extractClaimName(matchedPath);
182
+ if (claimName) {
183
+ (field?.optional ? optionalClaimNames : requiredClaimNames).push(
184
+ claimName
185
+ );
186
+ }
187
+ }
188
+
189
+ // FILTER validation
190
+ // If this field has a "filter" (JSON Schema), validate the claimValue
191
+ if (field.filter) {
192
+ try {
193
+ const validateSchema = ajv.compile(field.filter);
194
+ if (!validateSchema(matchedValue)) {
195
+ throw new MissingDataError(
196
+ `Claim value "${matchedValue}" for path "${matchedPath}" does not match the provided JSON Schema.`
197
+ );
198
+ }
199
+ } catch (error) {
200
+ return false;
201
+ }
202
+ }
203
+ // Submission Requirements validation
204
+ // TODO: [EUDIW-216] Read rule value if “all” o “pick” and validate
205
+
206
+ return true;
207
+ });
208
+
209
+ if (!allFieldsValid) {
210
+ throw new MissingDataError(
211
+ "Credential validation failed: Required fields are missing or do not match the input descriptor."
212
+ );
213
+ }
214
+
215
+ // Categorizes disclosures into required and optional based on claim names and disclosure constraints.
216
+
217
+ const requiredDisclosures = disclosures.filter((disclosure) =>
218
+ requiredClaimNames.includes(disclosure.decoded[INDEX_CLAIM_NAME])
219
+ );
220
+
221
+ const optionalDisclosures = disclosures.filter((disclosure) =>
222
+ optionalClaimNames.includes(disclosure.decoded[INDEX_CLAIM_NAME])
223
+ );
224
+
225
+ const isNotLimitDisclosure = !(
226
+ inputDescriptor.constraints.limit_disclosure === "required"
227
+ );
228
+
229
+ const unrequestedDisclosures = isNotLimitDisclosure
230
+ ? disclosures.filter(
231
+ (disclosure) =>
232
+ !optionalClaimNames.includes(
233
+ disclosure.decoded[INDEX_CLAIM_NAME]
234
+ ) &&
235
+ !requiredClaimNames.includes(disclosure.decoded[INDEX_CLAIM_NAME])
236
+ )
237
+ : [];
238
+
239
+ return {
240
+ requiredDisclosures,
241
+ optionalDisclosures,
242
+ unrequestedDisclosures,
243
+ };
244
+ };
245
+
246
+ type DecodedCredentialSdJwt = {
247
+ keyTag: string;
248
+ credential: string;
249
+ sdJwt: SdJwt4VC;
250
+ disclosures: DisclosureWithEncoded[];
251
+ };
252
+
253
+ /**
254
+ * Finds the first credential that satisfies the input descriptor constraints.
255
+ * @param inputDescriptor The input descriptor to evaluate.
256
+ * @param decodedSdJwtCredentials An array of decoded SD-JWT credentials.
257
+ * @returns An object containing the matched evaluation, keyTag, and credential.
258
+ */
259
+ export const findCredentialSdJwt = (
260
+ inputDescriptor: InputDescriptor,
261
+ decodedSdJwtCredentials: DecodedCredentialSdJwt[]
262
+ ): {
263
+ matchedEvaluation: EvaluatedDisclosures;
264
+ matchedKeyTag: string;
265
+ matchedCredential: string;
266
+ } => {
267
+ for (const {
268
+ keyTag,
269
+ credential,
270
+ sdJwt,
271
+ disclosures,
272
+ } of decodedSdJwtCredentials) {
273
+ try {
274
+ const evaluatedDisclosure = evaluateInputDescriptorForSdJwt4VC(
275
+ inputDescriptor,
276
+ sdJwt.payload,
277
+ disclosures
278
+ );
279
+
280
+ return {
281
+ matchedEvaluation: evaluatedDisclosure,
282
+ matchedKeyTag: keyTag,
283
+ matchedCredential: credential,
284
+ };
285
+ } catch {
286
+ // skip to next credential
287
+ continue;
288
+ }
289
+ }
290
+
291
+ throw new CredentialNotFoundError(
292
+ "None of the vc+sd-jwt credentials satisfy the requirements."
293
+ );
294
+ };
295
+
296
+ /**
297
+ * Evaluates multiple input descriptors against provided SD-JWT and MDOC credentials.
298
+ *
299
+ * For each input descriptor, this function:
300
+ * - Checks the credential format.
301
+ * - Decodes the credential.
302
+ * - Evaluates the descriptor using the associated disclosures.
303
+ *
304
+ * @param inputDescriptors - An array of input descriptors.
305
+ * @param credentialsSdJwt - An array of tuples containing keyTag and SD-JWT credential.
306
+ * @returns An array of objects, each containing the evaluated disclosures,
307
+ * the input descriptor, the credential, and the keyTag.
308
+ * @throws {CredentialNotFoundError} When the credential format is unsupported.
309
+ */
310
+ export const evaluateInputDescriptors: EvaluateInputDescriptors = async (
311
+ inputDescriptors,
312
+ credentialsSdJwt
313
+ ) => {
314
+ // We need decode SD-JWT credentials for evaluation
315
+ const decodedSdJwtCredentials =
316
+ credentialsSdJwt?.map(([keyTag, credential]) => {
317
+ const { sdJwt, disclosures } = decode(credential);
318
+ return { keyTag, credential, sdJwt, disclosures };
319
+ }) || [];
320
+
321
+ return Promise.all(
322
+ inputDescriptors.map(async (descriptor) => {
323
+ if (descriptor.format?.["vc+sd-jwt"]) {
324
+ if (!decodedSdJwtCredentials.length) {
325
+ throw new CredentialNotFoundError(
326
+ "vc+sd-jwt credential is not supported."
327
+ );
328
+ }
329
+
330
+ const { matchedEvaluation, matchedKeyTag, matchedCredential } =
331
+ findCredentialSdJwt(descriptor, decodedSdJwtCredentials);
332
+
333
+ return {
334
+ evaluatedDisclosure: matchedEvaluation,
335
+ inputDescriptor: descriptor,
336
+ credential: matchedCredential,
337
+ keyTag: matchedKeyTag,
338
+ };
339
+ }
340
+
341
+ throw new CredentialNotFoundError(
342
+ `${descriptor.format} format is not supported.`
343
+ );
344
+ })
345
+ );
346
+ };
347
+
348
+ /**
349
+ * Prepares remote presentations for a set of credentials based on input descriptors.
350
+ *
351
+ * For each credential and its corresponding input descriptor, this function:
352
+ * - Validates the credential format.
353
+ * - Generates a verifiable presentation token (vpToken) using the provided nonce and client identifier.
354
+ *
355
+ * @param credentialAndDescriptors - An array containing objects with requested claims,
356
+ * input descriptor, credential, and keyTag.
357
+ * @param nonce - A unique nonce for the verifiable presentation token.
358
+ * @param client_id - The client identifier.
359
+ * @returns A promise that resolves to an array of RemotePresentation objects.
360
+ * @throws {CredentialNotFoundError} When the credential format is unsupported.
361
+ */
362
+ export const prepareRemotePresentations: PrepareRemotePresentations = async (
363
+ credentialAndDescriptors,
364
+ nonce,
365
+ client_id
366
+ ) => {
367
+ return Promise.all(
368
+ credentialAndDescriptors.map(async (item) => {
369
+ const descriptor = item.inputDescriptor;
370
+
371
+ if (descriptor.format?.["vc+sd-jwt"]) {
372
+ const { vp_token } = await prepareVpToken(nonce, client_id, [
373
+ item.credential,
374
+ item.requestedClaims,
375
+ createCryptoContextFor(item.keyTag),
376
+ ]);
377
+
378
+ return {
379
+ requestedClaims: item.requestedClaims,
380
+ inputDescriptor: descriptor,
381
+ vpToken: vp_token,
382
+ format: "vc+sd-jwt",
383
+ };
384
+ }
385
+
386
+ throw new CredentialNotFoundError(
387
+ `${descriptor.format} format is not supported.`
388
+ );
389
+ })
390
+ );
391
+ };
@@ -0,0 +1,220 @@
1
+ import { EncryptJwe } from "@pagopa/io-react-native-jwt";
2
+ import uuid from "react-native-uuid";
3
+ import { getJwksFromConfig, type FetchJwks } from "./04-retrieve-rp-jwks";
4
+ import type { VerifyRequestObject } from "./05-verify-request-object";
5
+ import { NoSuitableKeysFoundInEntityConfiguration } from "./errors";
6
+ import { hasStatusOrThrow, type Out } from "../../utils/misc";
7
+ import {
8
+ type RemotePresentation,
9
+ DirectAuthorizationBodyPayload,
10
+ type LegacyRemotePresentation,
11
+ LegacyDirectAuthorizationBodyPayload,
12
+ } from "./types";
13
+ import * as z from "zod";
14
+ import type { JWK } from "../../utils/jwk";
15
+ import type { RelyingPartyEntityConfiguration } from "../../trust";
16
+
17
+ export type AuthorizationResponse = z.infer<typeof AuthorizationResponse>;
18
+ export const AuthorizationResponse = z.object({
19
+ status: z.string().optional(),
20
+ response_code: z
21
+ .string() /**
22
+ FIXME: [SIW-627] we expect this value from every RP implementation
23
+ Actually some RP does not return the value
24
+ We make it optional to not break the flow.
25
+ */
26
+ .optional(),
27
+ redirect_uri: z.string().optional(),
28
+ });
29
+
30
+ /**
31
+ * Selects a public key (with `use = enc`) from the set of JWK keys
32
+ * offered by the Relying Party (RP) for encryption.
33
+ *
34
+ * @param rpJwkKeys - The array of JWKs retrieved from the RP entity configuration.
35
+ * @returns The first suitable public key found in the list.
36
+ * @throws {NoSuitableKeysFoundInEntityConfiguration} If no suitable encryption key is found.
37
+ */
38
+ export const choosePublicKeyToEncrypt = (
39
+ rpJwkKeys: Out<FetchJwks>["keys"]
40
+ ): JWK => {
41
+ const encKey = rpJwkKeys.find((jwk) => jwk.use === "enc");
42
+
43
+ if (encKey) {
44
+ return encKey;
45
+ }
46
+
47
+ // No suitable key found
48
+ throw new NoSuitableKeysFoundInEntityConfiguration(
49
+ "No suitable public key found for encryption."
50
+ );
51
+ };
52
+
53
+ /**
54
+ * Builds a URL-encoded form body for a direct POST response using JWT encryption.
55
+ *
56
+ * @param jwkKeys - Array of JWKs from the Relying Party for encryption.
57
+ * @param requestObject - Contains state, nonce, and other relevant info.
58
+ * @param payload - Object that contains the VP token to encrypt and the mapping of the credential disclosures
59
+ * @returns A URL-encoded string for an `application/x-www-form-urlencoded` POST body, where `response` contains the encrypted JWE.
60
+ */
61
+ export const buildDirectPostJwtBody = async (
62
+ requestObject: Out<VerifyRequestObject>["requestObject"],
63
+ rpConf: RelyingPartyEntityConfiguration["payload"],
64
+ payload: DirectAuthorizationBodyPayload | LegacyDirectAuthorizationBodyPayload
65
+ ): Promise<string> => {
66
+ type Jwe = ConstructorParameters<typeof EncryptJwe>[1];
67
+
68
+ // Prepare the authorization response payload to be encrypted
69
+ const authzResponsePayload = JSON.stringify({
70
+ state: requestObject.state,
71
+ ...payload,
72
+ });
73
+
74
+ // Choose a suitable public key for encryption
75
+ const { keys } = getJwksFromConfig(rpConf.metadata);
76
+ const encPublicJwk = choosePublicKeyToEncrypt(keys);
77
+
78
+ // Encrypt the authorization payload
79
+ const {
80
+ authorization_encrypted_response_alg,
81
+ authorization_encrypted_response_enc,
82
+ } = rpConf.metadata.openid_credential_verifier;
83
+
84
+ const encryptedResponse = await new EncryptJwe(authzResponsePayload, {
85
+ alg: (authorization_encrypted_response_alg as Jwe["alg"]) || "RSA-OAEP-256",
86
+ enc:
87
+ (authorization_encrypted_response_enc as Jwe["enc"]) || "A256CBC-HS512",
88
+ kid: encPublicJwk.kid,
89
+ }).encrypt(encPublicJwk);
90
+
91
+ // Build the x-www-form-urlencoded form body
92
+ const formBody = new URLSearchParams({
93
+ response: encryptedResponse,
94
+ ...(requestObject.state ? { state: requestObject.state } : {}),
95
+ });
96
+ return formBody.toString();
97
+ };
98
+
99
+ /**
100
+ * Type definition for the function that sends the authorization response
101
+ * to the Relying Party, completing the presentation flow.
102
+ * Use with `presentation_definition`.
103
+ * @deprecated Use `sendAuthorizationResponse`
104
+ */
105
+ export type SendLegacyAuthorizationResponse = (
106
+ requestObject: Out<VerifyRequestObject>["requestObject"],
107
+ presentationDefinitionId: string,
108
+ remotePresentations: LegacyRemotePresentation[],
109
+ rpConf: RelyingPartyEntityConfiguration["payload"],
110
+ context?: {
111
+ appFetch?: GlobalFetch["fetch"];
112
+ }
113
+ ) => Promise<AuthorizationResponse>;
114
+
115
+ /**
116
+ * Sends the authorization response to the Relying Party (RP) using the specified `response_mode`.
117
+ * This function completes the presentation flow in an OpenID 4 Verifiable Presentations scenario.
118
+ *
119
+ * @param requestObject - The request details, including presentation requirements.
120
+ * @param presentationDefinition - The definition of the expected presentation.
121
+ * @param jwkKeys - Array of JWKs from the Relying Party for optional encryption.
122
+ * @param presentation - Tuple with verifiable credential, claims, and crypto context.
123
+ * @param context - Contains optional custom fetch implementation.
124
+ * @returns Parsed and validated authorization response from the Relying Party.
125
+ */
126
+ export const sendLegacyAuthorizationResponse: SendLegacyAuthorizationResponse =
127
+ async (
128
+ requestObject,
129
+ presentationDefinitionId,
130
+ remotePresentations,
131
+ rpConf,
132
+ { appFetch = fetch } = {}
133
+ ): Promise<AuthorizationResponse> => {
134
+ /**
135
+ * 1. Prepare the VP token and presentation submission
136
+ * If there is only one credential, `vpToken` is a single string.
137
+ * If there are multiple credential, `vpToken` is an array of string.
138
+ **/
139
+ const vp_token =
140
+ remotePresentations?.length === 1
141
+ ? remotePresentations[0]?.vpToken
142
+ : remotePresentations.map(
143
+ (remotePresentation) => remotePresentation.vpToken
144
+ );
145
+
146
+ const descriptor_map = remotePresentations.map(
147
+ (remotePresentation, index) => ({
148
+ id: remotePresentation.inputDescriptor.id,
149
+ path: remotePresentations.length === 1 ? `$` : `$[${index}]`,
150
+ format: remotePresentation.format,
151
+ })
152
+ );
153
+
154
+ const presentation_submission = {
155
+ id: uuid.v4(),
156
+ definition_id: presentationDefinitionId,
157
+ descriptor_map,
158
+ };
159
+
160
+ const requestBody = await buildDirectPostJwtBody(requestObject, rpConf, {
161
+ vp_token,
162
+ presentation_submission,
163
+ });
164
+
165
+ // 3. Send the authorization response via HTTP POST and validate the response
166
+ return await appFetch(requestObject.response_uri, {
167
+ method: "POST",
168
+ headers: {
169
+ "Content-Type": "application/x-www-form-urlencoded",
170
+ },
171
+ body: requestBody,
172
+ })
173
+ .then(hasStatusOrThrow(200))
174
+ .then((res) => res.json())
175
+ .then(AuthorizationResponse.parse);
176
+ };
177
+
178
+ /**
179
+ * Type definition for the function that sends the authorization response
180
+ * to the Relying Party, completing the presentation flow.
181
+ * Use with DCQL queries.
182
+ */
183
+ export type SendAuthorizationResponse = (
184
+ requestObject: Out<VerifyRequestObject>["requestObject"],
185
+ remotePresentations: RemotePresentation[],
186
+ rpConf: RelyingPartyEntityConfiguration["payload"],
187
+ context?: {
188
+ appFetch?: GlobalFetch["fetch"];
189
+ }
190
+ ) => Promise<AuthorizationResponse>;
191
+
192
+ export const sendAuthorizationResponse: SendAuthorizationResponse = async (
193
+ requestObject,
194
+ remotePresentations,
195
+ rpConf,
196
+ { appFetch = fetch } = {}
197
+ ): Promise<AuthorizationResponse> => {
198
+ // 1. Prepare the VP token as a JSON object with keys corresponding to the DCQL query credential IDs
199
+ const requestBody = await buildDirectPostJwtBody(requestObject, rpConf, {
200
+ vp_token: remotePresentations.reduce(
201
+ (acc, presentation) => ({
202
+ ...acc,
203
+ [presentation.credentialId]: presentation.vpToken,
204
+ }),
205
+ {} as Record<string, string>
206
+ ),
207
+ });
208
+
209
+ // 2. Send the authorization response via HTTP POST and validate the response
210
+ return await appFetch(requestObject.response_uri, {
211
+ method: "POST",
212
+ headers: {
213
+ "Content-Type": "application/x-www-form-urlencoded",
214
+ },
215
+ body: requestBody,
216
+ })
217
+ .then(hasStatusOrThrow(200))
218
+ .then((res) => res.json())
219
+ .then(AuthorizationResponse.parse);
220
+ };
@@ -39,3 +39,67 @@ export class NoSuitableKeysFoundInEntityConfiguration extends IoWalletError {
39
39
  super(message);
40
40
  }
41
41
  }
42
+
43
+ /**
44
+ * When a QR code is not valid.
45
+ *
46
+ */
47
+ export class InvalidQRCodeError extends IoWalletError {
48
+ code = "ERR_INVALID_QR_CODE";
49
+
50
+ /**
51
+ * @param detail A description of why the QR code is considered invalid.
52
+ */
53
+ constructor(detail: string) {
54
+ const message = `QR code is not valid: ${detail}.`;
55
+ super(message);
56
+ }
57
+ }
58
+
59
+ /**
60
+ * When the entity is unverified because the Relying Party is not trusted.
61
+ *
62
+ */
63
+ export class UnverifiedEntityError extends IoWalletError {
64
+ code = "ERR_UNVERIFIED_RP_ENTITY";
65
+
66
+ /**
67
+ * @param reason A description of why the entity cannot be verified.
68
+ */
69
+ constructor(reason: string) {
70
+ const message = `Unverified entity: ${reason}.`;
71
+ super(message);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * When some required data is missing to continue because certain attributes are not contained inside the wallet.
77
+ *
78
+ */
79
+ export class MissingDataError extends IoWalletError {
80
+ code = "ERR_MISSING_DATA";
81
+
82
+ /**
83
+ * @param missingAttributes An array or description of the attributes that are missing.
84
+ */
85
+ constructor(missingAttributes: string) {
86
+ const message = `Some required data is missing: ${missingAttributes}.`;
87
+ super(message);
88
+ }
89
+ }
90
+
91
+ /**
92
+ * When a credential is not found in the wallet.
93
+ *
94
+ */
95
+ export class CredentialNotFoundError extends IoWalletError {
96
+ code = "ERR_CREDENTIAL_NOT_FOUND";
97
+
98
+ /**
99
+ * @param credentialId The ID of the credential that was not found.
100
+ */
101
+ constructor(credentialId: string) {
102
+ const message = `Credential not found: ${credentialId}.`;
103
+ super(message);
104
+ }
105
+ }