All files / Rindu/utils getSpotifyLoginURL.ts

9.52% Statements 2/21
0% Branches 0/2
0% Functions 0/3
9.52% Lines 2/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                  45x                                                                   4x                                            
import {
  API_AUTH_URL,
  clientId,
  CODE_VERIFIER_COOKIE,
  enablePkceAuth,
  makeCookie,
  redirectUrl,
  SCOPES,
  SPOTIFY_AUTH_LOGIN_RESPONSE_TYPE,
} from "utils";
 
async function getPKCEParams() {
  const possible =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const randomValues = crypto.getRandomValues(new Uint8Array(64));
  const randomString = randomValues.reduce(
    (acc, x) => acc + possible[x % possible.length],
    ""
  );
 
  const code_verifier = randomString;
  const data = new TextEncoder().encode(code_verifier);
  const hashed = await crypto.subtle.digest("SHA-256", data);
 
  const code_challenge_base64 = btoa(
    String.fromCharCode(...new Uint8Array(hashed))
  )
    .replace(/=/g, "")
    .replace(/\+/g, "-")
    .replace(/\//g, "_");
 
  makeCookie({
    name: CODE_VERIFIER_COOKIE,
    value: code_verifier,
    age: 60 * 20,
  });
 
  return {
    code_challenge_method: "S256",
    code_challenge: code_challenge_base64,
  };
}
 
export async function getSpotifyLoginURL(): Promise<string> {
  Iif (!clientId) {
    throw new Error("Missing client Id");
  }
  const params = {
    response_type: SPOTIFY_AUTH_LOGIN_RESPONSE_TYPE,
    client_id: clientId,
    scope: SCOPES.join(","),
    redirect_uri: redirectUrl,
  };
 
  Iif (enablePkceAuth) {
    const PKCEParams = await getPKCEParams();
 
    Object.assign(params, PKCEParams);
  }
 
  const authUrl = new URL(API_AUTH_URL);
 
  authUrl.search = new URLSearchParams(params).toString();
  return authUrl.toString();
}