Added auth and request storage
This commit is contained in:
@@ -1,7 +1,11 @@
|
||||
import type { RouteDefinition, RouteModule } from '../routes/types.ts';
|
||||
import { ApplicationError } from '../errors/index.ts';
|
||||
import { z } from 'zod';
|
||||
import { toExtendedJson } from '@xo-cash/utils';
|
||||
|
||||
import type { RequestHeaders, RouteDefinition, RouteModule } from '../routes/types.ts';
|
||||
import { ApplicationError, UnauthorizedError } from '../errors/index.ts';
|
||||
import { ApplicationRouteStream } from './route-stream.ts';
|
||||
import type { BaseStream } from './stream/base-stream.ts';
|
||||
import type { AuthSecp256k1 } from '../auth/auth.ts';
|
||||
|
||||
/** Canonical request produced by every transport adapter. */
|
||||
export type ApplicationRequest = {
|
||||
@@ -12,14 +16,32 @@ export type ApplicationRequest = {
|
||||
/** Transport-decoded application payload. */
|
||||
body?: unknown;
|
||||
|
||||
/** Transport-normalized request headers, keyed by lowercase name. */
|
||||
headers?: RequestHeaders;
|
||||
|
||||
/** Optional correlation ID supplied by a multiplexed transport. */
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
export type ApplicationRouterDependencies = {
|
||||
/** Authentication service. */
|
||||
auth: AuthSecp256k1;
|
||||
};
|
||||
|
||||
const accountSchema = z.object({
|
||||
'x-public-key': z.string(),
|
||||
'x-signature': z.string(),
|
||||
'x-timestamp': z.coerce.number(),
|
||||
}).transform((data) => ({
|
||||
publicKey: data['x-public-key'],
|
||||
signature: data['x-signature'],
|
||||
timestamp: data['x-timestamp'],
|
||||
}));
|
||||
|
||||
/** Exact-match application routing shared by every wire transport. */
|
||||
export class ApplicationRouter {
|
||||
/** @param routes - Validated route table keyed by exact path. */
|
||||
private constructor(private readonly routes: ReadonlyMap<string, RouteDefinition>) {}
|
||||
private constructor(private readonly deps: ApplicationRouterDependencies, private readonly routes: ReadonlyMap<string, RouteDefinition>) {}
|
||||
|
||||
/**
|
||||
* Load and validate the complete route table before accepting traffic.
|
||||
@@ -27,7 +49,7 @@ export class ApplicationRouter {
|
||||
* @param routeModules - Route modules whose handlers will be registered.
|
||||
* @returns A ready-to-dispatch router instance.
|
||||
*/
|
||||
static async create(routeModules: RouteModule[]): Promise<ApplicationRouter> {
|
||||
static async create(deps: ApplicationRouterDependencies, routeModules: RouteModule[]): Promise<ApplicationRouter> {
|
||||
const routes = new Map<string, RouteDefinition>();
|
||||
|
||||
// Collect routes from every module and reject duplicates at startup.
|
||||
@@ -42,7 +64,7 @@ export class ApplicationRouter {
|
||||
}
|
||||
}
|
||||
|
||||
return new ApplicationRouter(routes);
|
||||
return new ApplicationRouter(deps, routes);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,12 +74,36 @@ export class ApplicationRouter {
|
||||
* @param connection - Shared connection stream for this transport session.
|
||||
*/
|
||||
async dispatch(request: ApplicationRequest, connection: BaseStream): Promise<void> {
|
||||
const { publicKey, signature, timestamp } = accountSchema.parse(request.headers);
|
||||
// Authenticate the headers on the request. (TODO: Remove the defaults, just here for testing)
|
||||
// const publicKey = request.headers?.['x-public-key'] || 'public-key';
|
||||
// const signature = request.headers?.['x-signature'] || 'signature';
|
||||
// const timestamp = request.headers?.['x-timestamp'] || Date.now();
|
||||
|
||||
// Make sure the request signature is valid and hasnt been used before
|
||||
await this.deps.auth.verifyUniqueRequest(signature);
|
||||
|
||||
// Ensure that the headers are present.
|
||||
if (!publicKey || !signature || !timestamp) {
|
||||
throw new UnauthorizedError('Missing authentication headers');
|
||||
}
|
||||
|
||||
// Compile the signature payload as `Path:Timestamp:Body`
|
||||
const signaturePayload = `${timestamp}:${request.path}:${toExtendedJson(request.body)}`;
|
||||
|
||||
// Verify the signature of the request.
|
||||
const verified = await this.deps.auth.verifySignature(publicKey, signature, signaturePayload);
|
||||
if (!verified) {
|
||||
throw new UnauthorizedError('Invalid signature');
|
||||
}
|
||||
|
||||
// Get the route from the routes map.
|
||||
const route = this.routes.get(request.path);
|
||||
if (!route) {
|
||||
throw new ApplicationError(404, `No route found for ${request.path}`);
|
||||
}
|
||||
|
||||
const stream = new ApplicationRouteStream(connection, request.body, request.requestId);
|
||||
const stream = new ApplicationRouteStream(connection, request.body, request.path, request.requestId, request.headers);
|
||||
await route.handler(stream);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user