← back to Gmc Titlefix

_auth.js

13 lines

// Shared: mint a Merchant/Content API access token from the GMC service account.
const crypto=require('crypto'),fs=require('fs');
const SA=JSON.parse(fs.readFileSync(process.env.HOME+'/Projects/secrets-manager/gmc-sa-146735262.json','utf8'));
const b64=b=>Buffer.from(b).toString('base64').replace(/=/g,'').replace(/\+/g,'-').replace(/\//g,'_');
async function token(){
  const now=Math.floor(Date.now()/1000);
  const si=b64(JSON.stringify({alg:'RS256',typ:'JWT'}))+'.'+b64(JSON.stringify({iss:SA.client_email,scope:'https://www.googleapis.com/auth/content',aud:'https://oauth2.googleapis.com/token',iat:now,exp:now+3600}));
  const s=crypto.createSign('RSA-SHA256');s.update(si);const jwt=si+'.'+b64(s.sign(SA.private_key));
  const r=await fetch('https://oauth2.googleapis.com/token',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({grant_type:'urn:ietf:params:oauth:grant-type:jwt-bearer',assertion:jwt})});
  const j=await r.json(); if(!j.access_token) throw new Error('token fail: '+JSON.stringify(j)); return j.access_token;
}
module.exports={token, MERCHANT:'146735262'};