[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,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;
|
||||
}
|
||||
Reference in New Issue
Block a user