import crypto from "node:crypto";
import { browserAuth } from "./server.js";
import { saveAuthState } from "./tokens.js";
export const AUTH_SERVER_PORT = 57801;
export const CLIENT_ID = "mYLGcH7kB4P0pw0HAk6GH7raRwYhSlW4";
export const CALLBACK_URL = `http://localhost:${AUTH_SERVER_PORT}/`;
export const AUTH0_DOMAIN = "auth.zuplo.com";
export const OAUTH_SCOPE = "openid email offline_access";
export const OAUTH_AUDIENCE = "https://dev.zuplo.com/";
export const encode = (value) => btoa(value);
export const decode = (value) => atob(value);
export const createRandomString = () => {
    const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";
    let random = "";
    const randomValues = Array.from(crypto.getRandomValues(new Uint8Array(43)));
    randomValues.forEach((v) => (random += charset[v % charset.length]));
    return random;
};
const urlEncodeB64 = (input) => {
    const b64Chars = { "+": "-", "/": "_", "=": "" };
    return input.replace(/[+/=]/g, (m) => b64Chars[m]);
};
export const bufferToBase64UrlEncoded = (input) => {
    const ie11SafeInput = new Uint8Array(input);
    return urlEncodeB64(btoa(String.fromCharCode(...Array.from(ie11SafeInput))));
};
export const sha256 = async (s) => {
    const digestOp = crypto.subtle.digest({ name: "SHA-256" }, new TextEncoder().encode(s));
    return await digestOp;
};
export async function login() {
    const code_verifier = createRandomString();
    const code_challengeBuffer = await sha256(code_verifier);
    const code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);
    const authUrl = new URL(`https://${AUTH0_DOMAIN}/authorize`);
    authUrl.searchParams.set("response_type", "code");
    authUrl.searchParams.set("code_challenge", code_challenge);
    authUrl.searchParams.set("code_challenge_method", "S256");
    authUrl.searchParams.set("client_id", CLIENT_ID);
    authUrl.searchParams.set("redirect_uri", CALLBACK_URL);
    authUrl.searchParams.set("scope", OAUTH_SCOPE);
    authUrl.searchParams.set("audience", OAUTH_AUDIENCE);
    const params = await browserAuth(authUrl.toString());
    const code = params.get("code");
    if (code === null) {
        throw new Error("No code");
    }
    const tokenParams = new URLSearchParams();
    tokenParams.set("grant_type", "authorization_code");
    tokenParams.set("client_id", CLIENT_ID);
    tokenParams.set("code_verifier", code_verifier);
    tokenParams.set("code", code);
    tokenParams.set("redirect_uri", CALLBACK_URL);
    const response = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        body: tokenParams,
    });
    const result = await response.json();
    await saveAuthState(result);
}
//# sourceMappingURL=login.js.map