import type { PreKeyBundle, OneTimePreKey, CryptoProvider } from '@shade/core'; import { fromBase64, NetworkError } from '@shade/core'; /** * HTTP transport client for the Shade Prekey Server. * * Signing: write operations (register, replenish, delete) are signed with * the caller's Ed25519 identity signing key. The caller must provide a * signing function via the constructor. * * Usage: * ```ts * const transport = new ShadeFetchTransport({ * baseUrl: 'https://shade.example.com', * crypto, * signingKey: identity.signingPrivateKey, * }); * await transport.register('alice', identity, signedPreKey, oneTimePreKeys); * const bundle = await transport.fetchBundle('bob'); // anonymous * ``` */ export class ShadeFetchTransport { private readonly baseUrl: string; private readonly crypto: CryptoProvider; private readonly signingPrivateKey?: Uint8Array; constructor(options: { baseUrl: string; crypto: CryptoProvider; signingPrivateKey?: Uint8Array }) { this.baseUrl = options.baseUrl; this.crypto = options.crypto; this.signingPrivateKey = options.signingPrivateKey; } private headers(): Record { return { 'Content-Type': 'application/json' }; } /** Sign a payload using the configured signing key */ private async sign>(payload: T): Promise { if (!this.signingPrivateKey) { throw new Error('ShadeFetchTransport: signingPrivateKey is required for write operations'); } const signedAt = Date.now(); const withTs = { ...payload, signedAt, signature: '' }; // Canonicalize: sort keys, omit signature const { signature, ...rest } = withTs; const sorted = Object.keys(rest).sort().reduce>((acc, k) => { acc[k] = (rest as Record)[k]; return acc; }, {}); const bytes = new TextEncoder().encode(JSON.stringify(sorted)); const sig = await this.crypto.sign(this.signingPrivateKey, bytes); return { ...payload, signedAt, signature: Buffer.from(sig).toString('base64') }; } /** Register identity and upload prekey bundle + one-time prekeys */ async register( address: string, identity: { signingKey: Uint8Array; dhKey: Uint8Array }, signedPreKey: { keyId: number; publicKey: Uint8Array; signature: Uint8Array }, oneTimePreKeys?: OneTimePreKey[], ): Promise { const body: any = { address, identitySigningKey: toB64(identity.signingKey), identityDHKey: toB64(identity.dhKey), signedPreKey: { keyId: signedPreKey.keyId, publicKey: toB64(signedPreKey.publicKey), signature: toB64(signedPreKey.signature), }, }; if (oneTimePreKeys?.length) { body.oneTimePreKeys = oneTimePreKeys.map((k) => ({ keyId: k.keyId, publicKey: toB64(k.keyPair.publicKey), })); } const signed = await this.sign(body); const res = await fetch(`${this.baseUrl}/v1/keys/register`, { method: 'POST', headers: this.headers(), body: JSON.stringify(signed), }); if (!res.ok) throw new NetworkError(`Register failed: ${res.status}`, res.status); } /** Fetch a prekey bundle for a peer (anonymous, consumes one one-time prekey) */ async fetchBundle(address: string): Promise { const res = await fetch(`${this.baseUrl}/v1/keys/bundle/${encodeURIComponent(address)}`, { headers: this.headers(), }); if (!res.ok) throw new NetworkError(`Fetch bundle failed: ${res.status}`, res.status); const data = await res.json(); return { registrationId: data.registrationId ?? 0, identitySigningKey: fromB64(data.identitySigningKey), identityDHKey: fromB64(data.identityDHKey), signedPreKey: { keyId: data.signedPreKey.keyId, publicKey: fromB64(data.signedPreKey.publicKey), signature: fromB64(data.signedPreKey.signature), }, oneTimePreKey: data.oneTimePreKey ? { keyId: data.oneTimePreKey.keyId, publicKey: fromB64(data.oneTimePreKey.publicKey), } : undefined, }; } /** Upload additional one-time prekeys (signed) */ async replenish( address: string, keys: Array<{ keyId: number; publicKey: Uint8Array }>, ): Promise { const body = { address, oneTimePreKeys: keys.map((k) => ({ keyId: k.keyId, publicKey: toB64(k.publicKey), })), }; const signed = await this.sign(body); const res = await fetch(`${this.baseUrl}/v1/keys/replenish`, { method: 'POST', headers: this.headers(), body: JSON.stringify(signed), }); if (!res.ok) throw new NetworkError(`Replenish failed: ${res.status}`, res.status); const data = await res.json(); return data.remaining; } /** Get remaining one-time prekey count (anonymous) */ async getKeyCount(address: string): Promise { const res = await fetch(`${this.baseUrl}/v1/keys/count/${encodeURIComponent(address)}`, { headers: this.headers(), }); if (!res.ok) throw new NetworkError(`Count failed: ${res.status}`, res.status); const data = await res.json(); return data.count; } /** Delete all keys for this identity (signed) */ async unregister(address: string): Promise { const signed = await this.sign({ address }); const res = await fetch(`${this.baseUrl}/v1/keys/${encodeURIComponent(address)}`, { method: 'DELETE', headers: this.headers(), body: JSON.stringify(signed), }); if (!res.ok) throw new NetworkError(`Unregister failed: ${res.status}`, res.status); } } function toB64(bytes: Uint8Array): string { return Buffer.from(bytes).toString('base64'); } function fromB64(str: string): Uint8Array { return new Uint8Array(Buffer.from(str, 'base64')); }