Files
Rosea/packages/identity/test/identity.test.ts
T

39 lines
1.8 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import { createIdentity, isIdentity } from '../src/index.js';
describe('createIdentity', () => {
it('makes a public key that fits the care event\'s key pattern', async () => {
const id = await createIdentity();
expect(id.publicKey).toMatch(/^[A-Za-z0-9_-]{32,128}$/);
expect(id.publicKey).toHaveLength(87); // 65 raw bytes of an uncompressed P-256 point
});
it('two identities are two different keys', async () => {
const [a, b] = await Promise.all([createIdentity(), createIdentity()]);
expect(a.publicKey).not.toBe(b.publicKey);
});
it('the private key cannot be exported, so it cannot leave the device', async () => {
const id = await createIdentity();
expect(id.privateKey.extractable).toBe(false);
await expect(crypto.subtle.exportKey('pkcs8', id.privateKey)).rejects.toThrow();
});
it('the private key still signs, and the public key verifies it', async () => {
const id = await createIdentity();
const data = new TextEncoder().encode('a petal');
const sig = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, id.privateKey, data);
const raw = Uint8Array.from(atob(id.publicKey.replace(/-/g, '+').replace(/_/g, '/') + '='), (c) => c.charCodeAt(0));
const pub = await crypto.subtle.importKey('raw', raw, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
expect(await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, pub, sig, data)).toBe(true);
});
it('isIdentity accepts one and refuses lookalikes', async () => {
const id = await createIdentity();
expect(isIdentity(id)).toBe(true);
expect(isIdentity({ publicKey: id.publicKey, privateKey: 'secret' })).toBe(false);
expect(isIdentity({ publicKey: 'short', privateKey: id.privateKey })).toBe(false);
expect(isIdentity(null)).toBe(false);
});
});