/** PKCE + state/nonce helpers (CSPRNG). */
import { randomBytes, createHash } from 'node:crypto'
import { encodeBase64UrlBytes } from 'relay-contracts'

/** A random base64url token for `state`/`nonce`/`code_verifier`. */
export function randomUrlToken(bytes = 32): string {
  return encodeBase64UrlBytes(new Uint8Array(randomBytes(bytes)))
}

/** S256 code challenge = base64url(SHA-256(code_verifier)). */
export function pkceChallenge(codeVerifier: string): string {
  const digest = createHash('sha256').update(codeVerifier).digest()
  return encodeBase64UrlBytes(new Uint8Array(digest))
}
