diff --git a/packages/identity/package.json b/packages/identity/package.json new file mode 100644 index 0000000..f087efc --- /dev/null +++ b/packages/identity/package.json @@ -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" + } +} diff --git a/packages/identity/src/index.ts b/packages/identity/src/index.ts new file mode 100644 index 0000000..9012c82 --- /dev/null +++ b/packages/identity/src/index.ts @@ -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 { + // 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; + return typeof v['publicKey'] === 'string' && PUBLIC_KEY.test(v['publicKey']) && typeof CryptoKey !== 'undefined' && v['privateKey'] instanceof CryptoKey; +} diff --git a/packages/identity/test/identity.test.ts b/packages/identity/test/identity.test.ts new file mode 100644 index 0000000..337e1a0 --- /dev/null +++ b/packages/identity/test/identity.test.ts @@ -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); + }); +}); diff --git a/packages/identity/tsconfig.json b/packages/identity/tsconfig.json new file mode 100644 index 0000000..2cbda19 --- /dev/null +++ b/packages/identity/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +}