gcp-refresh-token
Version:
A cli util to retrieve a Google OAuth 2.0 refresh token
27 lines (26 loc) • 2.83 kB
JavaScript
import{createServer as p}from"http";import g from"open";var m=e=>`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Plasmo | GCP Refresh Token</title>
<link rel="icon" type="image/svg+xml" href="https://plasmo.com/favicon-light.svg" sizes="any"/>
<style>
main {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 90vh;
font-family: Inter, sans-serif;
text-align: center;
}
</style>
</head>
<body>
<main>
${e}
</main>
</body>
</html>
`,f=({port:e=3e3,authUrl:t="",redirectUri:r=""})=>new Promise((i,a)=>{let s=[];console.log("Looking for the code on port:",e);let n=p(async(o,c)=>{let l=new URL(o.url,r).searchParams.get("code");if(!l){let h=new Error("Code not found in callback \u{1F6D1} Close this tab and try again in the console");c.end(m(h.message)),n.close(),a(h);return}c.end(m(`Code retrieved \u{1F680} on port: ${e}. Please close this tab and return to the console.`)),n.close(),i(l)});n.on("connection",o=>{s.push(o)}),n.on("close",()=>{s.forEach(o=>o.destroy())}),n.listen(e,()=>{console.log(`Starting the auth flow, opening the browser to: ${t}`),g(t,{wait:!1}).then(o=>o.unref())})});import{OAuth2Client as u}from"google-auth-library";var N=async({port:e=0,clientId:t="",clientSecret:r="",redirectUri:i="",scope:a=[""]})=>{let s=new u({clientId:t,clientSecret:r,redirectUri:i}),n=s.generateAuthUrl({prompt:"consent",access_type:"offline",scope:a}),o=await f({port:e,authUrl:n,redirectUri:i});console.log("Code retrieved, redeeming for token...");let{tokens:c}=await s.getToken(o);return c.refresh_token};import{existsSync as y}from"fs";import{readFile as w,writeFile as k}from"fs/promises";import{resolve as _}from"path";import{cwd as x}from"process";var v={installed:{client_id:"",client_secret:"",project_id:"",auth_uri:"https://accounts.google.com/o/oauth2/auth",token_uri:"https://oauth2.googleapis.com/token",auth_provider_x509_cert_url:"https://www.googleapis.com/oauth2/v1/certs",redirect_uris:["http://localhost"]},scope:["https://www.googleapis.com/auth/chromewebstore"],chrome:{clientId:"",clientSecret:"",refreshToken:""}},P="key.json",C=()=>_(x(),P),U=async(e=!1)=>{let t=C();if(!y(t))if(e){let r={...v};throw delete r.chrome,await k(t,JSON.stringify(r,null,2)),new Error("No key.json found, a default key was created. Follow the readme for more info: https://github.com/PlasmoHQ/gcp-refresh-token")}else throw new Error("No key.json found.");return{key:JSON.parse(await w(t,"utf8")),keyFilePath:t}},d=["client_id","client_secret","redirect_uris"],q=e=>{if(d.some(t=>!e.installed[t]))throw new Error(`key.json is missing one or more of the required fields: ${d.join(", ")}`)};export{f as a,N as b,v as c,C as d,U as e,q as f};