@pagopa/io-react-native-wallet 0.28.0 → 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 (132) hide show
  1. package/lib/commonjs/credential/issuance/03-start-user-authorization.js +3 -0
  2. package/lib/commonjs/credential/issuance/03-start-user-authorization.js.map +1 -1
  3. package/lib/commonjs/credential/presentation/01-start-flow.js +14 -24
  4. package/lib/commonjs/credential/presentation/01-start-flow.js.map +1 -1
  5. package/lib/commonjs/credential/presentation/03-get-request-object.js +30 -42
  6. package/lib/commonjs/credential/presentation/03-get-request-object.js.map +1 -1
  7. package/lib/commonjs/credential/presentation/04-retrieve-rp-jwks.js +32 -0
  8. package/lib/commonjs/credential/presentation/04-retrieve-rp-jwks.js.map +1 -0
  9. package/lib/commonjs/credential/presentation/05-verify-request-object.js +53 -0
  10. package/lib/commonjs/credential/presentation/05-verify-request-object.js.map +1 -0
  11. package/lib/commonjs/credential/presentation/06-fetch-presentation-definition.js +39 -0
  12. package/lib/commonjs/credential/presentation/06-fetch-presentation-definition.js.map +1 -0
  13. package/lib/commonjs/credential/presentation/07-evaluate-dcql-query.js +125 -0
  14. package/lib/commonjs/credential/presentation/07-evaluate-dcql-query.js.map +1 -0
  15. package/lib/commonjs/credential/presentation/07-evaluate-input-descriptor.js +289 -0
  16. package/lib/commonjs/credential/presentation/07-evaluate-input-descriptor.js.map +1 -0
  17. package/lib/commonjs/credential/presentation/08-send-authorization-response.js +170 -0
  18. package/lib/commonjs/credential/presentation/08-send-authorization-response.js.map +1 -0
  19. package/lib/commonjs/credential/presentation/errors.js +69 -1
  20. package/lib/commonjs/credential/presentation/errors.js.map +1 -1
  21. package/lib/commonjs/credential/presentation/index.js +29 -1
  22. package/lib/commonjs/credential/presentation/index.js.map +1 -1
  23. package/lib/commonjs/credential/presentation/types.js +124 -3
  24. package/lib/commonjs/credential/presentation/types.js.map +1 -1
  25. package/lib/commonjs/sd-jwt/index.js +41 -1
  26. package/lib/commonjs/sd-jwt/index.js.map +1 -1
  27. package/lib/commonjs/trust/chain.js.map +1 -1
  28. package/lib/commonjs/trust/types.js +26 -6
  29. package/lib/commonjs/trust/types.js.map +1 -1
  30. package/lib/commonjs/trust/utils.js +5 -0
  31. package/lib/commonjs/trust/utils.js.map +1 -1
  32. package/lib/commonjs/utils/jwk.js +5 -1
  33. package/lib/commonjs/utils/jwk.js.map +1 -1
  34. package/lib/module/credential/issuance/03-start-user-authorization.js +3 -0
  35. package/lib/module/credential/issuance/03-start-user-authorization.js.map +1 -1
  36. package/lib/module/credential/presentation/01-start-flow.js +14 -24
  37. package/lib/module/credential/presentation/01-start-flow.js.map +1 -1
  38. package/lib/module/credential/presentation/03-get-request-object.js +31 -43
  39. package/lib/module/credential/presentation/03-get-request-object.js.map +1 -1
  40. package/lib/module/credential/presentation/04-retrieve-rp-jwks.js +25 -0
  41. package/lib/module/credential/presentation/04-retrieve-rp-jwks.js.map +1 -0
  42. package/lib/module/credential/presentation/05-verify-request-object.js +46 -0
  43. package/lib/module/credential/presentation/05-verify-request-object.js.map +1 -0
  44. package/lib/module/credential/presentation/06-fetch-presentation-definition.js +32 -0
  45. package/lib/module/credential/presentation/06-fetch-presentation-definition.js.map +1 -0
  46. package/lib/module/credential/presentation/07-evaluate-dcql-query.js +117 -0
  47. package/lib/module/credential/presentation/07-evaluate-dcql-query.js.map +1 -0
  48. package/lib/module/credential/presentation/07-evaluate-input-descriptor.js +278 -0
  49. package/lib/module/credential/presentation/07-evaluate-input-descriptor.js.map +1 -0
  50. package/lib/module/credential/presentation/08-send-authorization-response.js +158 -0
  51. package/lib/module/credential/presentation/08-send-authorization-response.js.map +1 -0
  52. package/lib/module/credential/presentation/errors.js +64 -0
  53. package/lib/module/credential/presentation/errors.js.map +1 -1
  54. package/lib/module/credential/presentation/index.js +6 -2
  55. package/lib/module/credential/presentation/index.js.map +1 -1
  56. package/lib/module/credential/presentation/types.js +121 -2
  57. package/lib/module/credential/presentation/types.js.map +1 -1
  58. package/lib/module/sd-jwt/index.js +40 -1
  59. package/lib/module/sd-jwt/index.js.map +1 -1
  60. package/lib/module/trust/chain.js.map +1 -1
  61. package/lib/module/trust/types.js +26 -6
  62. package/lib/module/trust/types.js.map +1 -1
  63. package/lib/module/trust/utils.js +5 -0
  64. package/lib/module/trust/utils.js.map +1 -1
  65. package/lib/module/utils/jwk.js +3 -0
  66. package/lib/module/utils/jwk.js.map +1 -1
  67. package/lib/typescript/credential/issuance/03-start-user-authorization.d.ts.map +1 -1
  68. package/lib/typescript/credential/presentation/01-start-flow.d.ts +26 -5
  69. package/lib/typescript/credential/presentation/01-start-flow.d.ts.map +1 -1
  70. package/lib/typescript/credential/presentation/03-get-request-object.d.ts +7 -10
  71. package/lib/typescript/credential/presentation/03-get-request-object.d.ts.map +1 -1
  72. package/lib/typescript/credential/presentation/04-retrieve-rp-jwks.d.ts +23 -0
  73. package/lib/typescript/credential/presentation/04-retrieve-rp-jwks.d.ts.map +1 -0
  74. package/lib/typescript/credential/presentation/05-verify-request-object.d.ts +18 -0
  75. package/lib/typescript/credential/presentation/05-verify-request-object.d.ts.map +1 -0
  76. package/lib/typescript/credential/presentation/06-fetch-presentation-definition.d.ts +21 -0
  77. package/lib/typescript/credential/presentation/06-fetch-presentation-definition.d.ts.map +1 -0
  78. package/lib/typescript/credential/presentation/07-evaluate-dcql-query.d.ts +20 -0
  79. package/lib/typescript/credential/presentation/07-evaluate-dcql-query.d.ts.map +1 -0
  80. package/lib/typescript/credential/presentation/07-evaluate-input-descriptor.d.ts +88 -0
  81. package/lib/typescript/credential/presentation/07-evaluate-input-descriptor.d.ts.map +1 -0
  82. package/lib/typescript/credential/presentation/08-send-authorization-response.d.ts +70 -0
  83. package/lib/typescript/credential/presentation/08-send-authorization-response.d.ts.map +1 -0
  84. package/lib/typescript/credential/presentation/errors.d.ts +44 -0
  85. package/lib/typescript/credential/presentation/errors.d.ts.map +1 -1
  86. package/lib/typescript/credential/presentation/index.d.ts +7 -3
  87. package/lib/typescript/credential/presentation/index.d.ts.map +1 -1
  88. package/lib/typescript/credential/presentation/types.d.ts +747 -10
  89. package/lib/typescript/credential/presentation/types.d.ts.map +1 -1
  90. package/lib/typescript/sd-jwt/index.d.ts +19 -0
  91. package/lib/typescript/sd-jwt/index.d.ts.map +1 -1
  92. package/lib/typescript/trust/index.d.ts +236 -8
  93. package/lib/typescript/trust/index.d.ts.map +1 -1
  94. package/lib/typescript/trust/types.d.ts +3046 -76
  95. package/lib/typescript/trust/types.d.ts.map +1 -1
  96. package/lib/typescript/trust/utils.d.ts +6 -6
  97. package/lib/typescript/trust/utils.d.ts.map +1 -1
  98. package/lib/typescript/utils/decoder.d.ts +1 -1
  99. package/lib/typescript/utils/decoder.d.ts.map +1 -1
  100. package/lib/typescript/utils/errors.d.ts.map +1 -1
  101. package/lib/typescript/utils/jwk.d.ts +137 -0
  102. package/lib/typescript/utils/jwk.d.ts.map +1 -1
  103. package/lib/typescript/utils/misc.d.ts.map +1 -1
  104. package/lib/typescript/wallet-instance-attestation/types.d.ts +16 -16
  105. package/package.json +15 -11
  106. package/src/credential/issuance/03-start-user-authorization.ts +3 -0
  107. package/src/credential/presentation/01-start-flow.ts +19 -26
  108. package/src/credential/presentation/03-get-request-object.ts +35 -58
  109. package/src/credential/presentation/04-retrieve-rp-jwks.ts +34 -0
  110. package/src/credential/presentation/05-verify-request-object.ts +52 -0
  111. package/src/credential/presentation/06-fetch-presentation-definition.ts +48 -0
  112. package/src/credential/presentation/07-evaluate-dcql-query.ts +166 -0
  113. package/src/credential/presentation/07-evaluate-input-descriptor.ts +391 -0
  114. package/src/credential/presentation/08-send-authorization-response.ts +220 -0
  115. package/src/credential/presentation/errors.ts +64 -0
  116. package/src/credential/presentation/index.ts +22 -1
  117. package/src/credential/presentation/types.ts +134 -3
  118. package/src/sd-jwt/index.ts +49 -1
  119. package/src/trust/chain.ts +2 -2
  120. package/src/trust/types.ts +25 -5
  121. package/src/trust/utils.ts +6 -3
  122. package/src/utils/decoder.ts +1 -1
  123. package/src/utils/errors.ts +2 -2
  124. package/src/utils/jwk.ts +8 -1
  125. package/src/utils/misc.ts +2 -2
  126. package/lib/commonjs/credential/presentation/04-send-authorization-response.js +0 -138
  127. package/lib/commonjs/credential/presentation/04-send-authorization-response.js.map +0 -1
  128. package/lib/module/credential/presentation/04-send-authorization-response.js +0 -128
  129. package/lib/module/credential/presentation/04-send-authorization-response.js.map +0 -1
  130. package/lib/typescript/credential/presentation/04-send-authorization-response.d.ts +0 -34
  131. package/lib/typescript/credential/presentation/04-send-authorization-response.d.ts.map +0 -1
  132. package/src/credential/presentation/04-send-authorization-response.ts +0 -168
