From 760a16d06493166b24dae28346ab5cdf0ab27537 Mon Sep 17 00:00:00 2001 From: finn Date: Thu, 16 Nov 2023 08:52:33 -0800 Subject: [PATCH] use secure random value for challenge --- src/pow.ts | 13 ++----------- tests/http-api.spec.ts | 8 ++++---- 2 files changed, 6 insertions(+), 15 deletions(-) diff --git a/src/pow.ts b/src/pow.ts index 64dbb91..648e869 100644 --- a/src/pow.ts +++ b/src/pow.ts @@ -1,4 +1,4 @@ -import { createHash } from 'crypto'; +import { createHash, randomBytes } from 'crypto'; import type { Request, Response } from 'express'; import type { Express } from 'express'; import type { Dialect } from 'kysely'; @@ -122,17 +122,8 @@ export class ProofOfWork { } } -const challengeCharacters = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; - function generateChallenge(): string { - let challenge = ''; - while (challenge.length < 10) { - challenge += challengeCharacters.charAt( - Math.floor(Math.random() * challengeCharacters.length), - ); - } - return challenge; + return randomBytes(10).toString('base64'); } interface AuthorizedTenants { diff --git a/tests/http-api.spec.ts b/tests/http-api.spec.ts index 9afab0e..cc43bce 100644 --- a/tests/http-api.spec.ts +++ b/tests/http-api.spec.ts @@ -72,7 +72,7 @@ describe('http api', function () { challenge: string; complexity: number; }; - expect(body.challenge.length).to.equal(10); + expect(body.challenge.length).to.equal(16); expect(body.complexity).to.equal(5); }); @@ -83,7 +83,7 @@ describe('http api', function () { challenge: string; complexity: number; }; - expect(body.challenge.length).to.equal(10); + expect(body.challenge.length).to.equal(16); expect(body.complexity).to.equal(5); // solve the challenge @@ -119,7 +119,7 @@ describe('http api', function () { challenge: string; complexity: number; }; - expect(body.challenge.length).to.equal(10); + expect(body.challenge.length).to.equal(16); // solve the challenge let response = ''; @@ -172,7 +172,7 @@ describe('http api', function () { challenge: string; complexity: number; }; - expect(body.challenge.length).to.equal(10); + expect(body.challenge.length).to.equal(16); // generate a nonce let response = generateNonce(5);