-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverify.js
More file actions
233 lines (215 loc) · 6.76 KB
/
verify.js
File metadata and controls
233 lines (215 loc) · 6.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*!
* Copyright (c) 2024-2025 Digital Bazaar, Inc. All rights reserved.
*/
import * as bedrock from '@bedrock/core';
import {typeTableLoader as _typeTableLoader} from './typeTableLoader.js';
import assert from 'assert-plus';
import {BARCODE_FORMATS} from './constants.js';
import {httpClient} from '@digitalbazaar/http-client';
import {httpsAgent} from '@bedrock/https-agent';
import {util} from '@digitalbazaar/vpqr';
import {VC_CONTEXT_V2} from './constants.js';
import {zcapClient} from './zcapClient.js';
const {util: {BedrockError}} = bedrock;
export async function barcodeToCredential({
text, barcode, documentLoader, typeTableLoader = _typeTableLoader,
} = {}) {
if(barcode && barcode.format !== BARCODE_FORMATS.QR_CODE) {
throw new BedrockError(`Unsupported barcode format "${barcode.format}".`, {
name: 'NotSupportedError',
details: {httpStatusCode: 400, public: true}
});
}
text = barcode?.data ?? text;
const {jsonldDocument: credential} = await util.fromQrCode({
text,
documentLoader,
typeTableLoader,
expectedHeader: 'VC1-'
});
return {credential};
}
export async function barcodeToEnvelopedCredential({text, barcode} = {}) {
const credential = {
'@context': [VC_CONTEXT_V2],
id: null,
type: 'EnvelopedVerifiableCredential'
};
if(text !== undefined) {
barcode = {data: text, format: BARCODE_FORMATS.QR_CODE};
}
const mediaType = `data:application/vcb;barcode-format=${barcode.format}`;
if(barcode.format === BARCODE_FORMATS.PDF417 ||
barcode.format === BARCODE_FORMATS.QR_CODE) {
credential.id = `${mediaType};base64,` +
Buffer.from(barcode.data, 'utf8').toString('base64');
} else {
throw new BedrockError(
'Could not create enveloped verifiable credential; ' +
`unsupported barcode format "${barcode.format}".`, {
name: 'NotSupportedError',
details: {httpStatusCode: 400, public: true}
});
}
return {credential};
}
export function isExpired({credential, now = new Date(), maxClockSkew}) {
if(credential.validUntil === undefined) {
return false;
}
const validUntil = new Date(credential.validUntil);
return _compareTime({t1: now, t2: validUntil, maxClockSkew}) >= 0;
}
export async function verify({
credential, capability, variables = {}, options
} = {}) {
// set default options
options = {
checkExpiration: !options?.returnExchange,
maxClockSkew: 300,
returnExchange: false,
getCredentialFromExchange: _getCredentialFromExchange,
...options
};
const {
checkExpiration, maxClockSkew, returnExchange, getCredentialFromExchange
} = options;
assert.bool(checkExpiration, 'options.checkExpiration');
assert.number(maxClockSkew, 'options.maxClockSkew');
assert.bool(returnExchange, 'options.returnExchange');
assert.func(getCredentialFromExchange, 'options.getCredentialFromExchange');
if(options.checkExpiration && options.returnExchange) {
throw new Error(
'Only one of "checkExpiration" or "returnExchange" can be "true".');
}
// create exchange
let exchangeId;
try {
const response = await zcapClient.write({
json: {
// quick 5 minute TTL
ttl: 5 * 60,
variables
},
capability
});
exchangeId = response.headers.get('location');
} catch(cause) {
throw new BedrockError(
'Could not create verification exchange.', {
name: 'OperationError',
details: {httpStatusCode: 500, public: true},
cause
});
}
// use exchange
let response;
let error;
try {
const verifiablePresentation = {
'@context': ['https://www.w3.org/ns/credentials/v2'],
type: ['VerifiablePresentation'],
verifiableCredential: [credential]
};
response = await httpClient.post(exchangeId, {
agent: httpsAgent,
json: {verifiablePresentation}
});
} catch(e) {
error = e;
}
// prepare result
const result = {
credential,
verified: response?.status === 200,
error: error?.data,
exchange: undefined,
expired: undefined
};
// fetch exchange if requested or if VC is an enveloped VC
const isEnvelopedVC = credential?.type === 'EnvelopedVerifiableCredential';
if(returnExchange || isEnvelopedVC) {
// fetch unenveloped credential from exchange state
try {
const response = await zcapClient.read({url: exchangeId, capability});
const {data: {exchange}} = response;
if(returnExchange) {
result.exchange = exchange;
return result;
}
// use exchange state to update `credential`
if(isEnvelopedVC) {
// update `credential`
const {getCredentialFromExchange} = options;
credential = await getCredentialFromExchange({exchange, credential});
result.credential = credential;
}
} catch(cause) {
throw new BedrockError(
'Could not fetch verification exchange state.', {
name: 'OperationError',
details: {httpStatusCode: 500, public: true},
cause
});
}
}
if(checkExpiration) {
result.expired = isExpired({credential, maxClockSkew});
}
return result;
}
export async function verifyVcb({text, barcode, getVerifyOptions} = {}) {
try {
const verifyOptions = await getVerifyOptions({text});
const {
barcodeToCredential: getCredential = barcodeToCredential,
documentLoader = _throwNotFoundError,
verifyCredential
} = verifyOptions;
assert.func(getCredential);
assert.func(documentLoader);
assert.func(verifyCredential);
const {credential} = await getCredential({
text, barcode, documentLoader, typeTableLoader: _typeTableLoader
});
assert.object(credential);
return verifyCredential({credential});
} catch(cause) {
throw new BedrockError(
'Unable to verify VCB: ' + cause.message, {
name: 'OperationError',
// FIXME: should this be a 4xx?
details: {httpStatusCode: 500, public: true},
public: true,
cause
});
}
}
function _compareTime({t1, t2, maxClockSkew}) {
// `maxClockSkew` is in seconds, so transform to milliseconds
if(Math.abs(t1 - t2) < (maxClockSkew * 1000)) {
// times are equal within the max clock skew
return 0;
}
return t1 < t2 ? -1 : 1;
}
function _getCredentialFromExchange({exchange} = {}) {
// assume single step
const stepResults = exchange.variables?.results;
if(stepResults) {
const stepNames = Object.keys(stepResults);
const stepResult = stepResults[stepNames[0]];
const vc = stepResult?.verifiablePresentation.verifiableCredential;
if(Array.isArray(vc)) {
return vc[0];
}
return vc;
}
}
function _throwNotFoundError(url) {
throw new BedrockError(`Document "${url}" not found`, {
name: 'NotFoundError',
details: {httpStatusCode: 404, public: true},
public: true
});
}