Skip to content

πŸ“¨ The ultimate agentic social media scheduling tool πŸ€–

feat: hubspot

Nevo Davidb1a28b17eb73
diff --git a/.env.example b/.env.example
index bb0c5c623..3e25a928a 100644
--- a/.env.example
+++ b/.env.example
@@ -125,6 +125,11 @@ OPENAI_API_KEY=""
# OAuth client configured for the ChatGPT app. Only this client can receive
# verified user email claims for ChatGPT Enterprise domain restrictions.
OPENAI_OAUTH_CLIENT_ID=""
+# Client id of the OAuth app (Settings > Developers) that HubSpot agents
+# connect with. HubSpot sends no client secret, so this one app uses PKCE
+# 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=""
# 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 empty
diff --git a/apps/backend/src/api/routes/oauth.controller.ts b/apps/backend/src/api/routes/oauth.controller.ts
index b3f0986be..cda1d5311 100644
--- a/apps/backend/src/api/routes/oauth.controller.ts
+++ b/apps/backend/src/api/routes/oauth.controller.ts
@@ -102,13 +102,11 @@ export class OAuthController {
const code = await this._oauthService.createSelfHostedAuthorizationCode(
app.id,
{ ...instance, email },
- app.dynamic
- ? {
- codeChallenge: body.code_challenge,
- codeChallengeMethod: body.code_challenge_method,
- redirectUri: body.redirect_uri,
- }
- : undefined
+ this._oauthService.pkceBinding(app, {
+ codeChallenge: body.code_challenge,
+ codeChallengeMethod: body.code_challenge_method,
+ redirectUri: body.redirect_uri,
+ })
);
// Same redirect as an approved cloud authorization
@@ -129,6 +127,20 @@ export class OAuthController {
@Body() body: TokenExchangeDto,
@Headers('authorization') authorization?: string
) {
+ // client_secret_basic puts the credentials in the Authorization header,
+ // client_secret_post and public clients put them in the body
+ const basic = extractBasicCredentials(authorization);
+ const clientId = basic?.clientId || body.client_id;
+
+ // Only HubSpot gets refresh tokens, the service answers every other
+ // client with unsupported_grant_type, as before
+ if (body.grant_type === 'refresh_token') {
+ return this._oauthService.refreshAccessToken(
+ clientId,
+ body.refresh_token
+ );
+ }
+
if (body.grant_type !== 'authorization_code') {
throw new HttpException(
{ error: 'unsupported_grant_type' },
@@ -136,10 +148,6 @@ export class OAuthController {
);
}
- // client_secret_basic puts the credentials in the Authorization header,
- // client_secret_post and public clients put them in the body
- const basic = extractBasicCredentials(authorization);
- const clientId = basic?.clientId || body.client_id;
if (!clientId) {
throw new HttpException(
{ error: 'invalid_client' },
@@ -204,13 +212,11 @@ export class OAuthAuthorizedController {
app.id,
user.id,
org.id,
- app.dynamic
- ? {
- codeChallenge: body.code_challenge,
- codeChallengeMethod: body.code_challenge_method,
- redirectUri: body.redirect_uri,
- }
- : undefined
+ this._oauthService.pkceBinding(app, {
+ codeChallenge: body.code_challenge,
+ codeChallengeMethod: body.code_challenge_method,
+ redirectUri: body.redirect_uri,
+ })
);
const redirectUrl = new URL(redirectTarget);
diff --git a/libraries/nestjs-libraries/src/chat/start.mcp.ts b/libraries/nestjs-libraries/src/chat/start.mcp.ts
index b96c75d8a..0ff9fa058 100644
--- a/libraries/nestjs-libraries/src/chat/start.mcp.ts
+++ b/libraries/nestjs-libraries/src/chat/start.mcp.ts
@@ -27,6 +27,8 @@ const fixAcceptHeader = (req: Request) => {
const openAiOAuthClientId = process.env.OPENAI_OAUTH_CLIENT_ID?.trim();
const enableOidcEmailClaims = Boolean(openAiOAuthClientId);
+// The static app HubSpot agents connect with, see OAuthService
+const hubspotOAuthClientId = process.env.HUBSPOT_OAUTH_CLIENT_ID?.trim();
const oauthScopes = [
...(enableOidcEmailClaims ? ['openid', 'email'] : []),
'mcp:read',
@@ -179,19 +181,34 @@ export const startMcp = async (app: INestApplication) => {
// the pre-defined client credentials instead of DCR (a fresh path, because
// OpenAI kept serving its cached copy of the old /mcp-oauth metadata).
// /mcp-oauth-dynamic keeps DCR for Claude, Cursor and every other
- // self-registering client
- const authorizationServers: Record<string, { issuer: string; registration: boolean }> = {
+ // self-registering client.
+ // HubSpot agents follow the 2025-03-26 MCP authorization spec: they read the
+ // metadata from the domain root of the MCP url (no path issuer), connect with
+ // a pre-registered client instead of DCR and require the refresh_token
+ // grant, so the root is answered only when that client is configured
+ const authorizationServers: Record<string, { issuer: string; registration: boolean; refresh: boolean }> = {
'/mcp-oauth-chatgpt': {
issuer: new URL('/mcp-oauth-chatgpt', process.env.NEXT_PUBLIC_BACKEND_URL!).toString(),
registration: false,
+ refresh: false,
},
'/mcp-oauth-dynamic': {
issuer: new URL('/mcp-oauth-dynamic', process.env.NEXT_PUBLIC_BACKEND_URL!).toString(),
registration: true,
+ refresh: false,
},
+ ...(hubspotOAuthClientId
+ ? {
+ '/': {
+ issuer: new URL(process.env.NEXT_PUBLIC_BACKEND_URL!).origin,
+ registration: false,
+ refresh: true,
+ },
+ }
+ : {}),
};
- const authorizationServerMetadata = (server: { issuer: string; registration: boolean }) => ({
+ const authorizationServerMetadata = (server: { issuer: string; registration: boolean; refresh: boolean }) => ({
// RFC 8414: metadata served at /.well-known/oauth-authorization-server/<path>
// belongs to the path-based issuer <backend>/<path>
issuer: server.issuer,
@@ -204,7 +221,9 @@ export const startMcp = async (app: INestApplication) => {
userinfo_endpoint: `${backendUrl}/oauth/userinfo`,
}),
response_types_supported: ['code'],
- grant_types_supported: ['authorization_code'],
+ grant_types_supported: server.refresh
+ ? ['authorization_code', 'refresh_token']
+ : ['authorization_code'],
token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post', 'none'],
code_challenge_methods_supported: ['S256'],
scopes_supported: oauthScopes,
@@ -294,7 +313,8 @@ export const startMcp = async (app: INestApplication) => {
app.use('/.well-known/openid-configuration', async (req: Request, res: Response, next: () => void) => {
const server = authorizationServers[req.path];
- if (!server || !enableOidcEmailClaims) {
+ // the root issuer is HubSpot's, which never gets email claims
+ if (!server || !enableOidcEmailClaims || req.path === '/') {
next();
return;
}
diff --git a/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.repository.ts b/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.repository.ts
index eb30f8f9a..c477da5db 100644
--- a/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.repository.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.repository.ts
@@ -401,6 +401,7 @@ export class OAuthRepository {
},
select: {
id: true,
+ oauthAppId: true,
mcpUrl: true,
apiKey: true,
},
diff --git a/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.service.ts b/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.service.ts
index 6e401157f..1fd89c270 100644
--- a/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.service.ts
@@ -15,6 +15,16 @@ const openAiOAuthClientId = () =>
const enableOidcEmailClaims = () => Boolean(openAiOAuthClientId());
+// The static app HubSpot agents connect with (created under Settings >
+// Developers). HubSpot's MCP connector sends no client secret and requires a
+// refresh token, see isPublicClient and refreshFields
+const hubspotOAuthClientId = () =>
+ process.env.HUBSPOT_OAUTH_CLIENT_ID?.trim();
+
+// Postiz access tokens never expire, but HubSpot wants an expires_in: ten
+// years (a hundred would not fit in a 32-bit integer)
+const hubspotTokenExpiresIn = 10 * 365 * 24 * 60 * 60;
+
// Postiz Cloud only, a self-hosted install has nothing to relay to
export const selfHostedRelayEnabled = () =>
process.env.MCP_SELF_HOSTED_RELAY === 'true';
@@ -326,13 +336,18 @@ export class OAuthService {
}
// Dynamically registered clients must use their registered redirect_uris
- // and PKCE; statically registered apps keep the existing lenient flow
+ // and PKCE; statically registered apps keep the existing lenient flow,
+ // except a public one (HubSpot), which has no secret and needs PKCE too
if (app.dynamic) {
const registered: string[] = JSON.parse(app.redirectUris || '[]');
if (!options?.redirectUri || !registered.includes(options.redirectUri)) {
throw new HttpException('Invalid redirect_uri', HttpStatus.BAD_REQUEST);
}
- if (app.tokenEndpointAuthMethod === 'none' && !options?.codeChallenge) {
+ }
+
+ const isPublicClient = this.isPublicClient(app);
+ if (app.dynamic || isPublicClient) {
+ if (isPublicClient && !options?.codeChallenge) {
throw new HttpException(
'code_challenge is required for this client',
HttpStatus.BAD_REQUEST
@@ -353,6 +368,42 @@ export class OAuthService {
return app;
}
+ // Clients that authenticate with PKCE instead of a client secret: dynamic
+ // registrations with token_endpoint_auth_method=none, and HubSpot, whose
+ // MCP connector only takes a client id
+ private isPublicClient(
+ app: Pick<OAuthApp, 'clientId' | 'dynamic' | 'tokenEndpointAuthMethod'>
+ ) {
+ return (
+ (app.dynamic && app.tokenEndpointAuthMethod === 'none') ||
+ app.clientId === hubspotOAuthClientId()
+ );
+ }
+
+ // What an authorization code is bound to: a dynamic client's PKCE challenge
+ // and redirect_uri, a public static app's PKCE challenge only (static apps
+ // always redirect to their stored redirectUrl). Other static apps keep the
+ // lenient flow and bind nothing
+ pkceBinding(
+ app: Pick<OAuthApp, 'clientId' | 'dynamic' | 'tokenEndpointAuthMethod'>,
+ request: {
+ codeChallenge?: string;
+ codeChallengeMethod?: string;
+ redirectUri?: string;
+ }
+ ) {
+ if (app.dynamic) {
+ return request;
+ }
+ if (this.isPublicClient(app)) {
+ return {
+ codeChallenge: request.codeChallenge,
+ codeChallengeMethod: request.codeChallengeMethod,
+ };
+ }
+ return undefined;
+ }
+
async createAuthorizationCode(
oauthAppId: string,
userId: string,
@@ -430,10 +481,7 @@ export class OAuthService {
);
}
- // Public clients (dynamic registration with token_endpoint_auth_method=none)
- // authenticate with PKCE instead of a client secret
- const isPublicClient = app.dynamic && app.tokenEndpointAuthMethod === 'none';
- if (!isPublicClient) {
+ if (!this.isPublicClient(app)) {
if (
!clientSecret ||
!app.clientSecret ||
@@ -482,6 +530,7 @@ export class OAuthService {
access_token: token,
token_type: 'bearer',
scope: this.grantedScope(app),
+ ...this.refreshFields(app, token),
};
}
@@ -557,6 +606,69 @@ export class OAuthService {
access_token: token,
token_type: 'bearer',
scope: this.grantedScope(app),
+ ...this.refreshFields(app, token),
+ };
+ }
+
+ // HubSpot refuses a token response without a refresh token. Postiz access
+ // tokens never expire, so the refresh token is the access token itself:
+ // refreshing hands it back unchanged, and it stops working exactly when the
+ // access token does. No other client gets these fields
+ private refreshFields(app: Pick<OAuthApp, 'clientId'>, token: string) {
+ if (app.clientId !== hubspotOAuthClientId()) {
+ return {};
+ }
+
+ return {
+ refresh_token: token,
+ expires_in: hubspotTokenExpiresIn,
+ };
+ }
+
+ // The refresh_token grant, HubSpot only (see refreshFields): the refresh
+ // token is looked up like an access token and handed back while it is valid
+ async refreshAccessToken(clientId?: string, refreshToken?: string) {
+ if (!clientId || clientId !== hubspotOAuthClientId()) {
+ throw new HttpException(
+ { error: 'unsupported_grant_type' },
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ const app = await this._oauthRepository.getAppByClientId(clientId);
+ if (!app) {
+ throw new HttpException(
+ { error: 'invalid_client' },
+ HttpStatus.UNAUTHORIZED
+ );
+ }
+
+ if (!refreshToken) {
+ throw new HttpException(
+ { error: 'invalid_request', error_description: 'refresh_token is required' },
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ // a self-hosted connection only works while the relay is on
+ const encryptedToken = AuthService.fixedEncryption(refreshToken);
+ const authorization = refreshToken.startsWith('psh_')
+ ? selfHostedRelayEnabled()
+ ? await this._oauthRepository.findSelfHostedByAccessToken(encryptedToken)
+ : null
+ : await this._oauthRepository.findByAccessToken(encryptedToken);
+ if (!authorization || authorization.oauthAppId !== app.id) {
+ throw new HttpException(
+ { error: 'invalid_grant' },
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ return {
+ access_token: refreshToken,
+ token_type: 'bearer',
+ scope: this.grantedScope(app),
+ ...this.refreshFields(app, refreshToken),
};
}
diff --git a/libraries/nestjs-libraries/src/dtos/oauth/authorize-oauth.dto.ts b/libraries/nestjs-libraries/src/dtos/oauth/authorize-oauth.dto.ts
index 393391f2e..42400a56a 100644
--- a/libraries/nestjs-libraries/src/dtos/oauth/authorize-oauth.dto.ts
+++ b/libraries/nestjs-libraries/src/dtos/oauth/authorize-oauth.dto.ts
@@ -30,7 +30,8 @@ export class AuthorizeOAuthQueryDto {
code_challenge?: string;
// Not validated with IsIn: static clients may send arbitrary values that
- // were always ignored; only dynamic clients get S256 enforced (in the service)
+ // were always ignored; only dynamic clients and HubSpot get S256 enforced
+ // (in the service)
@IsString()
@IsOptional()
code_challenge_method?: string;
@@ -69,7 +70,8 @@ export class ApproveOAuthDto {
code_challenge?: string;
// Not validated with IsIn: static clients may send arbitrary values that
- // were always ignored; only dynamic clients get S256 enforced (in the service)
+ // were always ignored; only dynamic clients and HubSpot get S256 enforced
+ // (in the service)
@IsString()
@IsOptional()
code_challenge_method?: string;
diff --git a/libraries/nestjs-libraries/src/dtos/oauth/token-exchange.dto.ts b/libraries/nestjs-libraries/src/dtos/oauth/token-exchange.dto.ts
index ca3b3b7fe..62146d3d5 100644
--- a/libraries/nestjs-libraries/src/dtos/oauth/token-exchange.dto.ts
+++ b/libraries/nestjs-libraries/src/dtos/oauth/token-exchange.dto.ts
@@ -1,14 +1,20 @@
-import { IsDefined, IsOptional, IsString } from 'class-validator';
+import { IsDefined, IsOptional, IsString, ValidateIf } from 'class-validator';
export class TokenExchangeDto {
@IsString()
@IsDefined()
grant_type: string;
+ // The refresh_token grant sends refresh_token instead
@IsString()
@IsDefined()
+ @ValidateIf((o) => o.grant_type !== 'refresh_token')
code: string;
+ @IsString()
+ @IsOptional()
+ refresh_token?: string;
+
// Optional here because client_secret_basic clients send the id and secret
// in the Authorization header; the controller merges the two sources and
// the service rejects a request that ends up without a client_id
@@ -16,8 +22,8 @@ export class TokenExchangeDto {
@IsOptional()
client_id?: string;
- // Optional to allow PKCE-only public clients (dynamic registration);
- // the service still enforces it for confidential clients
+ // Optional to allow PKCE-only public clients (dynamic registration,
+ // HubSpot); the service still enforces it for confidential clients
@IsString()
@IsOptional()
client_secret?: string;