[identity] Keypair: Make the player's ECDSA P-256 key on the device, private key non-extractable
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@rosea/identity",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Keypair lifecycle. The ONLY module that creates key material (CLAUDE.md §2).",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json",
|
||||
"test": "vitest run --reporter=verbose"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* The player's identity: a keypair made on the device, and nothing else (CLAUDE.md §1,
|
||||
* *Anonymous*). No account, no name, no number. The public key is how the care log
|
||||
* names the rose (`from`, `to`); the private key cannot be exported, so it can never
|
||||
* leave this browser even by mistake. Nothing signs anything yet: that arrives with
|
||||
* friends (Phase 3).
|
||||
*
|
||||
* ECDSA P-256, not Ed25519: every browser that can install the PWA has it
|
||||
* (.agents/features/rose.md R9).
|
||||
*/
|
||||
|
||||
export interface Identity {
|
||||
/** The raw public key, base64url without padding: 87 characters. */
|
||||
readonly publicKey: string;
|
||||
/** Non-extractable. Kept by @rosea/storage as an opaque CryptoKey. */
|
||||
readonly privateKey: CryptoKey;
|
||||
}
|
||||
|
||||
const ALGORITHM: EcKeyGenParams = { name: 'ECDSA', namedCurve: 'P-256' };
|
||||
/** The schema's public-key pattern (packages/schema care-event, `publicKey`). */
|
||||
const PUBLIC_KEY = /^[A-Za-z0-9_-]{32,128}$/;
|
||||
|
||||
function base64url(bytes: Uint8Array): string {
|
||||
let s = '';
|
||||
for (const b of bytes) s += String.fromCharCode(b);
|
||||
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
/** Makes a new identity. `subtle` is a parameter so a test can pass Node's. */
|
||||
export async function createIdentity(subtle: SubtleCrypto = globalThis.crypto.subtle): Promise<Identity> {
|
||||
// extractable: false applies to the private key; the public key is always exportable.
|
||||
const pair = await subtle.generateKey(ALGORITHM, false, ['sign', 'verify']);
|
||||
const publicKey = base64url(new Uint8Array(await subtle.exportKey('raw', pair.publicKey)));
|
||||
return { publicKey, privateKey: pair.privateKey };
|
||||
}
|
||||
|
||||
/** The shape check for an identity read back from storage. */
|
||||
export function isIdentity(value: unknown): value is Identity {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return typeof v['publicKey'] === 'string' && PUBLIC_KEY.test(v['publicKey']) && typeof CryptoKey !== 'undefined' && v['privateKey'] instanceof CryptoKey;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user