|
| 1 | +import { type H3Event, setCookie, getCookie, getQuery, createError } from 'h3' |
| 2 | +import { subtle, getRandomValues } from 'uncrypto' |
| 3 | +import { useRuntimeConfig } from '#imports' |
| 4 | + |
| 5 | +export type OAuthChecks = 'pkce' | 'state' |
| 6 | + |
| 7 | +// From oauth4webapi https://github.com/panva/oauth4webapi/blob/4b46a7b4a4ca77a513774c94b718592fe3ad576f/src/index.ts#L567C1-L579C2 |
| 8 | +const CHUNK_SIZE = 0x8000 |
| 9 | +export function encodeBase64Url(input: Uint8Array | ArrayBuffer) { |
| 10 | + if (input instanceof ArrayBuffer) { |
| 11 | + input = new Uint8Array(input) |
| 12 | + } |
| 13 | + |
| 14 | + const arr = [] |
| 15 | + for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) { |
| 16 | + arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE))) |
| 17 | + } |
| 18 | + return btoa(arr.join('')).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') |
| 19 | +} |
| 20 | + |
| 21 | +function randomBytes() { |
| 22 | + return encodeBase64Url(getRandomValues(new Uint8Array(32))) |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Generate a random `code_verifier` for use in the PKCE flow |
| 27 | + * @see https://tools.ietf.org/html/rfc7636#section-4.1 |
| 28 | + */ |
| 29 | +export function generateCodeVerifier() { |
| 30 | + return randomBytes() |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Generate a random `state` used to prevent CSRF attacks |
| 35 | + * @see https://www.rfc-editor.org/rfc/rfc6749.html#section-4.1.1 |
| 36 | + */ |
| 37 | +export function generateState() { |
| 38 | + return randomBytes() |
| 39 | +} |
| 40 | + |
| 41 | +/** |
| 42 | + * Generate a `code_challenge` from a `code_verifier` for use in the PKCE flow |
| 43 | + * @param verifier `code_verifier` string |
| 44 | + * @returns `code_challenge` string |
| 45 | + * @see https://tools.ietf.org/html/rfc7636#section-4.1 |
| 46 | + */ |
| 47 | +export async function pkceCodeChallenge(verifier: string) { |
| 48 | + return encodeBase64Url(await subtle.digest({ name: 'SHA-256' }, new TextEncoder().encode(verifier))) |
| 49 | +} |
| 50 | + |
| 51 | +interface CheckUseResult { |
| 52 | + code_verifier?: string |
| 53 | +} |
| 54 | +/** |
| 55 | + * Checks for PKCE and state |
| 56 | + */ |
| 57 | +export const checks = { |
| 58 | + /** |
| 59 | + * Create checks |
| 60 | + * @param event H3Event |
| 61 | + * @param checks OAuthChecks[] a list of checks to create |
| 62 | + * @returns Record<string, string> a map of check parameters to add to the authorization URL |
| 63 | + */ |
| 64 | + async create(event: H3Event, checks?: OAuthChecks[]) { |
| 65 | + const res: Record<string, string> = {} |
| 66 | + const runtimeConfig = useRuntimeConfig() |
| 67 | + if (checks?.includes('pkce')) { |
| 68 | + const pkceVerifier = generateCodeVerifier() |
| 69 | + const pkceChallenge = await pkceCodeChallenge(pkceVerifier) |
| 70 | + res['code_challenge'] = pkceChallenge |
| 71 | + res['code_challenge_method'] = 'S256' |
| 72 | + setCookie(event, 'nuxt-auth-util-verifier', pkceVerifier, runtimeConfig.nuxtAuthUtils.security.cookie) |
| 73 | + } |
| 74 | + if (checks?.includes('state')) { |
| 75 | + res['state'] = generateState() |
| 76 | + setCookie(event, 'nuxt-auth-util-state', res['state'], runtimeConfig.nuxtAuthUtils.security.cookie) |
| 77 | + } |
| 78 | + return res |
| 79 | + }, |
| 80 | + /** |
| 81 | + * Use checks, verifying and returning the results |
| 82 | + * @param event H3Event |
| 83 | + * @param checks OAuthChecks[] a list of checks to use |
| 84 | + * @returns CheckUseResult a map that can contain `code_verifier` if `pkce` was used to be used in the token exchange |
| 85 | + */ |
| 86 | + async use(event: H3Event, checks?: OAuthChecks[]): Promise<CheckUseResult> { |
| 87 | + const res: CheckUseResult = {} |
| 88 | + const { state } = getQuery(event) |
| 89 | + if (checks?.includes('pkce')) { |
| 90 | + const pkceVerifier = getCookie(event, 'nuxt-auth-util-verifier') |
| 91 | + setCookie(event, 'nuxt-auth-util-verifier', '', { maxAge: -1 }) |
| 92 | + res['code_verifier'] = pkceVerifier |
| 93 | + } |
| 94 | + if (checks?.includes('state')) { |
| 95 | + const stateInCookie = getCookie(event, 'nuxt-auth-util-state') |
| 96 | + setCookie(event, 'nuxt-auth-util-state', '', { maxAge: -1 }) |
| 97 | + if (checks?.includes('state')) { |
| 98 | + if (!state || !stateInCookie) { |
| 99 | + const error = createError({ |
| 100 | + statusCode: 401, |
| 101 | + message: 'Login failed: state is missing', |
| 102 | + }) |
| 103 | + throw error |
| 104 | + } |
| 105 | + if (state !== stateInCookie) { |
| 106 | + const error = createError({ |
| 107 | + statusCode: 401, |
| 108 | + message: 'Login failed: state does not match', |
| 109 | + }) |
| 110 | + throw error |
| 111 | + } |
| 112 | + } |
| 113 | + } |
| 114 | + return res |
| 115 | + }, |
| 116 | +} |
0 commit comments