|
| 1 | +import { describe, expect, it } from 'vitest'; |
| 2 | +import { HashTree, reconstruct, Cbor } from '@dfinity/agent'; |
| 3 | +import { CertificateBuilder } from '@dfinity/certification-test-utils'; |
| 4 | +import { Principal } from '@dfinity/principal'; |
| 5 | +import { createHash, webcrypto } from 'node:crypto'; |
| 6 | +import { verifyCertification } from './index'; |
| 7 | + |
| 8 | +globalThis.crypto = webcrypto as Crypto; |
| 9 | + |
| 10 | +describe('verifyCertification', () => { |
| 11 | + it('should verify a valid certificate with delegation', async () => { |
| 12 | + const userId = '1234'; |
| 13 | + |
| 14 | + const username = 'testuser'; |
| 15 | + const usernameHash = new Uint8Array( |
| 16 | + createHash('sha256').update(username).digest(), |
| 17 | + ); |
| 18 | + |
| 19 | + const hashTree: HashTree = [ |
| 20 | + 2, |
| 21 | + new Uint8Array(Buffer.from(userId)), |
| 22 | + [3, usernameHash], |
| 23 | + ]; |
| 24 | + const rootHash = await reconstruct(hashTree); |
| 25 | + const cborEncodedTree = Cbor.encode(hashTree); |
| 26 | + |
| 27 | + const canisterId = Principal.fromUint8Array( |
| 28 | + new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1]), |
| 29 | + ); |
| 30 | + const time = BigInt(Date.now()); |
| 31 | + |
| 32 | + const certificate = new CertificateBuilder( |
| 33 | + canisterId.toString(), |
| 34 | + new Uint8Array(rootHash), |
| 35 | + ) |
| 36 | + .withTime(time) |
| 37 | + .withDelegation(123n, [{ high: 10, low: 0 }]) |
| 38 | + .build(); |
| 39 | + |
| 40 | + const decodedHashTree = await verifyCertification({ |
| 41 | + canisterId, |
| 42 | + encodedCertificate: certificate.cborEncodedCertificate, |
| 43 | + encodedTree: cborEncodedTree, |
| 44 | + maxCertificateTimeOffsetMs: 5000, |
| 45 | + rootKey: certificate.rootKey, |
| 46 | + }); |
| 47 | + expect(decodedHashTree).toEqual(hashTree); |
| 48 | + }); |
| 49 | +}); |
0 commit comments