@@ -0,0 +1,34 @@
1
+ import { JWK } from "../../utils/jwk";
2
+ import { RelyingPartyEntityConfiguration } from "../../trust/types";
3
+
4
+ /**
5
+ * Defines the signature for a function that retrieves JSON Web Key Sets (JWKS) from a client.
6
+ *
7
+ * @template T - The tuple type representing the function arguments.
8
+ * @param args - The arguments passed to the function.
9
+ * @returns A promise resolving to an object containing an array of JWKs.
10
+ */
11
+ export type FetchJwks<T extends Array<unknown> = []> = (...args: T) => {
12
+ keys: JWK[];
13
+ };
14
+
15
+ /**
16
+ * Retrieves the JSON Web Key Set (JWKS) from a Relying Party's entity configuration.
17
+ *
18
+ * @param rpConfig - The configuration object of the Relying Party entity.
19
+ * @returns An object containing an array of JWKs.
20
+ * @throws Will throw an error if the configuration is invalid or if JWKS is not found.
21
+ */
22
+ export const getJwksFromConfig: FetchJwks<
23
+ [RelyingPartyEntityConfiguration["payload"]["metadata"]]
24
+ > = (rpConfig) => {
25
+ const jwks = rpConfig.openid_credential_verifier.jwks;
26
+
27
+ if (!jwks || !Array.isArray(jwks.keys)) {
28
+ throw new Error("JWKS not found in Relying Party configuration.");
29
+ }
30
+
31
+ return {
32
+ keys: jwks.keys,
33
+ };
34
+ };
@@ -0,0 +1,52 @@
1
+ import { decode as decodeJwt, verify } from "@pagopa/io-react-native-jwt";
2
+ import type { RelyingPartyEntityConfiguration } from "../../trust";
3
+ import { UnverifiedEntityError } from "./errors";
4
+ import { RequestObject } from "./types";
5
+ import { getJwksFromConfig } from "./04-retrieve-rp-jwks";
6
+
7
+ export type VerifyRequestObject = (
8
+ requestObjectEncodedJwt: string,
9
+ context: {
10
+ clientId: string;
11
+ // jwkKeys: Out<FetchJwks>["keys"];
12
+ rpConf: RelyingPartyEntityConfiguration["payload"];
13
+ }
14
+ ) => Promise<{ requestObject: RequestObject }>;
15
+
16
+ /**
17
+ * Function to verify the Request Object's signature and the client ID.
18
+ * @param requestObjectEncodedJwt The Request Object in JWT format
19
+ * @param context.clientId The client ID to verify
20
+ * @param context.jwkKeys The set of keys to verify the signature
21
+ * @param context.rpConf The Entity Configuration of the Relying Party
22
+ * @returns The verified Request Object
23
+ */
24
+ export const verifyRequestObject: VerifyRequestObject = async (
25
+ requestObjectEncodedJwt,
26
+ { clientId, rpConf }
27
+ ) => {
28
+ const requestObjectJwt = decodeJwt(requestObjectEncodedJwt);
29
+ const { keys } = getJwksFromConfig(rpConf.metadata);
30
+
31
+ // Verify token signature to ensure the request object is authentic
32
+ const pubKey = keys?.find(
33
+ ({ kid }) => kid === requestObjectJwt.protectedHeader.kid
34
+ );
35
+
36
+ if (!pubKey) {
37
+ throw new UnverifiedEntityError("Request Object signature verification!");
38
+ }
39
+
40
+ // Standard claims are verified within `verify`
41
+ await verify(requestObjectEncodedJwt, pubKey, { issuer: clientId });
42
+
43
+ const requestObject = RequestObject.parse(requestObjectJwt.payload);
44
+
45
+ if (!(clientId === requestObject.client_id && clientId === rpConf.sub)) {
46
+ throw new UnverifiedEntityError(
47
+ "Client ID does not match Request Object or Entity Configuration"
48
+ );
49
+ }
50
+
51
+ return { requestObject };
52
+ };
@@ -0,0 +1,48 @@
1
+ import { PresentationDefinition, RequestObject } from "./types";
2
+ import { RelyingPartyEntityConfiguration } from "../../trust/types";
3
+
4
+ export type FetchPresentationDefinition = (
5
+ requestObject: RequestObject,
6
+ rpConf?: RelyingPartyEntityConfiguration["payload"]["metadata"]
7
+ ) => Promise<{
8
+ presentationDefinition: PresentationDefinition;
9
+ }>;
10
+
11
+ /**
12
+ * Retrieves a PresentationDefinition based on the given parameters.
13
+ *
14
+ * The method attempts the following strategies in order:
15
+ * 1. Checks if `presentation_definition` is directly available in the request object.
16
+ * 2. Uses a pre-configured `presentation_definition` from the relying party configuration if the `scope` is present in the request object.
17
+ *
18
+ * If none of the above conditions are met, the function throws an error indicating the definition could not be found. Note that `presentation_definition_uri` is not supported in 0.9.x.
19
+ *
20
+ * @param {RequestObject} requestObject - The request object containing the presentation definition or references to it.
21
+ * @param {RelyingPartyEntityConfiguration["payload"]["metadata"]} [rpConf] - Optional relying party configuration.
22
+ * @returns {Promise<{ presentationDefinition: PresentationDefinition }>} - Resolves with the presentation definition.
23
+ * @throws {Error} - Throws if the presentation definition cannot be found or fetched.
24
+ */
25
+ export const fetchPresentDefinition: FetchPresentationDefinition = async (
26
+ requestObject,
27
+ rpConf
28
+ ) => {
29
+ // Check if `presentation_definition` is directly available in the request object
30
+ if (requestObject.presentation_definition) {
31
+ return {
32
+ presentationDefinition: requestObject.presentation_definition,
33
+ };
34
+ }
35
+
36
+ // Check if `scope` is present in the request object and a pre-configured presentation definition exists
37
+ if (
38
+ requestObject.scope &&
39
+ rpConf?.openid_credential_verifier?.presentation_definition
40
+ ) {
41
+ return {
42
+ presentationDefinition:
43
+ rpConf.openid_credential_verifier.presentation_definition,
44
+ };
45
+ }
46
+
47
+ throw new Error("Presentation definition not found");
48
+ };
@@ -0,0 +1,166 @@
1
+ import {
2
+ DcqlQuery,
3
+ DcqlError,
4
+ DcqlCredentialSetError,
5
+ DcqlQueryResult,
6
+ } from "dcql";
7
+ import { isValiError } from "valibot";
8
+ import { decode, prepareVpToken } from "../../sd-jwt";
9
+ import type { Disclosure, DisclosureWithEncoded } from "../../sd-jwt/types";
10
+ import { ValidationFailed } from "../../utils/errors";
11
+ import { createCryptoContextFor } from "../../utils/crypto";
12
+ import type { RemotePresentation } from "./types";
13
+
14
+ type EvaluateDcqlQuery = (
15
+ credentialsSdJwt: [string /* keyTag */, string /* credential */][],
16
+ query: DcqlQuery.Input
17
+ ) => {
18
+ id: string;
19
+ credential: string;
20
+ keyTag: string;
21
+ requiredDisclosures: DisclosureWithEncoded[];
22
+ isOptional?: boolean;
23
+ }[];
24
+
25
+ type PrepareRemotePresentations = (
26
+ credentials: {
27
+ id: string;
28
+ credential: string;
29
+ keyTag: string;
30
+ requestedClaims: string[];
31
+ }[],
32
+ nonce: string,
33
+ clientId: string
34
+ ) => Promise<RemotePresentation[]>;
35
+
36
+ type DcqlMatchSuccess = Extract<
37
+ DcqlQueryResult.CredentialMatch,
38
+ { success: true }
39
+ >;
40
+
41
+ /**
42
+ * Convert a credential in JWT format to an object with claims
43
+ * for correct parsing by the `dcql` library.
44
+ */
45
+ const mapCredentialToObject = (jwt: string) => {
46
+ const { sdJwt, disclosures } = decode(jwt);
47
+ const credentialFormat = sdJwt.header.typ;
48
+
49
+ // TODO [SIW-2082]: support MDOC credentials
50
+ if (credentialFormat !== "vc+sd-jwt") {
51
+ throw new Error(`Unsupported credential format: ${credentialFormat}`);
52
+ }
53
+
54
+ return {
55
+ vct: sdJwt.payload.vct,
56
+ credential_format: credentialFormat,
57
+ claims: disclosures.reduce(
58
+ (acc, disclosure) => ({
59
+ ...acc,
60
+ [disclosure.decoded[1]]: disclosure.decoded,
61
+ }),
62
+ {} as Record<string, Disclosure>
63
+ ),
64
+ };
65
+ };
66
+
67
+ /**
68
+ * Extract only successful matches from the DCQL query result.
69
+ */
70
+ const getDcqlQueryMatches = (result: DcqlQueryResult) =>
71
+ Object.entries(result.credential_matches).filter(
72
+ ([, match]) => match.success === true
73
+ ) as [string, DcqlMatchSuccess][];
74
+
75
+ export const evaluateDcqlQuery: EvaluateDcqlQuery = (
76
+ credentialsSdJwt,
77
+ query
78
+ ) => {
79
+ const credentials = credentialsSdJwt.map(([, credential]) =>
80
+ mapCredentialToObject(credential)
81
+ );
82
+
83
+ try {
84
+ // Validate the query
85
+ const parsedQuery = DcqlQuery.parse(query);
86
+ DcqlQuery.validate(parsedQuery);
87
+
88
+ const queryResult = DcqlQuery.query(parsedQuery, credentials);
89
+
90
+ if (!queryResult.canBeSatisfied) {
91
+ throw new Error("No credential can satisfy the provided DCQL query");
92
+ }
93
+
94
+ // Build an object vct:credentialJwt to map matched credentials to their JWT
95
+ const credentialsSdJwtByVct = credentials.reduce(
96
+ (acc, c, i) => ({ ...acc, [c.vct]: credentialsSdJwt[i]! }),
97
+ {} as Record<string, [string /* keyTag */, string /* credential */]>
98
+ );
99
+
100
+ return getDcqlQueryMatches(queryResult).map(([id, match]) => {
101
+ if (match.output.credential_format !== "vc+sd-jwt") {
102
+ throw new Error("Unsupported format"); // TODO [SIW-2082]: support MDOC credentials
103
+ }
104
+ const { vct, claims } = match.output;
105
+
106
+ // Find a matching credential set to see whether the credential is optional
107
+ // If no credential set is found, then the credential is required by default
108
+ // NOTE: This is an extra, it might not be necessary
109
+ const credentialSet = queryResult.credential_sets?.find((set) =>
110
+ set.matching_options?.flat().includes(vct)
111
+ );
112
+ const isOptional = credentialSet ? !credentialSet.required : false;
113
+
114
+ const [keyTag, credential] = credentialsSdJwtByVct[vct]!;
115
+ const requiredDisclosures = Object.values(
116
+ claims
117
+ ) as DisclosureWithEncoded[];
118
+ return {
119
+ id,
120
+ keyTag,
121
+ credential,
122
+ isOptional,
123
+ requiredDisclosures,
124
+ };
125
+ });
126
+ } catch (error) {
127
+ // Invalid DCQL query structure
128
+ if (isValiError(error)) {
129
+ throw new ValidationFailed({
130
+ message: "Invalid DCQL query",
131
+ reason: error.issues.map((issue) => issue.message).join(", "),
132
+ });
133
+ }
134
+
135
+ if (error instanceof DcqlError) {
136
+ // TODO [SIW-2110]: handle invalid DQCL query or let the error propagate
137
+ }
138
+ if (error instanceof DcqlCredentialSetError) {
139
+ // TODO [SIW-2110]: handle missing credentials or let the error propagate
140
+ }
141
+ throw error;
142
+ }
143
+ };
144
+
145
+ export const prepareRemotePresentations: PrepareRemotePresentations = async (
146
+ credentials,
147
+ nonce,
148
+ clientId
149
+ ) => {
150
+ return Promise.all(
151
+ credentials.map(async (item) => {
152
+ const { vp_token } = await prepareVpToken(nonce, clientId, [
153
+ item.credential,
154
+ item.requestedClaims,
155
+ createCryptoContextFor(item.keyTag),
156
+ ]);
157
+
158
+ return {
159
+ credentialId: item.id,
160
+ requestedClaims: item.requestedClaims,
161
+ vpToken: vp_token,
162
+ format: "vc+sd-jwt",
163
+ };
164
+ })
165
+ );
166
+ };
@@ -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
+ };