-
Notifications
You must be signed in to change notification settings - Fork 4
/
pkce.ts
38 lines (34 loc) · 1.3 KB
/
pkce.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { encodeBase64url } from "./deps.ts";
/**
* A challenge method used for PKCE.
* Transforms a verifier into a challenge.
*/
export type ChallengeMethod = (verifier: string) => Promise<string>;
/** The allowed PKCE code challenge methods. */
export interface ChallengeMethods {
[key: string]: ChallengeMethod;
}
/**
* The default allowed PKCE code challenge methods.
* Clients SHOULD use PKCE code challenge methods that do not expose the
* PKCE verifier in the authorization request. Currently, "S256" is the only such method.
* https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#section-2.1.1
*/
export const challengeMethods: ChallengeMethods = {
S256: async (verifier: string) => {
const data = (new TextEncoder()).encode(verifier);
const buffer = await crypto.subtle.digest("SHA-256", data);
return encodeBase64url(new Uint8Array(buffer));
},
};
/**
* Generates a random code verifier with a minimum of 256 bits of entropy.
* This is done by generating a random 32-octet sequence then base64url encoding it
* to produce a 43 octet URL safe string.
* https://datatracker.ietf.org/doc/html/rfc7636#section-7.1
*/
export function generateCodeVerifier() {
const sequence = new Uint8Array(32);
crypto.getRandomValues(sequence);
return encodeBase64url(sequence);
}