UNPKG

kafka-ts

Version:

**KafkaTS** is a Apache Kafka client library for Node.js. It provides both a low-level API for communicating directly with the Apache Kafka cluster and high-level APIs for publishing and subscribing to Kafka topics.

57 lines (56 loc) 2.25 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.oAuthAuthenticator = exports.oAuthBearer = void 0; const api_1 = require("../api"); const number_1 = require("../utils/number"); const retry_1 = require("../utils/retry"); const MAX_INT = Math.pow(2, 31) - 1; const oAuthBearer = (getToken) => { return { mechanism: 'OAUTHBEARER', authenticate: async ({ sendRequest }) => { const { access_token: accessToken } = await getToken(); const sep = String.fromCharCode(1); const authBytes = `n,,${sep}auth=Bearer ${accessToken}${sep}${sep}`; await sendRequest(api_1.API.SASL_AUTHENTICATE, { authBytes: Buffer.from(authBytes) }); }, }; }; exports.oAuthBearer = oAuthBearer; const oAuthAuthenticator = ({ endpoint, clientId, clientSecret, refreshThresholdSeconds = 15, }) => { let tokenPromise = createToken(endpoint, { grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, }); const scheduleRefresh = () => { tokenPromise.then((token) => { const refreshInMs = (0, number_1.clamp)((token.expires_in - refreshThresholdSeconds) * 1000, 1, MAX_INT); setTimeout(() => { tokenPromise = createToken(endpoint, { grant_type: 'refresh_token', client_id: clientId, client_secret: clientSecret, refresh_token: token.refresh_token, }); scheduleRefresh(); }, refreshInMs); }); }; scheduleRefresh(); return () => tokenPromise; }; exports.oAuthAuthenticator = oAuthAuthenticator; const createToken = async (endpoint, body) => { return (0, retry_1.withRetry)((0, retry_1.exponentialBackoff)(100), 5)(async () => { const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(body), }); if (!response.ok) { throw new Error(`Failed to obtain OAuth token: ${await response.text()}`); } return response.json(); }); };