Update Utils version. Add abstract Client class. Code Cleanup

This commit is contained in:
2026-08-12 05:16:16 +00:00
parent d42efd0f56
commit 55d09d048e
7 changed files with 265 additions and 252 deletions
+15 -91
View File
@@ -1,20 +1,14 @@
import { SSESession, toExtendedJson } from '@xo-cash/utils';
import { PrivateKey } from '@xo-cash/primitives'
import { binToHex, flattenBinArray, secp256k1, sha256 } from '@bitauth/libauth'
import type { WriteRequest } from '../types.js';
export type AuthenticatedRequestHeaders = {
'X-Public-Key': string;
'X-Timestamp': string;
'X-Signature': string;
};
import { SyncClient } from '../shared/client.js';
export type SSEClientOptions = {
onMessage: (message: string) => void;
onError: (error: Error) => void;
};
export class SSEClient {
export class SSEClient extends SyncClient {
private sseSession: SSESession;
private readonly subscriptions: Set<string> = new Set();
private readonly messageListeners = new Set<(message: string) => void>();
@@ -28,6 +22,8 @@ export class SSEClient {
}
constructor(private readonly url: string, privateKey: PrivateKey, options: Partial<SSEClientOptions> = {}) {
super();
this.privateKey = privateKey;
this.sseSession = new SSESession(`${this.url}/data/subscribe`, {
method: 'POST',
@@ -59,7 +55,13 @@ export class SSEClient {
onRequest: async (request) => {
// Create the request authentication headers
const requestBody = toExtendedJson(request.body);
const authHeaders = SSEClient.authenticateRequest(this.privateKey, requestBody);
// Get the path from the URL
const url = new URL(this.url);
const path = url.pathname;
// Sign the request body
const authHeaders = SyncClient.signRequest(this.privateKey.toBytes(), path, requestBody);
// Initialize the request headers if they don't exist
request.headers ??= {};
@@ -83,7 +85,7 @@ export class SSEClient {
// Create a listener to re-emit the messages
this.sseSession.on('message', (message) => {
for (const listener of this.messageListeners) {
listener(message);
listener(message.data);
}
});
@@ -104,7 +106,7 @@ export class SSEClient {
const valueStr = toExtendedJson(value);
const valueBytes = this.textEncoder.encode(valueStr);
const resource = SSEClient.makeWriteRequest(this.privateKey, resourceId, valueBytes);
const resource = SyncClient.signWriteRequest(this.privateKey.toBytes(), resourceId, valueBytes);
const bodyStr = toExtendedJson({ resources: [resource] });
@@ -121,7 +123,8 @@ export class SSEClient {
});
if (!res.ok) {
throw new Error(`Failed to write resource: ${res.statusText}`);
const error = await res.json();
throw new Error(`Failed to write resource [${resourceId}] (${res.statusText}): ${JSON.stringify(error)}`);
}
return res.json();
@@ -161,83 +164,4 @@ export class SSEClient {
await this.reconnect();
}
/**
* Derives a resource-scoped private key from the root key and resource id.
*/
private static deriveResourcePrivateKey(privateKey: Uint8Array, resourceId: string): Uint8Array {
const resourceIdBytes = new TextEncoder().encode(resourceId);
return sha256.hash(flattenBinArray([ privateKey, resourceIdBytes ]));
}
/**
* Signs a canonical payload string and returns the compressed public key and DER signature.
*/
private static signPayload(
privateKey: Uint8Array,
payload: string,
): { publicKey: string; signature: string } {
const payloadHash = sha256.hash(new TextEncoder().encode(payload));
const publicKey = secp256k1.derivePublicKeyCompressed(privateKey);
if (typeof publicKey === 'string') {
throw new Error('Failed to derive public key');
}
const signature = secp256k1.signMessageHashDER(privateKey, payloadHash);
if (typeof signature === 'string') {
throw new Error('Failed to sign message');
}
return {
publicKey: binToHex(publicKey),
signature: binToHex(signature),
};
}
/**
* Builds a signed write resource for POST /data/write.
*
* The signing key is derived per resource via sha256(privateKey + resourceId).
* The signature covers only the resource value, not the full request body.
*/
static makeWriteRequest(
privateKey: PrivateKey,
resourceId: string,
value: Uint8Array,
): WriteRequest {
const derivedKey = SSEClient.deriveResourcePrivateKey(privateKey.toBytes(), resourceId);
const timestamp = Date.now();
const payload = `${timestamp}${resourceId}${toExtendedJson(value)}`;
const { publicKey, signature } = SSEClient.signPayload(derivedKey, payload);
return {
id: resourceId,
value,
publicKey,
timestamp,
signature,
};
}
/**
* Signs an entire request body for transport-layer authentication headers.
*
* Unlike {@link makeWriteRequest}, this uses the root private key and signs
* the full serialized body rather than an individual resource value.
*/
static authenticateRequest(
privateKey: PrivateKey,
body: string,
): AuthenticatedRequestHeaders {
const timestamp = Date.now();
const payload = `${timestamp}${body}`;
const { publicKey, signature } = SSEClient.signPayload(privateKey.toBytes(), payload);
return {
'X-Public-Key': publicKey,
'X-Timestamp': timestamp.toString(),
'X-Signature': signature,
};
}
}