Update Utils version. Add abstract Client class. Code Cleanup
This commit is contained in:
+2
-3
@@ -3,7 +3,6 @@ import { PrivateKey } from "@xo-cash/primitives";
|
||||
import { SSEClient } from "./sse/client.js";
|
||||
import { WsClient } from './ws/client.js';
|
||||
|
||||
|
||||
const testSSE = async () => {
|
||||
const privateKey = PrivateKey.fromString('c440ce6ac5b63ae7bc4af9891b80b7a88ccdeebba5e43246885e9ec56f912ac2');
|
||||
const client = new SSEClient('https://v2.sync.xo.harvmaster.com', privateKey, {
|
||||
@@ -50,5 +49,5 @@ const testWS = async () => {
|
||||
// await client.disconnect();
|
||||
}
|
||||
|
||||
// testSSE();
|
||||
testWS();
|
||||
testSSE();
|
||||
// testWS();
|
||||
@@ -0,0 +1,117 @@
|
||||
import { binToHex, flattenBinArray, secp256k1, sha256 } from "@bitauth/libauth";
|
||||
|
||||
import { toExtendedJson } from "@xo-cash/utils";
|
||||
import type { WriteRequest } from "../types.js";
|
||||
|
||||
export type AuthenticatedRequestHeaders = {
|
||||
'X-Public-Key': string;
|
||||
'X-Timestamp': string;
|
||||
'X-Signature': string;
|
||||
};
|
||||
|
||||
export type SignedPayload = { publicKey: string; signature: string };
|
||||
|
||||
export abstract class SyncClient {
|
||||
|
||||
abstract connect(): Promise<void>;
|
||||
abstract disconnect(): Promise<void>;
|
||||
abstract write(resourceId: string, value: Record<string, unknown>): Promise<unknown>;
|
||||
abstract read(resourceId: string): Promise<unknown>;
|
||||
abstract subscribe(resourceId: string): Promise<void>;
|
||||
abstract unsubscribe(resourceId: string): Promise<unknown>;
|
||||
|
||||
/**
|
||||
* Derives the resource private key from the private key and resource ID
|
||||
* @param privateKey - The private key to derive the resource private key from
|
||||
* @param resourceId - The resource ID to derive the resource private key from
|
||||
* @returns The resource private key
|
||||
*/
|
||||
static deriveResourcePrivateKey(privateKey: Uint8Array, resourceId: string): Uint8Array {
|
||||
// Convert the resource ID to bytes
|
||||
const resourceIdBytes = new TextEncoder().encode(resourceId);
|
||||
|
||||
// Hash the private key and resource ID
|
||||
return sha256.hash(flattenBinArray([ privateKey, resourceIdBytes ]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs a payload with the private key and returns the public key and signature
|
||||
* @param privateKey - The private key to sign the payload with
|
||||
* @param payload - The payload to sign
|
||||
* @returns The public key and signature
|
||||
*/
|
||||
static signPayload(privateKey: Uint8Array, payload: string): SignedPayload {
|
||||
// Convert the payload to Binary and hash it
|
||||
const payloadHash = sha256.hash(new TextEncoder().encode(payload));
|
||||
|
||||
// Derive the public key
|
||||
const publicKey = secp256k1.derivePublicKeyCompressed(privateKey);
|
||||
|
||||
// If the public key is a string, throw an error
|
||||
if (typeof publicKey === 'string') {
|
||||
throw new Error('Failed to derive public key');
|
||||
}
|
||||
|
||||
// Sign the payload
|
||||
const signature = secp256k1.signMessageHashDER(privateKey, payloadHash);
|
||||
|
||||
// If the signature is a string, throw an error
|
||||
if (typeof signature === 'string') {
|
||||
throw new Error('Failed to sign message');
|
||||
}
|
||||
|
||||
return {
|
||||
publicKey: binToHex(publicKey),
|
||||
signature: binToHex(signature),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs a write request with the private key and returns the write request
|
||||
* @param privateKey - The private key to sign the write request with
|
||||
* @param resourceId - The resource ID to write to
|
||||
* @param value - The value to write
|
||||
* @returns The write request
|
||||
*/
|
||||
static signWriteRequest(privateKey: Uint8Array, resourceId: string, value: Uint8Array): WriteRequest {
|
||||
// Derive the resource private key
|
||||
const derivedKey = this.deriveResourcePrivateKey(privateKey, resourceId);
|
||||
|
||||
// Create the payload
|
||||
const timestamp = Date.now();
|
||||
const payload = `${timestamp}${resourceId}${toExtendedJson(value)}`;
|
||||
|
||||
// Sign the payload
|
||||
const { publicKey, signature } = this.signPayload(derivedKey, payload);
|
||||
|
||||
return {
|
||||
id: resourceId,
|
||||
value,
|
||||
publicKey,
|
||||
timestamp,
|
||||
signature,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs a request with the private key and returns the public key, timestamp, and signature
|
||||
* @param privateKey - The private key to sign the request with
|
||||
* @param path - The path of the request
|
||||
* @param body - The body of the request
|
||||
* @returns The public key, timestamp, and signature
|
||||
*/
|
||||
static signRequest(privateKey: Uint8Array, path: string, body: unknown): AuthenticatedRequestHeaders {
|
||||
// Create the payload
|
||||
const timestamp = Date.now();
|
||||
const payload = `${timestamp}:${path}:${toExtendedJson(body)}`;
|
||||
|
||||
// Sign the payload
|
||||
const { publicKey, signature } = this.signPayload(privateKey, payload);
|
||||
|
||||
return {
|
||||
'X-Public-Key': publicKey,
|
||||
'X-Timestamp': timestamp.toString(),
|
||||
'X-Signature': signature,
|
||||
};
|
||||
}
|
||||
}
|
||||
+15
-91
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+10
-8
@@ -1,14 +1,15 @@
|
||||
import { fromExtendedJson, toExtendedJson } from '@xo-cash/utils';
|
||||
import type { PrivateKey } from '@xo-cash/primitives';
|
||||
|
||||
import { SSEClient } from '../sse/client.js';
|
||||
import { WsMessageSchema, WsSuccessResponseSchema, WsErrorResponseSchema, type WsMessage } from './types.js';
|
||||
import { SyncClient } from '../shared/client.js';
|
||||
|
||||
/** A request sent over the sync server's WebSocket connection. */
|
||||
type WsRequest = {
|
||||
id?: string;
|
||||
path: string;
|
||||
body?: unknown;
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
|
||||
type PendingRequest = {
|
||||
@@ -38,7 +39,7 @@ export type WsClientOptions = {
|
||||
* resubscription, and request-timeout behavior. Those concerns are omitted
|
||||
* here to keep the transport demo easy to follow.
|
||||
*/
|
||||
export class WsClient {
|
||||
export class WsClient extends SyncClient {
|
||||
private socket: WebSocket | undefined;
|
||||
private readonly pendingRequests = new Map<string, PendingRequest>();
|
||||
private readonly messageListeners = new Set<(message: WsMessage) => void>();
|
||||
@@ -49,6 +50,8 @@ export class WsClient {
|
||||
private readonly privateKey: PrivateKey,
|
||||
options: Partial<WsClientOptions> = {},
|
||||
) {
|
||||
super();
|
||||
|
||||
this.messageListeners.add(options.onMessage ?? (() => {}));
|
||||
this.errorListeners.add(options.onError ?? (() => {}));
|
||||
}
|
||||
@@ -118,11 +121,7 @@ export class WsClient {
|
||||
*/
|
||||
async write(resourceId: string, value: Record<string, unknown>): Promise<unknown> {
|
||||
const valueBytes = new TextEncoder().encode(toExtendedJson(value));
|
||||
const resource = SSEClient.makeWriteRequest(
|
||||
this.privateKey,
|
||||
resourceId,
|
||||
valueBytes,
|
||||
);
|
||||
const resource = SyncClient.signWriteRequest(this.privateKey.toBytes(), resourceId, valueBytes);
|
||||
|
||||
return this.request('/data/write', { resources: [resource] });
|
||||
}
|
||||
@@ -154,8 +153,11 @@ export class WsClient {
|
||||
this.pendingRequests.set(id, { resolve, reject });
|
||||
});
|
||||
|
||||
// Sign the request body
|
||||
const headers = SyncClient.signRequest(this.privateKey.toBytes(), path, toExtendedJson(body));
|
||||
|
||||
try {
|
||||
this.send({ id, path, body });
|
||||
this.send({ id, path, body, headers });
|
||||
} catch (error) {
|
||||
// Avoid leaving a promise in the map when the socket was not open.
|
||||
this.pendingRequests.delete(id);
|
||||
|
||||
Reference in New Issue
Block a user