Why PKCE is required
#Proof Key for Code Exchange (RFC 7636) binds the authorization code to the client that started the flow. Your app keeps a random code_verifier and sends only its SHA-256 hash (code_challenge). A stolen code cannot be exchanged without the verifier. OzVault requires S256 for public and confidential clients alike.
Generate the verifier and challenge
#The verifier must be 43-128 characters from A-Z, a-z, 0-9 and - . _ ~. 32 random bytes encoded as base64url give 43 characters. Store the verifier server-side (or in sessionStorage for browser-only apps) next to state, and delete it once used.
import { randomBytes, createHash } from "node:crypto";
// 32 random bytes -> 43-character base64url verifier (RFC 7636)
const codeVerifier = randomBytes(32).toString("base64url");
const codeChallenge = createHash("sha256").update(codeVerifier).digest("base64url");
const state = randomBytes(16).toString("base64url");function base64url(bytes) {
return btoa(String.fromCharCode(...new Uint8Array(bytes)))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
export async function createPkce() {
const codeVerifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier));
return { codeVerifier, codeChallenge: base64url(digest) };
}import base64, hashlib, secrets
code_verifier = secrets.token_urlsafe(32) # 43 characters
code_challenge = base64.urlsafe_b64encode(
hashlib.sha256(code_verifier.encode("ascii")).digest()
).rstrip(b"=").decode("ascii")
state = secrets.token_urlsafe(16)Send the verifier when exchanging the code
#Include code_verifier in the token request. A wrong verifier returns invalid_grant and permanently burns the code, so a guessed verifier gets exactly one attempt.
Clear documentation is part of the product.