UNPKG

@eagleeye-solutions/integration-events-common

Version:
83 lines 3.13 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.sendMessageToGcpPubSubTopic = sendMessageToGcpPubSubTopic; exports.unwrapPubSubMessage = unwrapPubSubMessage; exports.isGoogleCloudRun = isGoogleCloudRun; exports.requireGoogleJwt = requireGoogleJwt; const pubsub_1 = require("@google-cloud/pubsub"); const google_auth_library_1 = require("google-auth-library"); const http_errors_1 = __importDefault(require("http-errors")); const authClient = new google_auth_library_1.OAuth2Client(); const pubsubClients = {}; const topicClients = {}; async function sendMessageToGcpPubSubTopic(appConfig, topicName, message, attributes, logger) { const projectId = appConfig.platformConfig.projectId; if (!pubsubClients[projectId]) { pubsubClients[projectId] = new pubsub_1.PubSub({ projectId }); } const pubsub = pubsubClients[projectId]; const actualTopicName = process.env.SIMULATE_PUBSUB_FAILURE ? 'fake-topic' : topicName; const topicKey = `${projectId}:${actualTopicName}`; if (!topicClients[topicKey]) { topicClients[topicKey] = pubsub.topic(actualTopicName); } const topic = topicClients[topicKey]; try { await topic.publishMessage({ json: message, attributes, }); logger.debug(`Published message to topic: ${topic.name}`); } catch (err) { logger.error(err, `Error publishing to topic: ${topic.name}`); throw err; } } function unwrapPubSubMessage(request) { if (typeof request?.body?.message?.data === 'string') { // Assume received as Pub/Sub wrapped data, so we need to unwrap it. return JSON.parse(Buffer.from(request.body.message.data, 'base64').toString('utf-8')); } else { throw new Error(`Unexpected data format: ${JSON.stringify(request.body)}`); } } function isGoogleCloudRun() { return process.env.K_SERVICE !== undefined; } async function requireGoogleJwt(appConfig, req, res, next) { const authHeader = req.get('Authorization'); if (authHeader === undefined) { throw http_errors_1.default.Unauthorized('Authorization header not found'); } const [, token] = authHeader.match(/Bearer (.*)/) ?? []; if (token === undefined) { throw http_errors_1.default.Unauthorized('Bearer token not found'); } const ticket = await authClient.verifyIdToken({ idToken: token, audience: appConfig.platformConfig.pubSubAuthenticatedPushAudience, }); const claim = ticket.getPayload(); if (claim?.email_verified && claim?.email === appConfig.platformConfig.pubSubAuthenticatedPushServiceAccount) { next(); } else { throw http_errors_1.default.Unauthorized(`Invalid claims: ${JSON.stringify({ claim })}`); } } exports.default = { sendMessageToGcpPubSubTopic, unwrapPubSubMessage, isGoogleCloudRun, requireGoogleJwt, }; //# sourceMappingURL=gcp.js.map