@digitalbazaar/oid4-client 4.2.0 → 4.4.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.
@@ -0,0 +1,312 @@
1
+ /*!
2
+ * Copyright (c) 2023-2025 Digital Bazaar, Inc. All rights reserved.
3
+ */
4
+ import {createNamedError, selectJwk} from './util.js';
5
+ import {EncryptJWT} from 'jose';
6
+ import {httpClient} from '@digitalbazaar/http-client';
7
+ import jsonpointer from 'jsonpointer';
8
+ import {pathsToVerifiableCredentialPointers} from './convert.js';
9
+
10
+ const TEXT_ENCODER = new TextEncoder();
11
+
12
+ export async function send({
13
+ verifiablePresentation,
14
+ presentationSubmission,
15
+ authorizationRequest,
16
+ vpToken,
17
+ encryptionOptions = {},
18
+ agent
19
+ } = {}) {
20
+ try {
21
+ if(!(verifiablePresentation || vpToken)) {
22
+ throw createNamedError({
23
+ message: 'One of "verifiablePresentation" or "vpToken" must be given.',
24
+ name: 'DataError'
25
+ });
26
+ }
27
+ // if no `vpToken` given, use VP
28
+ vpToken = vpToken ?? JSON.stringify(verifiablePresentation);
29
+
30
+ // if no `presentationSubmission` provided, auto-generate one
31
+ let generatedPresentationSubmission = false;
32
+ if(!presentationSubmission) {
33
+ ({presentationSubmission} = createPresentationSubmission({
34
+ presentationDefinition: authorizationRequest.presentation_definition,
35
+ verifiablePresentation
36
+ }));
37
+ generatedPresentationSubmission = true;
38
+ }
39
+
40
+ // prepare response body
41
+ const body = new URLSearchParams();
42
+
43
+ // if `authorizationRequest.response_mode` is `direct.jwt` generate a JWT
44
+ if(authorizationRequest.response_mode === 'direct_post.jwt') {
45
+ const jwt = await _encrypt({
46
+ vpToken, presentationSubmission, authorizationRequest,
47
+ encryptionOptions
48
+ });
49
+ body.set('response', jwt);
50
+ } else {
51
+ // include vp token and presentation submittion directly in body
52
+ body.set('vp_token', vpToken);
53
+ body.set(
54
+ 'presentation_submission', JSON.stringify(presentationSubmission));
55
+ }
56
+
57
+ // send response
58
+ const response = await httpClient.post(authorizationRequest.response_uri, {
59
+ agent, body, headers: {accept: 'application/json'},
60
+ // FIXME: limit response size
61
+ // timeout in ms for response
62
+ timeout: 5000
63
+ });
64
+
65
+ // return response data as `result`
66
+ const result = response.data || {};
67
+ if(generatedPresentationSubmission) {
68
+ // return any generated presentation submission
69
+ return {result, presentationSubmission};
70
+ }
71
+ return {result};
72
+ } catch(cause) {
73
+ const message = cause.data?.error_description ?? cause.message;
74
+ const error = new Error(
75
+ `Could not send OID4VP authorization response: ${message}.`,
76
+ {cause});
77
+ error.name = 'OperationError';
78
+ throw error;
79
+ }
80
+ }
81
+
82
+ // creates a "presentation submission" from a presentation definition and VP
83
+ export function createPresentationSubmission({
84
+ presentationDefinition, verifiablePresentation
85
+ } = {}) {
86
+ const descriptor_map = [];
87
+ const presentationSubmission = {
88
+ id: crypto.randomUUID(),
89
+ definition_id: presentationDefinition.id,
90
+ descriptor_map
91
+ };
92
+
93
+ try {
94
+ // walk through each input descriptor object and match it to a VC
95
+ let {verifiableCredential: vcs} = verifiablePresentation;
96
+ const single = !Array.isArray(vcs);
97
+ if(single) {
98
+ vcs = [vcs];
99
+ }
100
+ /* Note: It is conceivable that the same VC could match multiple input
101
+ descriptors. In this simplistic implementation, the first VC that matches
102
+ is used. This may result in VCs in the VP not being mapped to an input
103
+ descriptor, but every input descriptor having a VC that matches (i.e., at
104
+ least one VC will be shared across multiple input descriptors). If
105
+ some other behavior is more desirable, this can be changed in a future
106
+ version. */
107
+ for(const inputDescriptor of presentationDefinition.input_descriptors) {
108
+ // walk through each VC and try to match it to the input descriptor
109
+ for(let i = 0; i < vcs.length; ++i) {
110
+ const verifiableCredential = vcs[i];
111
+ if(_matchesInputDescriptor({inputDescriptor, verifiableCredential})) {
112
+ descriptor_map.push({
113
+ id: inputDescriptor.id,
114
+ path: '$',
115
+ format: 'ldp_vp',
116
+ path_nested: {
117
+ format: 'ldp_vc',
118
+ path: single ?
119
+ '$.verifiableCredential' :
120
+ '$.verifiableCredential[' + i + ']'
121
+ }
122
+ });
123
+ break;
124
+ }
125
+ }
126
+ }
127
+ } catch(cause) {
128
+ throw createNamedError({
129
+ message: `Could not create presentation submission: ${cause.message}`,
130
+ name: 'OperationError',
131
+ cause
132
+ });
133
+ }
134
+
135
+ return {presentationSubmission};
136
+ }
137
+
138
+ async function _encrypt({
139
+ vpToken, presentationSubmission, authorizationRequest, encryptionOptions
140
+ }) {
141
+ // get recipient public JWK from client_metadata JWK key set
142
+ const jwks = authorizationRequest?.client_metadata?.jwks;
143
+ const recipientPublicJwk = selectJwk({
144
+ keys: jwks?.keys, alg: 'ECDH-ES', kty: 'EC', crv: 'P-256', use: 'enc'
145
+ });
146
+ if(!recipientPublicJwk) {
147
+ throw createNamedError({
148
+ message: 'No matching key found for "ECDH-ES" in client meta data ' +
149
+ 'JWK key set.',
150
+ name: 'NotFoundError'
151
+ });
152
+ }
153
+
154
+ // configure `keyManagementParameters` for `EncryptJWT` API
155
+ const keyManagementParameters = {};
156
+ if(encryptionOptions?.mdoc?.sessionTranscript) {
157
+ // ISO 18013-7: include specific session transcript params as apu + apv
158
+ const {
159
+ mdocGeneratedNonce,
160
+ // default to using `authorizationRequest.nonce` for verifier nonce
161
+ verifierGeneratedNonce = authorizationRequest.nonce
162
+ } = encryptionOptions.mdoc.sessionTranscript;
163
+ // note: `EncryptJWT` API requires `apu/apv` (`partyInfoU`/`partyInfoV`)
164
+ // to be passed as Uint8Arrays; they will be encoded using `base64url` by
165
+ // that API
166
+ keyManagementParameters.apu = TEXT_ENCODER.encode(mdocGeneratedNonce);
167
+ keyManagementParameters.apv = TEXT_ENCODER.encode(verifierGeneratedNonce);
168
+ }
169
+
170
+ const claimSet = {
171
+ vp_token: vpToken,
172
+ presentation_submission: presentationSubmission
173
+ };
174
+ const jwt = await new EncryptJWT(claimSet)
175
+ .setProtectedHeader({
176
+ alg: 'ECDH-ES', enc: 'A256GCM',
177
+ kid: recipientPublicJwk.kid
178
+ })
179
+ .setKeyManagementParameters(keyManagementParameters)
180
+ .encrypt(recipientPublicJwk);
181
+ return jwt;
182
+ }
183
+
184
+ function _filterToValue({filter, strict = false}) {
185
+ /* Each `filter` has a JSON Schema object. In recognition of the fact that
186
+ a query must be usable by common database engines (including perhaps
187
+ encrypted cloud databases) and of the fact that each JSON Schema object will
188
+ come from an untrusted source (and could have malicious regexes, etc.), only
189
+ simple JSON Schema types are supported:
190
+
191
+ `string`: with `const` or `enum`, `format` is not supported and `pattern` has
192
+ partial support as it will be treated as a simple string not a regex; regex
193
+ is a DoS attack vector
194
+
195
+ `array`: with `contains` where uses a `string` filter
196
+
197
+ `allOf`: supported only with the above schemas present in it.
198
+
199
+ */
200
+ let value;
201
+
202
+ const {type} = filter;
203
+ if(type === 'array') {
204
+ if(filter.contains) {
205
+ if(Array.isArray(filter.contains)) {
206
+ return filter.contains.map(filter => _filterToValue({filter, strict}));
207
+ }
208
+ return _filterToValue({filter: filter.contains, strict});
209
+ }
210
+ if(Array.isArray(filter.allOf) && filter.allOf.every(f => f.contains)) {
211
+ return filter.allOf.map(
212
+ f => _filterToValue({filter: f.contains, strict}));
213
+ }
214
+ if(strict) {
215
+ throw new Error(
216
+ 'Unsupported filter; array filters must use "allOf" and/or ' +
217
+ '"contains" with a string filter.');
218
+ }
219
+ return value;
220
+ }
221
+ if(type === 'string' || type === undefined) {
222
+ if(filter.const !== undefined) {
223
+ value = filter.const;
224
+ } else if(filter.pattern) {
225
+ value = filter.pattern;
226
+ } else if(filter.enum) {
227
+ value = filter.enum.slice();
228
+ } else if(strict) {
229
+ throw new Error(
230
+ 'Unsupported filter; string filters must use "const" or "pattern".');
231
+ }
232
+ return value;
233
+ }
234
+ if(strict) {
235
+ throw new Error(`Unsupported filter type "${type}".`);
236
+ }
237
+ }
238
+
239
+ function _matchesInputDescriptor({
240
+ inputDescriptor, verifiableCredential, strict = false
241
+ }) {
242
+ // walk through each field ensuring there is a matching value
243
+ const fields = inputDescriptor?.constraints?.fields || [];
244
+ for(const field of fields) {
245
+ const {path, filter, optional} = field;
246
+ if(optional) {
247
+ // skip field, it is optional
248
+ continue;
249
+ }
250
+
251
+ try {
252
+ // each field must have a `path` (which can be a string or an array)
253
+ if(!(Array.isArray(path) || typeof path === 'string')) {
254
+ throw new Error(
255
+ 'Input descriptor field "path" must be a string or array.');
256
+ }
257
+
258
+ // process any filter
259
+ let value = '';
260
+ if(filter !== undefined) {
261
+ value = _filterToValue({filter, strict});
262
+ }
263
+ // no value to match, presume no match
264
+ if(value === undefined) {
265
+ return false;
266
+ }
267
+ // normalize value to array
268
+ if(!Array.isArray(value)) {
269
+ value = [value];
270
+ }
271
+
272
+ // get JSON pointers for every path inside a verifiable credential
273
+ const pointers = pathsToVerifiableCredentialPointers({paths: path});
274
+
275
+ // check for a value at at least one path
276
+ for(const pointer of pointers) {
277
+ const existing = jsonpointer.get(verifiableCredential, pointer);
278
+ if(existing === undefined) {
279
+ // VC does not match
280
+ return false;
281
+ }
282
+ // look for at least one matching value in `existing`
283
+ let match = false;
284
+ for(const v of value) {
285
+ if(Array.isArray(existing)) {
286
+ if(existing.includes(v)) {
287
+ match = true;
288
+ break;
289
+ }
290
+ } else if(existing === v) {
291
+ match = true;
292
+ break;
293
+ }
294
+ }
295
+ if(!match) {
296
+ return false;
297
+ }
298
+ }
299
+ } catch(cause) {
300
+ const id = field.id || (JSON.stringify(field).slice(0, 50) + ' ...');
301
+ const error = createNamedError({
302
+ message: `Could not process input descriptor field: "${id}".`,
303
+ name: 'DataError',
304
+ cause
305
+ });
306
+ error.field = field;
307
+ throw error;
308
+ }
309
+ }
310
+
311
+ return true;
312
+ }