From 202959f5dda29e02f3593c7dd29b468d27bcaa23 Mon Sep 17 00:00:00 2001 From: David Dal Busco Date: Thu, 31 Jul 2025 16:40:52 +0200 Subject: [PATCH] feat: use crypto API for nonce --- src/services/login.services.ts | 5 +++-- src/utils/auth.utils.ts | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/services/login.services.ts b/src/services/login.services.ts index 93bcb773..d238a525 100644 --- a/src/services/login.services.ts +++ b/src/services/login.services.ts @@ -2,6 +2,7 @@ import {Ed25519KeyIdentity} from '@dfinity/identity'; import type {JsonnableEd25519KeyIdentity} from '@dfinity/identity/lib/cjs/identity/ed25519'; import {nextArg} from '@junobuild/cli-tools'; import {bold, green, underline} from 'kleur'; +import {randomBytes} from 'node:crypto'; import fs from 'node:fs'; import type http from 'node:http'; import {createServer} from 'node:http'; @@ -18,7 +19,7 @@ const __dirname = dirname(__filename); export const login = async (args?: string[]) => { const port = await getPort(); - const nonce = Math.floor(Math.random() * (2 << 29) + 1); + const nonce = randomBytes(16).toString('hex'); const key = Ed25519KeyIdentity.generate(); const principal = key.getPrincipal().toText(); @@ -37,7 +38,7 @@ export const login = async (args?: string[]) => { const orbiters = url.searchParams.get('orbiters'); const missionControl = url.searchParams.get('mission_control'); - if (returnedNonce !== `${nonce}`) { + if (returnedNonce !== nonce) { await respondWithFile(req, res, 400, '../templates/login/failure.html'); reject(new Error('Unexpected error while logging in.')); server.close(); diff --git a/src/utils/auth.utils.ts b/src/utils/auth.utils.ts index 39639203..6ac4ce2b 100644 --- a/src/utils/auth.utils.ts +++ b/src/utils/auth.utils.ts @@ -7,7 +7,7 @@ export const authUrl = ({ principal }: { port: number; - nonce: number; + nonce: string; principal: string; }): string => { const callbackUrl = authCallbackUrl({port, nonce}); @@ -24,9 +24,9 @@ export const requestUrl = ({port, reqUrl}: {port: number; reqUrl: string | undef return `${requestUrl}${reqUrl}`; }; -const authCallbackUrl = ({port, nonce}: {port: number; nonce: number}): string => { +const authCallbackUrl = ({port, nonce}: {port: number; nonce: string}): string => { const redirectUrl = new URL(REDIRECT_URL.replace('{port}', `${port}`)); - redirectUrl.searchParams.set('state', `${nonce}`); + redirectUrl.searchParams.set('state', nonce); return redirectUrl.toString(); };