Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/plugin/pkce-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,15 @@ describe('exchangeCodeForTokens - Issue #3', () => {
if (result.type !== 'failed') throw new Error('expected failed');
});
});

describe('generateCodeVerifier - Issue #10', () => {
it('produces a base64url string of the correct length (32 bytes => 43 chars)', async () => {
const mod = await import('./pkce-flow');
const verifier = mod.generateCodeVerifier();

expect(typeof verifier).toBe('string');
expect(verifier.length).toBe(43); // ceil(32 / 3) * 4 = 43 with base64url padding stripped
// base64url characters only
expect(verifier).toMatch(/^[A-Za-z0-9_-]+$/);
});
});
17 changes: 14 additions & 3 deletions src/plugin/pkce-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ async function executePkceAuthorization(
// Generate PKCE parameters
const codeVerifier = generateCodeVerifier();
const codeChallenge = generateCodeChallenge(codeVerifier);
const state = crypto.randomBytes(16).toString('hex');
const state = generateRandomHex(16);
const redirectUri = `http://localhost:${PKCE_CALLBACK_PORT}/callback`;

// Build authorization URL
Expand Down Expand Up @@ -279,11 +279,22 @@ function generateCodeChallenge(verifier: string): string {
return crypto.createHash('sha256').update(verifier).digest('base64url');
}

/**
* Generate a random hex string using Web Crypto (non-blocking, idiomatic in Node 18+)
*/
function generateRandomHex(byteLength: number): string {
const bytes = new Uint8Array(byteLength);
crypto.webcrypto.getRandomValues(bytes);
return Buffer.from(bytes).toString('hex');
}

/**
* Generate a random string for PKCE code_verifier
*/
function generateCodeVerifier(): string {
return crypto.randomBytes(32).toString('base64url');
export function generateCodeVerifier(): string {
const bytes = new Uint8Array(32);
crypto.webcrypto.getRandomValues(bytes);
return Buffer.from(bytes).toString('base64url');
}

/**
Expand Down
Loading