π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: hubspot
Nevo David0956d49ab79a
diff --git a/.env.example b/.env.exampleindex 3e25a928a..90abe339e 100644--- a/.env.example+++ b/.env.example@@ -130,6 +130,12 @@ OPENAI_OAUTH_CLIENT_ID=""# instead, gets a refresh token, and the MCP backend answers OAuth discovery# at its domain root. Set it on both the API and the MCP backend.# HUBSPOT_OAUTH_CLIENT_ID=""+# Client id and secret of the HubSpot app itself (HubSpot project > app >+# Auth tab), not of the Postiz app above. Its redirect URL is+# <NEXT_PUBLIC_BACKEND_URL>/oauth/hubspot/callback, which finishes the install+# (HubSpot only counts it once the code is exchanged). Set them on the API.+# HUBSPOT_APP_CLIENT_ID=""+# HUBSPOT_APP_CLIENT_SECRET=""# MCP OAuth Dynamic Client Registration (RFC 7591) redirect-domain allowlist.# When set (comma separated), POST /oauth/register only accepts redirect_uris# whose host matches a listed domain or one of its subdomains; unset or emptydiff --git a/apps/backend/src/api/routes/oauth.controller.ts b/apps/backend/src/api/routes/oauth.controller.tsindex cda1d5311..f7a2a6a74 100644--- a/apps/backend/src/api/routes/oauth.controller.ts+++ b/apps/backend/src/api/routes/oauth.controller.ts@@ -8,8 +8,10 @@ import {HttpStatus,Post,Query,+ Res,UseGuards,} from '@nestjs/common';+import { Response } from 'express';import { ApiTags } from '@nestjs/swagger';import { Throttle } from '@nestjs/throttler';import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';@@ -23,6 +25,7 @@ import {} from '@gitroom/nestjs-libraries/dtos/oauth/authorize-oauth.dto';import { TokenExchangeDto } from '@gitroom/nestjs-libraries/dtos/oauth/token-exchange.dto';import { RegisterClientDto } from '@gitroom/nestjs-libraries/dtos/oauth/register-client.dto';+import { HubspotInstallQueryDto } from '@gitroom/nestjs-libraries/dtos/oauth/hubspot-install.dto';import { extractBasicCredentials } from '@gitroom/nestjs-libraries/chat/oauth-types';import { McpRelayService } from '@gitroom/nestjs-libraries/chat/mcp.relay.service';import { ThrottlerRealIpGuard } from '@gitroom/nestjs-libraries/throttler/throttler.provider';@@ -173,6 +176,19 @@ export class OAuthController {async userinfoPost(@Headers('authorization') authorization?: string) {return this._oauthService.getUserInfo(authorization);}++ // Public (HubSpot sends the person here after they install the HubSpot app)+ // and capped per IP, since every attempt sends a request to HubSpot+ @UseGuards(ThrottlerRealIpGuard)+ @Throttle({ default: { limit: 30, ttl: 3600000 } })+ @Get('/hubspot/callback')+ async hubspotCallback(+ @Query() query: HubspotInstallQueryDto,+ @Res({ passthrough: false }) response: Response+ ) {+ await this._oauthService.completeHubspotInstall(query.code);+ return response.redirect(302, process.env.FRONTEND_URL!);+ }}@ApiTags('OAuth')diff --git a/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.service.ts b/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.service.tsindex 1fd89c270..ee9a328a1 100644--- a/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.service.ts@@ -25,6 +25,12 @@ const hubspotOAuthClientId = () =>// years (a hundred would not fit in a 32-bit integer)const hubspotTokenExpiresIn = 10 * 365 * 24 * 60 * 60;+// The HubSpot app itself (HubSpot project > app > Auth tab), not the Postiz+// app above: its redirect URL finishes the install, see completeHubspotInstall+const hubspotAppClientId = () => process.env.HUBSPOT_APP_CLIENT_ID?.trim();+const hubspotAppClientSecret = () =>+ process.env.HUBSPOT_APP_CLIENT_SECRET?.trim();+// Postiz Cloud only, a self-hosted install has nothing to relay toexport const selfHostedRelayEnabled = () =>process.env.MCP_SELF_HOSTED_RELAY === 'true';@@ -672,6 +678,51 @@ export class OAuthService {};}+ // HubSpot only counts an install of the HubSpot app once its code is+ // exchanged. Postiz makes no HubSpot API calls, so the tokens are not kept+ async completeHubspotInstall(code: string) {+ const clientId = hubspotAppClientId();+ const clientSecret = hubspotAppClientSecret();+ if (!clientId || !clientSecret) {+ throw new HttpException('Not found', HttpStatus.NOT_FOUND);+ }++ let response: Response;+ try {+ response = await fetch('https://api.hubapi.com/oauth/v3/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'authorization_code',+ client_id: clientId,+ client_secret: clientSecret,+ redirect_uri: `${process.env.NEXT_PUBLIC_BACKEND_URL}/oauth/hubspot/callback`,+ code,+ }),+ signal: AbortSignal.timeout(30000),+ });+ } catch (err) {+ // timeout or network failure, fetch rejects instead of answering+ throw new HttpException(+ 'Could not reach HubSpot to finish installing Postiz, please try again',+ HttpStatus.BAD_GATEWAY,+ { cause: err }+ );+ }++ if (!response.ok) {+ const value = await response.json().catch(() => null);+ throw new HttpException(+ `Could not finish installing Postiz in HubSpot${+ value?.message ? `: ${value.message}` : ''+ }`,+ HttpStatus.BAD_REQUEST+ );+ }++ await response.body?.cancel();+ }+// null when the relay is off or the token is unknown or revokedasync getSelfHostedByAccessToken(token: string) {if (!selfHostedRelayEnabled()) {diff --git a/libraries/nestjs-libraries/src/dtos/oauth/hubspot-install.dto.ts b/libraries/nestjs-libraries/src/dtos/oauth/hubspot-install.dto.tsnew file mode 100644index 000000000..a7944ad3b--- /dev/null+++ b/libraries/nestjs-libraries/src/dtos/oauth/hubspot-install.dto.ts@@ -0,0 +1,8 @@+import { IsDefined, IsString } from 'class-validator';++export class HubspotInstallQueryDto {+ // Added by HubSpot to the HubSpot app's redirect URL after an install+ @IsString()+ @IsDefined()+ code: string;+}