https://discord.gg/botpress logo
Anyone know how to get the bot to authenticated au...
# 🤝help
c
I have a successful connection to my Google Cloud Document AI endpoint if I give it a token myself. However I need to be able to refresh the token every hour (let's say every 50min). I have a json key but it requires the javascript crypto library in my action card. But crypto is not available in custom action cards. Like I can run an external service to handle that with it's own API key but that just seems redundant. I'm just wondering if there's a way to do that within botpress itself.
w
i think you can achieve that pretty easily using n8n
maybe even move the document extraction logic to n8n itself
it has pre-build nodes for that there, and also pre-build token signing nodes
i used them to sign JWT tokens for botpress's chat-api endpoint
@cool-action-13068 actually you can just ditch the crypto import and use the web crypto api instead
Copy code
javascript

const SECRET_KEY = 'your-secret-key-here';
const ALGORITHM = 'HS256';

const payload = {
  documentUrl: event.payload.fileUrl,
  timestamp: Date.now(),
  exp: Math.floor(Date.now() / 1000) + 3600, // expires in 1 hour
  iat: Math.floor(Date.now() / 1000)
};

const header = {
  alg: ALGORITHM,
  typ: 'JWT'
};


function base64UrlEncode(str) {
  const base64 = btoa(str);
  return base64
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '');
}

function str2ab(str) {
  const buf = new ArrayBuffer(str.length);
  const bufView = new Uint8Array(buf);
  for (let i = 0; i < str.length; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

function ab2base64(buffer) {
  const binary = String.fromCharCode(...new Uint8Array(buffer));
  return btoa(binary);
}

function getAlgorithm(alg) {
  const algMap = {
    'HS256': 'SHA-256',
    'HS384': 'SHA-384',
    'HS512': 'SHA-512'
  };
  return algMap[alg] || 'SHA-256';
}

async function signJWT() {
  try {

    const encodedHeader = base64UrlEncode(JSON.stringify(header));
    const encodedPayload = base64UrlEncode(JSON.stringify(payload));
    const signingInput = `${encodedHeader}.${encodedPayload}`;
    

    const keyData = str2ab(SECRET_KEY);
    const cryptoKey = await crypto.subtle.importKey(
      'raw',
      keyData,
      { name: 'HMAC', hash: getAlgorithm(ALGORITHM) },
      false,
      ['sign']
    );
    

    const signature = await crypto.subtle.sign(
      'HMAC',
      cryptoKey,
      str2ab(signingInput)
    );
    

    const encodedSignature = ab2base64(signature)
      .replace(/\+/g, '-')
      .replace(/\//g, '_')
      .replace(/=/g, '');
    

    const jwtToken = `${encodedHeader}.${encodedPayload}.${encodedSignature}`;
    

    workflow.jwtToken = jwtToken;
    workflow.tokenExpiry = payload.exp;
    workflow.tokenPayload = payload;
    
    console.log('JWT token generated successfully');
    
  } catch (error) {
    console.error('Error generating JWT token:', error);
    workflow.jwtToken = null;
    workflow.error = error.message;
  }
}

await signJWT();
here u go
i set it to expire in 1 hour and set the payload to be "event.payload.fileUrl" which is where the link from the user's file is stored
make sure to change the secret
the token is accessible through workflow.jwtToken afterwards
heres a screenshot of a token generated by that code being validated
c
is this done in botpress or another environment ?
w
botpress
just paste that into a custom code block
w
yea
c
neat
w
did it work?
c
looking into it rn
Copy code
json
{
  "type": "service_account",
  "project_id": "PROJECT_ID_HERE",
  "private_key_id": "PRIVATE_KEY_ID_HERE",
  "private_key": "PRIVATE_KEY_HERE",
  "client_email": "CLIENT_EMAIL_HERE",
  "client_id": "CLIENT_ID_HERE",
  "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",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/CLIENT_EMAIL_HERE",
  "universe_domain": "googleapis.com"
}
Cause this is what I have and I need to encode the private key (SHA256) with the client_email. https://developers.google.com/identity/protocols/oauth2/service-account#httprest
w
well you can just paste that into the payload
i think
with the variables filled of course
c
yeah obviously :D
just noting things as I go rn
kid => private_key_id
Also so I understand :
Copy code
ts
  const keyData = str2ab(SECRET_KEY)
SECRET_KEY refers to the actual SHA256 private key I have that's needed to sign the jwt, correct ?
w
yes
this one
w
in my screenshot it's "your-secret-key-here"
no not that
secret key is basically the password for the encryption
it can be any word or anything really
dude you should really consider moving this portion to n8n
c
so I need to filter out the key start and key end parts
w
if all you're doing is transcribing files
i'm not kidding it's gonna take 2 minutes
botpress is really not meant for this and it could have negative consequences
well it depends
do you set the secret key yourself in google?
or do they give you one
c
they give one
w
and they call it private key?
c
well it's a SHA256 asymetric key an api key doesn't work unless it's a public endpoint
but I'm using a private endpoint
w
SHA256 is the encryption method
the secret-key is what you give SHA256 so it encrypts in a specific way
but yeah i just read their documentation
and i guess they call the secret key a private key
it is that
c
yeah
I made this template script that works in node. Shouldn't be used as is and doesn't work directly in botpress cloud at least since crypto isn't usable there afaik. In my case I'll adapt it for use as a Supabase edge function for my bot to call as needed.