This commit is contained in:
2026-09-02 10:03:55 +00:00
8 changed files with 241 additions and 159 deletions
+98 -86
View File
@@ -1,110 +1,122 @@
import type { Database } from '../services/storage/database';
import type { Database } from '../services/storage/database.ts';
import { hexToBin, instantiateSecp256k1, type Secp256k1, sha256 } from '@bitauth/libauth';
import { UnauthorizedError } from '../errors/unauthorized-error';
import { UnauthorizedError } from '../errors/unauthorized-error.ts';
export type AuthSecp256k1RequiredDeps = {
database: Database;
}
database: Database;
};
export type AuthSecp256k1OptionalDeps = {
secp256k1: Secp256k1;
}
secp256k1: Secp256k1;
};
export type AuthSecp256k1Deps = AuthSecp256k1RequiredDeps & Partial<AuthSecp256k1OptionalDeps>;
export type AuthSecp256k1Options = {
timestampWindowMs: number;
}
timestampWindowMs: number;
};
export class AuthSecp256k1 {
/**
* Create a new instance of AuthSecp256k1
* @returns A new instance of AuthSecp256k1
*/
static async create(inputDeps: AuthSecp256k1Deps, options: AuthSecp256k1Options): Promise<AuthSecp256k1> {
const deps = {
secp256k1: await instantiateSecp256k1(),
...inputDeps,
/**
* Create a new instance of AuthSecp256k1
* @returns A new instance of AuthSecp256k1
*/
static async create(inputDeps: AuthSecp256k1Deps, options: AuthSecp256k1Options): Promise<AuthSecp256k1> {
const deps = {
secp256k1: await instantiateSecp256k1(),
...inputDeps,
};
return new AuthSecp256k1(deps, options);
}
return new AuthSecp256k1(deps, options);
}
/**
* TODO: Consider adding a Record<string, Mutex> where each key is the signature to guarantee signatures arent being processed concurrently.
*/
readonly #deps: Required<AuthSecp256k1Deps>;
readonly #options: AuthSecp256k1Options;
/**
* TODO: Consider adding a Record<string, Mutex> where each key is the signature to guarantee signatures arent being processed concurrently.
*/
/**
* @param deps - The dependencies to use
* @param options - The options to use
*/
private constructor(private readonly deps: Required<AuthSecp256k1Deps>, private readonly options: AuthSecp256k1Options) {}
/**
* Verify a signature
* @param publicKeyHex - The public key to verify the signature against
* @param signatureHex - The signature to verify
* @param payload - The payload to verify the signature against
* @returns Whether the signature is valid
*/
async verifySignature(publicKeyHex: string, signatureHex: string, payload: string): Promise<boolean> {
return true;
// Convert the public key and signature to binary
const publicKey = hexToBin(publicKeyHex);
const signature = hexToBin(signatureHex);
// Convert the payload to bytes and compute the sha256 hash
const payloadBytes = new TextEncoder().encode(payload);
const messageHash = sha256.hash(payloadBytes);
// Verify the signature
const verified = await this.deps.secp256k1.verifySignatureDERLowS(signature, publicKey, messageHash);
// If the signature is not valid, throw an unauthorized error
if (!verified) {
throw new UnauthorizedError('Invalid signature');
/**
* @param deps - The dependencies to use
* @param options - The options to use
*/
private constructor(deps: Required<AuthSecp256k1Deps>, options: AuthSecp256k1Options) {
this.#deps = deps;
this.#options = options;
}
// Return the verified signature
return verified;
}
/**
* Verify a signature
* @param publicKeyHex - The public key to verify the signature against
* @param signatureHex - The signature to verify
* @param payload - The payload to verify the signature against
* @returns Whether the signature is valid
*/
async verifySignature(publicKeyHex: string, signatureHex: string, payload: string): Promise<boolean> {
// Convert the public key and signature to binary
const publicKey = hexToBin(publicKeyHex);
const signature = hexToBin(signatureHex);
async verifyUniqueRequest(signature: string): Promise<boolean> {
if (!signature) {
throw new UnauthorizedError('Signature is required');
// Convert the payload to bytes and compute the sha256 hash
const payloadBytes = new TextEncoder().encode(payload);
const messageHash = sha256.hash(payloadBytes);
// Verify the signature
const verified = this.#deps.secp256k1.verifySignatureDERLowS(signature, publicKey, messageHash);
// If the signature is not valid, throw an unauthorized error
if (!verified) {
throw new UnauthorizedError('Invalid signature');
}
// Return the verified signature
return verified;
}
console.log('Verifying unique request', signature);
/**
* Verify a signature is unique and add it to the database if it is
*
* @param signature - The signature to verify
* @returns Whether the signature is unique
*/
async verifyUniqueRequest(signature: string): Promise<boolean> {
// If the signature is not provided, throw an unauthorized error
if (!signature) {
throw new UnauthorizedError('Signature is required');
}
// Check if the signature has been used before
const request = await this.deps.database.db.
selectFrom('authed_requests')
.selectAll()
.where('signature', '=', signature)
.executeTakeFirst();
if (request) {
throw new UnauthorizedError('Request already used');
// Check if the signature has been used before
const request = await this.#deps.database.db.selectFrom('authed_requests').selectAll()
.where('signature', '=', signature)
.executeTakeFirst();
// If the signature has been used before, throw an unauthorized error
if (request) {
throw new UnauthorizedError('Request already used');
}
// Add the signature to the requests table
await this.#deps.database.db.insertInto('authed_requests').values({ signature })
.execute();
// Return true if the signature is valid
return true;
}
// Add the signature to the requests table
await this.deps.database.db.insertInto('authed_requests').values({ signature }).execute();
/**
* Assert that a timestamp is within a allowed window
* @param timestamp - The timestamp to check
* @param windowMs - The window in milliseconds
*
* @throws An {@link UnauthorizedError} if the timestamp is outside the allowed window
*/
assertTimestampFreshness(timestamp: number, windowMs = this.#options.timestampWindowMs): void {
// Subtract the timestamp from the current time to get the age in milliseconds
const age = Math.abs(Date.now() - timestamp);
// Return true if the signature is valid
return true;
}
/**
* Assert that a timestamp is within a allowed window
* @param timestamp - The timestamp to check
* @param windowMs - The window in milliseconds
*
* @throws An {@link UnauthorizedError} if the timestamp is outside the allowed window
*/
assertTimestampFreshness(timestamp: number, windowMs = this.options.timestampWindowMs): void {
const age = Math.abs(Date.now() - timestamp);
if (age > windowMs) {
throw new UnauthorizedError('Timestamp outside allowed window');
// If the timestamp is outside the allowed window, throw an unauthorized error
if (age > windowMs) {
throw new UnauthorizedError('Timestamp outside allowed window');
}
}
}
}
}
+4 -1
View File
@@ -88,7 +88,10 @@ export class App {
startUniqueRequestCleanup(cleanupIntervalMs: number, timestampWindowMs: number): void {
// Every 10 seconds, we will cleanup the requests table
setInterval(async () => {
await this.database.db.deleteFrom('authed_requests').where('timestamp', '<', Date.now() - timestampWindowMs).execute();
await this.database.db
.deleteFrom('authed_requests')
.where('timestamp', '<', Date.now() - timestampWindowMs)
.execute();
}, cleanupIntervalMs);
}
}
+17 -14
View File
@@ -24,24 +24,30 @@ export type ApplicationRequest = {
};
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'],
}));
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 deps: ApplicationRouterDependencies, 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.
@@ -74,11 +80,8 @@ export class ApplicationRouter {
* @param connection - Shared connection stream for this transport session.
*/
async dispatch(request: ApplicationRequest, connection: BaseStream): Promise<void> {
// Authenticate the headers on the request.
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);
@@ -26,7 +26,7 @@ export const up = async (db: Kysely<DatabaseTables>): Promise<void> => {
.addColumn('signature', 'text', (col) => col.notNull())
.addPrimaryKeyConstraint('pk_resource_data', [ 'resource_id', 'public_key' ])
.execute();
// Table for authed requests
// We will store the signature and the timestamp of the request, and we will clear out rows that are older than our msTimeout for our auth
await db.schema
@@ -46,5 +46,7 @@ export const up = async (db: Kysely<DatabaseTables>): Promise<void> => {
export const down = async (db: Kysely<DatabaseTables>): Promise<void> => {
await db.schema.dropTable('resource_data').ifExists()
.execute();
await db.schema.dropTable('authed_requests').ifExists().execute();
await db.schema.dropTable('authed_requests').ifExists()
.execute();
};
+1 -23
View File
@@ -28,6 +28,7 @@ export interface ResourceDataTable {
}
export interface AuthedRequestsTable {
/** Signature of the request. */
signature: string;
@@ -35,29 +36,6 @@ export interface AuthedRequestsTable {
timestamp: Timestamp;
}
// export interface PaymentsTable {
// /** Unique identifier for the payment. */
// payment_id: string;
// /** Public key of the account in the transaction */
// public_key: string;
// /** Amount of the payment. This can be positive or negative.*/
// amount: number;
// /** Timestamp of the payment. */
// timestamp: Timestamp;
// /** Signature of the payment. */
// signature: string;
// /** Hash of the message that was signed. */
// message_hash: string;
// /** Resource ID of the payment. */
// resource_id: string;
// }
/** Complete Kysely schema mapping for the sync server database. */
export interface DatabaseTables {
resource_data: ResourceDataTable;