-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
573 lines (497 loc) · 17.1 KB
/
index.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
import * as bbs2023Cryptosuite from '@digitalbazaar/bbs-2023-cryptosuite';
import * as Bls12381Multikey from '@digitalbazaar/bls12-381-multikey';
import * as EcdsaMultikey from '@digitalbazaar/ecdsa-multikey';
import * as ecdsaRdfc2019Cryptosuite from
'@digitalbazaar/ecdsa-rdfc-2019-cryptosuite';
import * as ecdsaSd2023Cryptosuite
from '@digitalbazaar/ecdsa-sd-2023-cryptosuite';
import * as Ed25519Multikey from '@digitalbazaar/ed25519-multikey';
import * as examples1Context from '@digitalbazaar/credentials-examples-context';
import * as jose from 'jose';
import * as mfHasher from 'multiformats/hashes/hasher';
import * as odrlContext from '@digitalbazaar/odrl-context';
import {base64pad, base64url} from 'multiformats/bases/base64';
import {defaultDocumentLoader, issue} from '@digitalbazaar/vc';
import {extendContextLoader, purposes} from 'jsonld-signatures';
import {sha3_256, sha3_384} from '@noble/hashes/sha3';
import {base16} from 'multiformats/bases/base16';
import {base58btc} from 'multiformats/bases/base58';
import {DataIntegrityProof} from '@digitalbazaar/data-integrity';
import ed25519Context from 'ed25519-signature-2020-context';
import {Ed25519Signature2020} from '@digitalbazaar/ed25519-signature-2020';
import {Ed25519VerificationKey2020} from
'@digitalbazaar/ed25519-verification-key-2020';
import {cryptosuite as eddsaRdfc2022CryptoSuite} from
'@digitalbazaar/eddsa-rdfc-2022-cryptosuite';
import examples2Context from './contexts/credentials/examples/v2';
import {sha256} from '@noble/hashes/sha256';
import {sha384} from '@noble/hashes/sha512';
// default types
const TAB_TYPES = [
'ecdsa-rdfc-2019',
'eddsa-rdfc-2022',
'ecdsa-sd-2023',
'bbs-2023',
'vc-jwt'
];
// additional types: Ed25519Signature2020
// purposes used below
const {AssertionProofPurpose} = purposes;
// setup contexts used by respec-vc
const contexts = {};
for(const item of [odrlContext, ed25519Context, examples1Context]) {
for(const [url, context] of item.contexts) {
contexts[url] = context;
}
}
contexts['https://www.w3.org/ns/credentials/examples/v2'] = examples2Context;
// setup static document loader
const documentLoader = extendContextLoader(async function documentLoader(url) {
const context = contexts[url];
if(context !== undefined) {
return {
contextUrl: null,
documentUrl: url,
document: context
};
}
return defaultDocumentLoader(url);
});
async function createBBSExampleProof() {
const key = await Bls12381Multikey.generateBbsKeyPair({
algorithm: Bls12381Multikey.ALGORITHMS.BBS_BLS12381_SHA256
});
const proof = new DataIntegrityProof({
signer: key.signer(),
cryptosuite: bbs2023Cryptosuite.createSignCryptosuite({
mandatoryPointers: ['/issuer']
})
});
return {
proof,
key,
label: 'bbs'
};
}
async function createEcdsaRdfc2019ExampleProof() {
const key = await EcdsaMultikey
.generate({curve: 'P-256'});
// ecdsa-rdfc-2019
const {cryptosuite: rdfcCryptosuite} = ecdsaRdfc2019Cryptosuite;
const proof = new DataIntegrityProof({
signer: key.signer(),
cryptosuite: rdfcCryptosuite
});
return {
proof,
key,
label: 'ecdsa'
};
}
async function createEcdsaSd2023ExampleProof() {
const key = await EcdsaMultikey
.generate({curve: 'P-256'});
// ecdsa-sd-2023
const {createSignCryptosuite} = ecdsaSd2023Cryptosuite;
const proof = new DataIntegrityProof({
signer: key.signer(),
cryptosuite: createSignCryptosuite({
mandatoryPointers: ['/issuer']
})
});
return {
proof,
key,
label: 'ecdsa-sd'
};
}
async function createEddsaRdfc2022ExampleProof() {
// Ed25519Signature2020
const keyPairEd25519VerificationKey2020 = await Ed25519VerificationKey2020
.generate();
const key = await Ed25519Multikey
.from(keyPairEd25519VerificationKey2020);
// eddsa-rdfc-2022
const proof = new DataIntegrityProof({
signer: key.signer(),
cryptosuite: eddsaRdfc2022CryptoSuite
});
return {
proof,
key,
label: 'eddsa'
};
}
// convert an XML Schema v1.` Datetime value to a UNIX timestamp
function xmlDateTimeToUnixTimestamp(xmlDateTime) {
if(!xmlDateTime) {
return undefined;
}
return Date.parse(xmlDateTime) / 1000;
}
// transform the input credential to a JWT
async function transformToJwt({credential, kid, jwk}) {
const header = {alg: 'ES256', typ: 'JWT', kid};
const payload = {
vc: credential
};
if(credential.expirationDate) {
payload.exp = xmlDateTimeToUnixTimestamp(credential.expirationDate);
}
if(credential.issuer) {
payload.iss = credential.issuer;
}
if(credential.issuanceDate) {
payload.nbf = xmlDateTimeToUnixTimestamp(credential.issuanceDate);
}
if(credential.id) {
payload.jti = credential.id;
}
if(credential.credentialSubject.id) {
payload.sub = credential.credentialSubject.id;
}
// create the JWT description
let description = '---------------- JWT header ---------------\n' +
JSON.stringify(header, null, 2);
description += '\n\n--------------- JWT payload ---------------\n' +
'// NOTE: The example below uses a valid VC-JWT serialization\n' +
'// that duplicates the iss, nbf, jti, and sub fields in the\n' +
'// Verifiable Credential (vc) field.\n\n' +
JSON.stringify(payload, null, 2);
const jwt = await new jose.SignJWT(payload)
.setProtectedHeader(header)
.sign(jwk.privateKey);
return description + '\n\n--------------- JWT ---------------\n\n' + jwt;
}
async function attachProof({credential, suite}) {
const credentialCopy = JSON.parse(JSON.stringify(credential));
const options = {credential: credentialCopy, suite, documentLoader};
options.purposes = new AssertionProofPurpose();
return issue(options);
}
function addVcExampleStyles() {
const exampleStyles = document.createElement('style');
const radioLabels = [...Array(TAB_TYPES.length + 1).keys()]
.map(i => {
const j = i + 1;
return `.vc-tabbed [type="radio"]:nth-of-type(${j}):checked ~ .vc-tabs .vc-tab:nth-of-type(${j}) label`;
});
const radioSelector = [...Array(TAB_TYPES.length + 1).keys()]
.map(i => {
const j = i + 1;
return `.vc-tabbed [type="radio"]:nth-of-type(${j}):checked ~ .vc-tab-content:nth-of-type(${j})`;
});
exampleStyles.innerHTML += `
.vc-tabbed {
overflow-x: hidden;
margin: 0 0;
}
.vc-tabbed [type="radio"] {
display: none;
}
.vc-tabs {
display: flex;
align-items: stretch;
list-style: none;
padding: 0;
border-bottom: 1px solid #ccc;
}
li.vc-tab {
margin: unset;
}
.vc-tab > label {
display: block;
margin-bottom: -1px;
padding: .4em .5em;
border: 1px solid #ccc;
border-top-right-radius: .4em;
border-top-left-radius: .4em;
background: #eee;
color: #666;
cursor: pointer;
transition: all 0.3s;
}
.vc-tab:hover label {
border-left-color: #333;
border-top-color: #333;
border-right-color: #333;
color: #333;
}
.vc-tab-content {
display: none;
}
${radioLabels.join(',\n ')} {
border-bottom-color: #fff;
background: #fff;
color: #222;
}
${radioSelector.join(',\n ')} {
display: block;
}`;
document.getElementsByTagName('head')[0].appendChild(exampleStyles);
}
function addContext(url, context) {
contexts[url] = context;
}
async function createVcExamples() {
// process all 'vc-hash' entries
const sha2256Hasher = mfHasher.from({
name: 'sha2-256',
code: 0x12,
encode: input => sha256(input)
});
const sha2384Hasher = mfHasher.from({
name: 'sha2-384',
code: 0x20,
encode: input => sha384(input)
});
const sha3256Hasher = mfHasher.from({
name: 'sha3-256',
code: 0x16,
encode: input => sha3_256(input)
});
const sha3384Hasher = mfHasher.from({
name: 'sha3-384',
code: 0x15,
encode: input => sha3_384(input)
});
const vcHashEntries = document.querySelectorAll('.vc-hash');
for(const hashEntry of vcHashEntries) {
// get the hash requirements
const hashUrl = hashEntry.dataset?.hashUrl || 'INVALID_URL';
const hashFormat = hashEntry.dataset?.hashFormat?.split(/(\s+)/) || [];
let encodedHash = null;
// select the base encoder (default: base64-url with no padding)
let baseEncoder;
if(hashFormat.includes('sri')) {
baseEncoder = base64pad;
} else if(hashFormat.includes('base16')) {
baseEncoder = base16;
} else if(hashFormat.includes('base58btc')) {
baseEncoder = base58btc;
} else {
baseEncoder = base64url;
}
// retrieve the file and generate the hash
try {
const response = await fetch(hashUrl);
// ensure retrieval succeeded
if(response.status !== 200) {
throw new Error('Failed to retrieve ' + hashUrl);
}
const hashData = new Uint8Array(await response.arrayBuffer());
// determine the hash algorithm to use and produce the output accordingly
if(hashFormat.includes('openssl') && hashFormat.includes('-sha256')) {
const mfHash = await sha2256Hasher.digest(hashData);
encodedHash = Array.prototype.map.call(mfHash.digest, byte => {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
} else if(hashFormat.includes('sri')) {
if(hashFormat.includes('sha2-256')) {
const mfHash = await sha2256Hasher.digest(hashData);
encodedHash = 'sha256-' + baseEncoder.encode(mfHash.digest);
} else if(hashFormat.includes('sha2-384')) {
const mfHash = await sha2384Hasher.digest(hashData);
encodedHash = 'sha384-' + baseEncoder.encode(mfHash.digest);
}
} else if(hashFormat.includes('multihash')) {
if(hashFormat.includes('sha2-256')) {
const mfHash = await sha2256Hasher.digest(hashData).bytes;
encodedHash = baseEncoder.encode(mfHash);
} else if(hashFormat.includes('sha2-384')) {
const mfHash = await sha2384Hasher.digest(hashData).bytes;
encodedHash = baseEncoder.encode(mfHash);
} else if(hashFormat.includes('sha3-256')) {
const mfHash = await sha3256Hasher.digest(hashData).bytes;
encodedHash = baseEncoder.encode(mfHash);
} else if(hashFormat.includes('sha3-384')) {
const mfHash = await sha3384Hasher.digest(hashData).bytes;
encodedHash = baseEncoder.encode(mfHash);
}
}
// set the encodedHash value
hashEntry.innerText = encodedHash || 'Unsupported hash format: \'' +
hashEntry.dataset?.hashFormat + '\'';
} catch(e) {
console.error('respec-vc error: Failed to create cryptographic hash.',
e, hashEntry);
hashEntry.innerText = 'Error generating cryptographic hash for ' +
hashUrl;
continue;
}
}
// process all 'vc' entries
const exampleProofs = [];
// ecdsa-rdfc-2019
const ecdsaRdfc2019 = await createEcdsaRdfc2019ExampleProof();
exampleProofs.push(ecdsaRdfc2019);
// Ed25519Signature2020
const keyPairEd25519VerificationKey2020 = await Ed25519VerificationKey2020
.generate();
const suiteEd25519Signature2020 = new Ed25519Signature2020({
key: keyPairEd25519VerificationKey2020
});
// eddsa-rdfc-2022
const eddsaRdfc2022 = await createEddsaRdfc2022ExampleProof();
exampleProofs.push(eddsaRdfc2022);
// ecdsa-sd-2023
const ecdsaSd2023 = await createEcdsaSd2023ExampleProof();
exampleProofs.push(ecdsaSd2023);
// bbs-2023
const bbs2023 = await createBBSExampleProof();
exampleProofs.push(bbs2023);
// vc-jwt
const jwk = await jose.generateKeyPair('ES256');
// add styles for examples
addVcExampleStyles();
// process every example that needs a vc-proof
const vcProofExamples = document.querySelectorAll('.vc');
let vcProofExampleIndex = 0;
for(const example of vcProofExamples) {
vcProofExampleIndex++;
const verificationMethod = example.dataset?.vcVm ||
'did:key:' + keyPairEd25519VerificationKey2020.publicKeyMultibase;
const tabTypes = example.dataset?.vcTabs || TAB_TYPES;
// extract and parse the example as JSON
let credential = {};
try {
let exampleText = example.innerText;
exampleText = exampleText.replace(/\/\/ .*$/gm, '');
credential = JSON.parse(exampleText);
} catch(e) {
console.error('respec-vc error: Failed to create Verifiable Credential.',
e, example.innerText);
continue;
}
// set up the tabbed content
const tabbedContent = document.createElement('div');
tabbedContent.setAttribute('class', 'vc-tabbed');
// set up the tab labels
const tabLabels = document.createElement('ul');
tabLabels.setAttribute('class', 'vc-tabs');
tabbedContent.appendChild(tabLabels);
/**
* Definition for the content callback used by addTab.
*
* @callback contentCallback
*/
/**
* Add tab to tab container in DOM. Run callback function to populate
* content on tab click.
*
* @param {string} suffix - One of the TAB_TYPES values (or `unsigned`).
* @param {string} labelText - Human readable label name.
* @param {string} tabText - Text to display on the tab.
* @param {contentCallback} callback - Function which returns HTML.
*/
function addTab(suffix, labelText, tabText, callback) {
const button = document.createElement('input');
button.setAttribute('type', 'radio');
button.setAttribute('id', `vc-tab${vcProofExampleIndex}${suffix}`);
button.setAttribute('name', `vc-tabs${vcProofExampleIndex}`);
if(tabbedContent.firstChild.tagName === 'INPUT') {
// place this one last of the inputs
[...tabbedContent.querySelectorAll('input')].pop().after(button);
} else {
tabbedContent.prepend(button);
}
const label = document.createElement('li');
label.setAttribute('class', 'vc-tab');
const tabLabel = document.createElement('label');
tabLabel.setAttribute('for', button.getAttribute('id'));
const abbr = document.createElement('abbr');
abbr.setAttribute('title', labelText);
abbr.innerText = tabText;
tabLabel.appendChild(abbr);
label.appendChild(tabLabel);
tabLabels.appendChild(label);
const content = document.createElement('div');
content.setAttribute('class', 'vc-tab-content');
content.style.minHeight = `${example.clientHeight}px`;
tabbedContent.appendChild(content);
if(suffix === 'unsigned') {
content.innerHTML = callback();
} else {
label.addEventListener('click', async () => {
content.innerHTML = await callback();
}, {once: true});
}
}
/**
* Add a Data Integrity based proof example tab.
*
* @global string verificationMethod
* @param {object} suite - Suite object.
* @param {string} tabText - Text to display on the tab.
* @param {string | undefined} key - Optional key to use for the proof.
*/
async function addProofTab(suite, tabText, key) {
let verifiableCredentialProof;
const label = suite?.cryptosuite || suite.type;
if(key) {
suite.verificationMethod = 'did:key:' + key.publicKeyMultibase;
} else {
suite.verificationMethod = verificationMethod;
}
addTab(label, `Secured with Data Integrity - ${label}`, tabText, async () => {
// attach the proof
try {
verifiableCredentialProof = await attachProof({credential, suite});
return `<pre>${JSON.stringify(verifiableCredentialProof, null, 2)
.match(/.{1,75}/g).join('\n')}</pre>`;
} catch(e) {
console.error(
'respec-vc error: Failed to attach proof to Verifiable Credential.',
e, example.innerText);
}
});
}
function hasTab(identifier) {
return tabTypes.indexOf(identifier) > -1;
}
// set up the unsigned button
addTab(
'unsigned',
'Unsecured credential',
'Credential',
() => example.outerHTML
);
for(const {proof, key, label} of exampleProofs) {
if(hasTab(proof.cryptosuite)) {
await addProofTab(proof, label, key);
}
}
if(hasTab(suiteEd25519Signature2020.type)) {
await addProofTab(suiteEd25519Signature2020, 'Ed25519Signature2020');
}
if(hasTab('vc-jwt')) {
// set up the signed JWT button
addTab('vc-jwt', 'Secured with VC-JWT', 'vc-jwt',
async () => {
// convert to a JWT
let verifiableCredentialJwt;
try {
verifiableCredentialJwt = await transformToJwt({
credential, kid: verificationMethod, jwk});
return `<pre>${verifiableCredentialJwt.match(/.{1,75}/g).join('\n')}</pre>`;
} catch(e) {
console.error(
'respec-vc error: Failed to convert Credential to JWT.',
e, example.innerText);
}
});
}
// append the tabbed content
// replace the original example with the tabbed content
const container = example.parentNode;
// set first radio as checked
tabbedContent.querySelector('input').toggleAttribute('checked');
container.append(tabbedContent);
example.remove();
}
}
// setup exports on window
window.respecVc = {
addContext,
createVcExamples
};