-
Notifications
You must be signed in to change notification settings - Fork 1
/
DataIntegrityProof.js
460 lines (414 loc) · 15.3 KB
/
DataIntegrityProof.js
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*!
* Copyright (c) 2022-2023 Digital Bazaar, Inc. All rights reserved.
*/
import * as base58btc from 'base58-universal';
import * as base64url from 'base64url-universal';
import * as util from './util.js';
import jsigs from 'jsonld-signatures';
import {sha256digest} from './sha256digest.js';
const {suites: {LinkedDataProof}} = jsigs;
// multibase base58-btc header
const MULTIBASE_BASE58BTC_HEADER = 'z';
// multibase base64url no pad header
const MULTIBASE_BASE64URL_HEADER = 'u';
const DATA_INTEGRITY_CONTEXT = 'https://w3id.org/security/data-integrity/v1';
const PROOF_TYPE = 'DataIntegrityProof';
// VCDM 2.0 core context
const VC_2_0_CONTEXT = 'https://www.w3.org/ns/credentials/v2';
export class DataIntegrityProof extends LinkedDataProof {
constructor({signer, date, cryptosuite} = {}) {
super({type: PROOF_TYPE});
const {
canonize, createVerifier, name, requiredAlgorithm,
derive, createProofValue, createVerifyData
} = cryptosuite;
// `createVerifier` is required
if(!(createVerifier && typeof createVerifier === 'function')) {
throw new TypeError(
'"cryptosuite.createVerifier" must be a function.');
}
// assert optional functions
if(derive && typeof derive !== 'function') {
throw new TypeError(
'"cryptosuite.derive" must be a function.');
}
if(createProofValue && typeof createProofValue !== 'function') {
throw new TypeError(
'"cryptosuite.createProofValue" must be a function.');
}
if(createVerifyData && typeof createVerifyData !== 'function') {
throw new TypeError(
'"cryptosuite.createVerifyData" must be a function.');
}
this.contextUrl = DATA_INTEGRITY_CONTEXT;
this.canonize = canonize;
this.createVerifier = createVerifier;
this.cryptosuite = name;
// save internal reference to cryptosuite instance
this._cryptosuite = cryptosuite;
this.requiredAlgorithm = requiredAlgorithm;
if(date) {
this.date = new Date(date);
if(isNaN(this.date)) {
throw TypeError(`"date" "${date}" is not a valid date.`);
}
}
const vm = _processSignatureParams({signer, requiredAlgorithm});
this.verificationMethod = vm.verificationMethod;
this.signer = vm.signer;
}
/**
* Adds a signature (proofValue) field to the proof object. Called by
* LinkedDataSignature.createProof().
*
* @param {object} options - The options to use.
* @param {Uint8Array|object} options.verifyData - Data to be signed
* (extracted from document, according to the suite's spec).
* @param {object} options.proof - Proof object (containing the proofPurpose,
* verificationMethod, etc).
*
* @returns {Promise<object>} Resolves with the proof containing the signature
* value.
*/
async sign({verifyData, proof}) {
if(!(this.signer && typeof this.signer.sign === 'function')) {
throw new Error('A signer API has not been specified.');
}
const signatureBytes = await this.signer.sign({data: verifyData});
proof.proofValue =
MULTIBASE_BASE58BTC_HEADER + base58btc.encode(signatureBytes);
return proof;
}
/**
* Verifies the proof signature against the given data.
*
* @param {object} options - The options to use.
* @param {Uint8Array|object} options.verifyData - Verify data as produced
* from `createVerifyData`.
* @param {object} options.verificationMethod - Key object.
* @param {object} options.proof - The proof to be verified.
*
* @returns {Promise<boolean>} Resolves with the verification result.
*/
async verifySignature({verifyData, verificationMethod, proof}) {
const verifier = await this.createVerifier({verificationMethod});
if(this.requiredAlgorithm !== verifier.algorithm) {
const message = `The verifier's algorithm ` +
`"${verifier.algorithm}" ` +
`does not match the required algorithm for the cryptosuite ` +
`"${this.requiredAlgorithm}".`;
throw new Error(message);
}
const {proofValue} = proof;
if(!(proofValue && typeof proofValue === 'string')) {
throw new TypeError(
'The proof does not include a valid "proofValue" property.');
}
const multibaseHeader = proofValue[0];
let signature;
if(multibaseHeader === MULTIBASE_BASE58BTC_HEADER) {
signature = base58btc.decode(proofValue.slice(1));
} else if(multibaseHeader === MULTIBASE_BASE64URL_HEADER) {
signature = base64url.decode(proofValue.slice(1));
} else {
throw new Error(
'Only base58btc or base64url multibase encoding is supported.');
}
return verifier.verify({data: verifyData, signature});
}
/**
* @param {object} options - The options to use.
* @param {object} options.document - The document to create a proof for.
* @param {object} options.purpose - The `ProofPurpose` instance to use.
* @param {Array} options.proofSet - Any existing proof set.
* @param {Function} options.documentLoader - The document loader to use.
*
* @returns {Promise<object>} Resolves with the created proof object.
*/
async createProof({document, purpose, proofSet, documentLoader}) {
// build proof (currently known as `signature options` in spec)
let proof;
if(this.proof) {
// shallow copy
proof = {...this.proof};
} else {
// create proof JSON-LD document
proof = {};
}
// ensure proof type is set
proof.type = this.type;
// set default `now` date if not given in `proof` or `options`
let date = this.date;
if(proof.created === undefined && date === undefined) {
date = new Date();
}
// ensure date is in string format
if(date && typeof date !== 'string') {
date = util.w3cDate(date);
}
// add API overrides
if(date) {
proof.created = date;
}
proof.verificationMethod = this.verificationMethod;
proof.cryptosuite = this.cryptosuite;
// add any extensions to proof (mostly for legacy support)
proof = await this.updateProof({
document, proof, purpose, proofSet, documentLoader
});
// allow purpose to update the proof; any terms added to `proof` must have
// be compatible with its context
proof = await purpose.update(
proof, {document, suite: this, documentLoader});
// create data to sign
let verifyData;
// use custom cryptosuite `createVerifyData` if available
if(this._cryptosuite.createVerifyData) {
verifyData = await this._cryptosuite.createVerifyData({
cryptosuite: this._cryptosuite,
document, proof, proofSet, documentLoader,
dataIntegrityProof: this
});
} else {
verifyData = await this.createVerifyData(
{document, proof, proofSet, documentLoader});
}
// use custom `createProofValue` if available
if(this._cryptosuite.createProofValue) {
proof.proofValue = await this._cryptosuite.createProofValue({
cryptosuite: this._cryptosuite,
verifyData, document, proof, proofSet,
documentLoader, dataIntegrityProof: this
});
} else {
// default to simple signing of data
proof = await this.sign(
{verifyData, document, proof, proofSet, documentLoader});
}
return proof;
}
/**
* @param {object} options - The options to use.
* @param {object} options.document - The document to derive from.
* @param {object} options.purpose - The `ProofPurpose` instance to use.
* @param {Array} options.proofSet - Any existing proof set.
* @param {Function} options.documentLoader - The document loader to use.
*
* @returns {Promise<object>} Resolves with the new document with a new
* `proof` field.
*/
async derive({document, purpose, proofSet, documentLoader}) {
// delegate entirely to cryptosuite instance
if(!this._cryptosuite.derive) {
throw new Error('"cryptosuite.derive" not provided.');
}
return this._cryptosuite.derive({
cryptosuite: this._cryptosuite, document, purpose, proofSet,
documentLoader, dataIntegrityProof: this
});
}
/**
* @param {object} options - The options to use.
* @param {object} options.proof - The proof to update.
*
* @returns {Promise<object>} Resolves with the created proof object.
*/
async updateProof({proof}) {
return proof;
}
/**
* @param {object} options - The options to use.
* @param {object} options.proof - The proof to verify.
* @param {Array} options.proofSet - Any existing proof set.
* @param {object} options.document - The document to create a proof for.
* @param {Function} options.documentLoader - The document loader to use.
*
* @returns {Promise<{object}>} Resolves with the verification result.
*/
async verifyProof({proof, proofSet, document, documentLoader}) {
try {
// create data to verify
let verifyData;
// use custom cryptosuite `createVerifyData` if available
if(this._cryptosuite.createVerifyData) {
verifyData = await this._cryptosuite.createVerifyData({
cryptosuite: this._cryptosuite,
document, proof, proofSet, documentLoader,
dataIntegrityProof: this
});
} else {
verifyData = await this.createVerifyData(
{document, proof, proofSet, documentLoader});
}
// fetch verification method
const verificationMethod = await this.getVerificationMethod({
proof, documentLoader
});
// verify signature on data
const verified = await this.verifySignature({
verifyData, verificationMethod, proof
});
if(!verified) {
throw new Error('Invalid signature.');
}
return {verified: true, verificationMethod};
} catch(error) {
return {verified: false, error};
}
}
/**
* @param {object} options - The options to use.
* @param {object} options.document - The document to create verify data for.
* @param {object} options.proof - The proof to create verify data for.
* @param {Function} options.documentLoader - The document loader to use.
*
* @returns {Promise<Uint8Array|object>} Resolves to the verify data to
* be passed to `sign` or `verifySignature`.
*/
async createVerifyData({document, proof, documentLoader}) {
// get cached document hash
let cachedDocHash;
const {_hashCache} = this;
if(_hashCache && _hashCache.document === document) {
cachedDocHash = _hashCache.hash;
} else {
this._hashCache = {
document,
// canonize and hash document
hash: cachedDocHash =
this.canonize(document, {documentLoader})
.then(c14nDocument => sha256digest({string: c14nDocument}))
};
}
// await both c14n proof hash and c14n document hash
const [proofHash, docHash] = await Promise.all([
// canonize and hash proof
this.canonizeProof(proof, {document, documentLoader})
.then(c14nProofOptions => sha256digest({string: c14nProofOptions})),
cachedDocHash
]);
// concatenate hash of c14n proof options and hash of c14n document
return util.concat(proofHash, docHash);
}
/**
* @param {object} options - The options to use.
* @param {object} options.proof - The proof for which to get the
* verification method.
* @param {Function} options.documentLoader - The document loader to use.
*/
async getVerificationMethod({proof, documentLoader}) {
let {verificationMethod} = proof;
if(typeof verificationMethod === 'object') {
verificationMethod = verificationMethod.id;
}
if(!verificationMethod) {
throw new Error('No "verificationMethod" found in proof.');
}
const result = await documentLoader(verificationMethod);
if(!result) {
throw new Error(
`Unable to load verification method "${verificationMethod}".`);
}
const {document} = result;
verificationMethod = typeof document === 'string' ?
JSON.parse(document) : document;
return verificationMethod;
}
async canonizeProof(proof, {documentLoader, document}) {
// `proofValue` must not be included in the proof options
proof = {
'@context': document['@context'],
...proof
};
this.ensureSuiteContext({document: proof, addSuiteContext: true});
delete proof.proofValue;
return this.canonize(proof, {documentLoader, skipExpansion: false});
}
/**
* Checks whether a given proof exists in the document.
*
* @param {object} options - The options to use.
* @param {object} options.proof - The proof to match.
*
* @returns {Promise<boolean>} Whether a match for the proof was found.
*/
async matchProof({
proof /*, document, purpose, documentLoader, expansionMap */
}) {
const {type, cryptosuite} = proof;
return type === this.type && cryptosuite === this.cryptosuite;
}
/**
* Ensures the document to be signed contains the required signature suite
* specific `@context`, by either adding it (if `addSuiteContext` is true),
* or throwing an error if it's missing.
*
* @param {object} options - Options hashmap.
* @param {object} options.document - JSON-LD document to be signed.
* @param {boolean} options.addSuiteContext - Add suite context?
*/
ensureSuiteContext({document, addSuiteContext}) {
const {contextUrl} = this;
if(_includesContext({document, contextUrl}) ||
_includesContext({document, contextUrl: VC_2_0_CONTEXT})) {
// document already includes the required context
return;
}
if(!addSuiteContext) {
throw new TypeError(
`The document to be signed must contain this suite's @context, ` +
`"${contextUrl}".`);
}
// enforce the suite's context by adding it to the document
const existingContext = document['@context'] || [];
document['@context'] = Array.isArray(existingContext) ?
[...existingContext, contextUrl] : [existingContext, contextUrl];
}
}
/**
* Tests whether a provided JSON-LD document includes a context URL in its
* `@context` property.
*
* @param {object} options - Options hashmap.
* @param {object} options.document - A JSON-LD document.
* @param {string} options.contextUrl - A context URL.
*
* @returns {boolean} Returns true if document includes context.
*/
function _includesContext({document, contextUrl}) {
const context = document['@context'];
return context === contextUrl ||
(Array.isArray(context) && context.includes(contextUrl));
}
/**
* See constructor docstring for param details.
*
* @param {object} options - The options to use.
* @param {object} options.signer - The signer to use.
* @param {object} options.requiredAlgorithm - The required algorithm.
* @returns {{verificationMethod: string
* signer: {sign: Function, id: string, algorithm: string}}}} - Validated and
* initialized signature-related parameters.
*/
function _processSignatureParams({signer, requiredAlgorithm}) {
const vm = {
verificationMethod: undefined,
signer: undefined
};
if(!signer) {
return vm;
}
if(typeof signer.sign !== 'function') {
throw new TypeError('A signer API has not been specified.');
}
if(requiredAlgorithm !== signer.algorithm) {
const message = `The signer's algorithm ` +
`"${signer.algorithm}" ` +
`does not match the required algorithm for the cryptosuite ` +
`"${requiredAlgorithm}".`;
throw new Error(message);
}
vm.signer = signer;
vm.verificationMethod = signer.id;
return vm;
}