diff --git a/src/index.ts b/src/index.ts index e33da29..5525ea6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -23,4 +23,53 @@ export default new OAuthProvider({ authorizeEndpoint: "/authorize", tokenEndpoint: "/token", clientRegistrationEndpoint: "/register", + accessTokenTTL: 1728000, // 20 days, + tokenExchangeCallback: async (options) => { + if (options.grantType === "refresh_token") { + if (options.grantType === "refresh_token") { + const { accessToken, instanceUrl } = options.props; + // fetch a new TS token + + const url = `${instanceUrl}/callosum/v1/v2/auth/token/fetch?validity_time_in_sec=2592000`; // 30 days + + const response = await fetch(url, { + method: "GET", + headers: { + Authorization: `Bearer ${accessToken}`, // old token (may still be valid) + Accept: "application/json", + "User-Agent": "ThoughtSpot-ts-client", + }, + }); + + if (!response.ok) { + + console.error("Failed to fetch new TS token:", await response.text()); + + // Don't issue new Cloudflare token — force user to reauth + throw new Error(JSON.stringify({ + error: "invalid_grant", + error_description: "TS access token expired. Please reauthenticate." + })); + } + + const data = await response.json(); + const newToken = data.data?.token; + + + return { + accessTokenProps: { + ...options.props, + accessToken: newToken, + }, + newProps: { + ...options.props, + accessToken: newToken, + }, + accessTokenTTL:1728000 // 20 days + }; + }; + } + // fallback to default behavior for other grant types + return; + }, }); diff --git a/src/thoughtspot/thoughtspot-client.ts b/src/thoughtspot/thoughtspot-client.ts index 8c5908a..dca5045 100644 --- a/src/thoughtspot/thoughtspot-client.ts +++ b/src/thoughtspot/thoughtspot-client.ts @@ -2,6 +2,9 @@ import { createBearerAuthenticationConfig, ThoughtSpotRestApi } from "@thoughtsp import YAML from "yaml"; export const getThoughtSpotClient = (instanceUrl: string, bearerToken: string) => { + if (!instanceUrl || !bearerToken) { + throw Error("instanceUrl and bearerToken are required to create a ThoughtSpot client"); + } const client = new ThoughtSpotRestApi(createBearerAuthenticationConfig( instanceUrl, () => Promise.resolve(bearerToken), @@ -82,6 +85,11 @@ async function addGetSessionInfo(client: any, instanceUrl: string, token: string "Authorization": `Bearer ${token}`, } }); + + if (response.status !== 200) { + console.log("response", response); + throw new Error(`Failed to get session info.`); + } const data: any = await response.json(); const info = data.info;