Skip to content

📨 The ultimate agentic social media scheduling tool 🤖

feat: self hosting connector

Nevo David876ab9e6d954
diff --git a/.env.example b/.env.example
index d91b43bc2..bb0c5c623 100644
--- a/.env.example
+++ b/.env.example
@@ -134,6 +134,11 @@ OPENAI_OAUTH_CLIENT_ID=""
# and are always accepted. Example locks web callbacks to the claude.ai
# connector; add cursor.com for Cursor.
# DCR_VERIFIED_DOMAINS="claude.ai,claude.com"
+# Postiz Cloud only: lets people connect a self-hosted Postiz on the MCP
+# consent screen ("Use self-hosted"). The MCP tool calls of that connection
+# are relayed to the instance with its API key. Leave unset on self-hosted
+# installs; set it on both the API and the MCP backend.
+# MCP_SELF_HOSTED_RELAY=true
# EVOLINK_API_KEY="" # EvoLink API key for Seedance AI video generation (https://evolink.ai)
NEXT_PUBLIC_DISCORD_SUPPORT=""
NEXT_PUBLIC_POLOTNO=""
diff --git a/apps/backend/src/api/routes/oauth.controller.ts b/apps/backend/src/api/routes/oauth.controller.ts
index 369b20f2b..b3f0986be 100644
--- a/apps/backend/src/api/routes/oauth.controller.ts
+++ b/apps/backend/src/api/routes/oauth.controller.ts
@@ -8,21 +8,32 @@ import {
HttpStatus,
Post,
Query,
+ UseGuards,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
+import { Throttle } from '@nestjs/throttler';
import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
import { User, Organization } from '@prisma/client';
-import { AuthorizeOAuthQueryDto, ApproveOAuthDto } from '@gitroom/nestjs-libraries/dtos/oauth/authorize-oauth.dto';
+import {
+ AuthorizeOAuthQueryDto,
+ ApproveOAuthDto,
+ AuthorizeSelfHostedDto,
+} 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 { 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';
@ApiTags('OAuth')
@Controller('/oauth')
export class OAuthController {
- constructor(private _oauthService: OAuthService) {}
+ constructor(
+ private _oauthService: OAuthService,
+ private _mcpRelayService: McpRelayService
+ ) {}
// Dynamic Client Registration (RFC 7591), used by MCP clients like Claude
@Post('/register')
@@ -42,6 +53,11 @@ export class OAuthController {
}
);
+ const selfHosted = this._oauthService.allowsSelfHosted(
+ app,
+ query.resource
+ );
+
return {
app: {
name: app.name,
@@ -51,9 +67,61 @@ export class OAuthController {
redirectUrl: app.redirectUrl,
},
state: query.state,
+ selfHosted,
+ selfHostedEmail:
+ selfHosted && this._oauthService.selfHostedRequiresEmail(app),
};
}
+ // Public (the person may have no account here) and capped per client,
+ // since every attempt sends requests to the instance
+ @UseGuards(ThrottlerRealIpGuard)
+ @Throttle({ default: { limit: 30, ttl: 3600000 } })
+ @Post('/authorize/self-hosted')
+ async authorizeSelfHosted(@Body() body: AuthorizeSelfHostedDto) {
+ const app = await this._oauthService.validateAuthorizationRequest(
+ body.client_id,
+ {
+ redirectUri: body.redirect_uri,
+ codeChallenge: body.code_challenge,
+ codeChallengeMethod: body.code_challenge_method,
+ }
+ );
+
+ const email = body.email?.trim();
+ this._oauthService.validateSelfHostedRequest(app, {
+ resource: body.resource,
+ email,
+ });
+
+ const instance = await this._mcpRelayService.connect(
+ body.instance_url,
+ body.api_key
+ );
+
+ 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
+ );
+
+ // Same redirect as an approved cloud authorization
+ const redirectUrl = new URL(
+ app.dynamic ? body.redirect_uri! : app.redirectUrl
+ );
+ redirectUrl.searchParams.set('code', code);
+ if (body.state) {
+ redirectUrl.searchParams.set('state', body.state);
+ }
+ return { redirect: redirectUrl.toString() };
+ }
+
@Post('/token')
// RFC 6749 §5.1: successful token responses are 200; strict clients (Canva) reject Nest's default 201
@HttpCode(200)
diff --git a/apps/frontend/src/app/(app)/oauth/authorize/page.tsx b/apps/frontend/src/app/(app)/oauth/authorize/page.tsx
index 29c2ce128..e6dbbdfb2 100644
--- a/apps/frontend/src/app/(app)/oauth/authorize/page.tsx
+++ b/apps/frontend/src/app/(app)/oauth/authorize/page.tsx
@@ -1,221 +1,10 @@
-'use client';
+import { OAuthAuthorize } from '@gitroom/frontend/components/oauth/authorize.component';
+import { cookies } from 'next/headers';
-import { useCallback, useEffect, useState } from 'react';
-import { useSearchParams } from 'next/navigation';
-import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
-import { Logo } from '@gitroom/frontend/components/new-layout/logo';
+export const dynamic = 'force-dynamic';
-export default function OAuthAuthorizePage() {
- const searchParams = useSearchParams();
- const fetch = useFetch();
- const [appInfo, setAppInfo] = useState<any>(null);
- const [error, setError] = useState('');
- const [loading, setLoading] = useState(true);
- const [submitting, setSubmitting] = useState(false);
-
- const clientId = searchParams.get('client_id');
- const responseType = searchParams.get('response_type');
- const state = searchParams.get('state');
- const redirectUri = searchParams.get('redirect_uri');
- const codeChallenge = searchParams.get('code_challenge');
- const codeChallengeMethod = searchParams.get('code_challenge_method');
-
- useEffect(() => {
- if (!clientId || !responseType) {
- setError('Missing required parameters (client_id, response_type)');
- setLoading(false);
- return;
- }
- if (responseType !== 'code') {
- setError('Only response_type=code is supported');
- setLoading(false);
- return;
- }
-
- const params = new URLSearchParams({
- client_id: clientId,
- response_type: responseType,
- ...(state ? { state } : {}),
- ...(redirectUri ? { redirect_uri: redirectUri } : {}),
- ...(codeChallenge ? { code_challenge: codeChallenge } : {}),
- ...(codeChallengeMethod
- ? { code_challenge_method: codeChallengeMethod }
- : {}),
- });
-
- fetch(`/oauth/authorize?${params}`)
- .then((r) => r.json())
- .then((data) => {
- if (data.statusCode && data.statusCode >= 400) {
- setError(data.message || 'Invalid OAuth request');
- } else {
- setAppInfo(data);
- }
- setLoading(false);
- })
- .catch(() => {
- setError('Failed to validate OAuth request');
- setLoading(false);
- });
- }, [clientId, responseType, state, redirectUri, codeChallenge, codeChallengeMethod]);
-
- const handleAction = useCallback(
- async (action: 'approve' | 'deny') => {
- setSubmitting(true);
- try {
- const result = await (
- await fetch('/oauth/authorize', {
- method: 'POST',
- body: JSON.stringify({
- client_id: clientId,
- state,
- action,
- ...(redirectUri ? { redirect_uri: redirectUri } : {}),
- ...(codeChallenge ? { code_challenge: codeChallenge } : {}),
- ...(codeChallengeMethod
- ? { code_challenge_method: codeChallengeMethod }
- : {}),
- }),
- })
- ).json();
-
- if (result.redirect) {
- window.location.href = result.redirect;
- }
- } catch {
- setError('Failed to process authorization');
- setSubmitting(false);
- }
- },
- [clientId, state, redirectUri, codeChallenge, codeChallengeMethod]
- );
-
- if (loading) {
- return (
- <div className="flex flex-1 items-center justify-center text-white relative overflow-hidden">
- <div className="absolute inset-0 opacity-30">
- <div className="absolute top-[20%] left-[10%] w-[300px] h-[300px] bg-[#612BD3] rounded-full blur-[120px]" />
- <div className="absolute bottom-[20%] right-[10%] w-[250px] h-[250px] bg-[#FC69FF] rounded-full blur-[120px]" />
- </div>
- <div className="relative z-10 text-center">
- <div className="flex justify-center mb-[24px]">
- <Logo />
- </div>
- <div className="text-[16px] text-gray-400">
- Please wait...
- </div>
- <div className="mt-[32px] flex justify-center">
- <div className="w-[48px] h-[48px] border-[3px] border-[#612BD3] border-t-transparent rounded-full animate-spin" />
- </div>
- </div>
- </div>
- );
- }
-
- if (error) {
- return (
- <div className="flex flex-1 items-center justify-center text-white relative overflow-hidden">
- <div className="absolute inset-0 opacity-30">
- <div className="absolute top-[20%] left-[10%] w-[300px] h-[300px] bg-[#612BD3] rounded-full blur-[120px]" />
- <div className="absolute bottom-[20%] right-[10%] w-[250px] h-[250px] bg-[#FC69FF] rounded-full blur-[120px]" />
- </div>
- <div className="relative z-10 text-center">
- <div className="flex justify-center mb-[24px]">
- <Logo />
- </div>
- <div className="w-[80px] h-[80px] mx-auto mb-[24px] rounded-full bg-red-500/20 flex items-center justify-center">
- <svg
- className="w-[40px] h-[40px] text-red-500"
- fill="currentColor"
- viewBox="0 0 20 20"
- >
- <path
- fillRule="evenodd"
- d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
- clipRule="evenodd"
- />
- </svg>
- </div>
- <div className="text-[28px] font-semibold mb-[12px]">
- Authorization Error
- </div>
- <div className="text-[16px] text-gray-400 max-w-[400px]">
- {error}
- </div>
- </div>
- </div>
- );
- }
-
- if (!appInfo) {
- return null;
- }
-
- return (
- <div className="flex flex-1 items-center justify-center text-white relative overflow-hidden">
- <div className="absolute inset-0 opacity-30">
- <div className="absolute top-[20%] left-[10%] w-[300px] h-[300px] bg-[#612BD3] rounded-full blur-[120px]" />
- <div className="absolute bottom-[20%] right-[10%] w-[250px] h-[250px] bg-[#FC69FF] rounded-full blur-[120px]" />
- </div>
-
- <div className="relative z-10 w-full max-w-[500px] mx-auto px-[20px]">
- <div className="flex justify-center mb-[32px]">
- <Logo />
- </div>
-
- <div className="bg-[#1A1919] rounded-[16px] p-[32px] flex flex-col gap-[24px]">
- <div className="flex flex-col items-center gap-[16px]">
- {appInfo.app.picture?.path ? (
- <img
- src={appInfo.app.picture.path}
- alt={appInfo.app.name}
- className="w-[64px] h-[64px] rounded-full object-cover"
- />
- ) : (
- <div className="w-[64px] h-[64px] rounded-full bg-[#2A2929] flex items-center justify-center text-[24px] text-gray-400">
- {appInfo.app.name?.[0]?.toUpperCase() || '?'}
- </div>
- )}
- <h2 className="text-[24px] font-semibold text-center">
- {appInfo.app.name}
- </h2>
- {appInfo.app.description && (
- <div className="text-gray-400 text-center text-[14px]">
- {appInfo.app.description}
- </div>
- )}
- </div>
-
- <div className="border-t border-[#2A2929] pt-[16px]">
- <div className="text-[14px] text-gray-400 mb-[12px]">
- This application is requesting access to your Postiz account. It
- will be able to:
- </div>
- <ul className="text-[14px] list-disc list-inside space-y-[4px]">
- <li>Access your integrations and channels</li>
- <li>Create and schedule posts on your behalf</li>
- <li>Read your post analytics</li>
- </ul>
- </div>
-
- <div className="flex gap-[12px]">
- <button
- onClick={() => handleAction('approve')}
- disabled={submitting}
- className="flex-1 bg-[#612BD3] hover:bg-[#7B3FF2] disabled:opacity-50 text-white rounded-[8px] py-[10px] px-[16px] text-[14px] font-semibold transition-colors"
- >
- Authorize
- </button>
- <button
- onClick={() => handleAction('deny')}
- disabled={submitting}
- className="flex-1 bg-[#2A2929] hover:bg-[#3A3939] disabled:opacity-50 text-white rounded-[8px] py-[10px] px-[16px] text-[14px] font-semibold transition-colors"
- >
- Deny
- </button>
- </div>
- </div>
- </div>
- </div>
- );
+// signed-out visitors get the page too (sign in, or use self-hosted)
+export default async function OAuthAuthorizePage() {
+ const get = (await cookies()).get('auth');
+ return <OAuthAuthorize logged={!!get?.name} />;
}
diff --git a/apps/frontend/src/components/oauth/authorize.component.tsx b/apps/frontend/src/components/oauth/authorize.component.tsx
new file mode 100644
index 000000000..00556c4e0
--- /dev/null
+++ b/apps/frontend/src/components/oauth/authorize.component.tsx
@@ -0,0 +1,277 @@
+'use client';
+
+import { FC, useCallback, useEffect, useState } from 'react';
+import { useSearchParams } from 'next/navigation';
+import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
+import { Logo } from '@gitroom/frontend/components/new-layout/logo';
+import { OAuthSelfHosted } from '@gitroom/frontend/components/oauth/self.hosted.component';
+
+export const OAuthAuthorize: FC<{ logged: boolean }> = ({ logged }) => {
+ const searchParams = useSearchParams();
+ const fetch = useFetch();
+ const [appInfo, setAppInfo] = useState<any>(null);
+ const [error, setError] = useState('');
+ const [loading, setLoading] = useState(true);
+ const [submitting, setSubmitting] = useState(false);
+ const [selfHosted, setSelfHosted] = useState(false);
+
+ const clientId = searchParams.get('client_id');
+ const responseType = searchParams.get('response_type');
+ const state = searchParams.get('state');
+ const redirectUri = searchParams.get('redirect_uri');
+ const codeChallenge = searchParams.get('code_challenge');
+ const codeChallengeMethod = searchParams.get('code_challenge_method');
+ const resource = searchParams.get('resource');
+
+ useEffect(() => {
+ if (!clientId || !responseType) {
+ setError('Missing required parameters (client_id, response_type)');
+ setLoading(false);
+ return;
+ }
+ if (responseType !== 'code') {
+ setError('Only response_type=code is supported');
+ setLoading(false);
+ return;
+ }
+
+ const params = new URLSearchParams({
+ client_id: clientId,
+ response_type: responseType,
+ ...(state ? { state } : {}),
+ ...(redirectUri ? { redirect_uri: redirectUri } : {}),
+ ...(codeChallenge ? { code_challenge: codeChallenge } : {}),
+ ...(codeChallengeMethod
+ ? { code_challenge_method: codeChallengeMethod }
+ : {}),
+ ...(resource ? { resource } : {}),
+ });
+
+ fetch(`/oauth/authorize?${params}`)
+ .then((r) => r.json())
+ .then((data) => {
+ if (data.statusCode && data.statusCode >= 400) {
+ setError(data.message || 'Invalid OAuth request');
+ } else {
+ setAppInfo(data);
+ }
+ setLoading(false);
+ })
+ .catch(() => {
+ setError('Failed to validate OAuth request');
+ setLoading(false);
+ });
+ }, [
+ clientId,
+ responseType,
+ state,
+ redirectUri,
+ codeChallenge,
+ codeChallengeMethod,
+ resource,
+ ]);
+
+ const handleAction = useCallback(
+ async (action: 'approve' | 'deny') => {
+ setSubmitting(true);
+ try {
+ const result = await (
+ await fetch('/oauth/authorize', {
+ method: 'POST',
+ body: JSON.stringify({
+ client_id: clientId,
+ state,
+ action,
+ ...(redirectUri ? { redirect_uri: redirectUri } : {}),
+ ...(codeChallenge ? { code_challenge: codeChallenge } : {}),
+ ...(codeChallengeMethod
+ ? { code_challenge_method: codeChallengeMethod }
+ : {}),
+ }),
+ })
+ ).json();
+
+ if (result.redirect) {
+ window.location.href = result.redirect;
+ }
+ } catch {
+ setError('Failed to process authorization');
+ setSubmitting(false);
+ }
+ },
+ [clientId, state, redirectUri, codeChallenge, codeChallengeMethod]
+ );
+
+ // Sign in (or sign up) and land back on this same request
+ const signIn = useCallback(() => {
+ window.location.href = `/auth/login?returnUrl=${encodeURIComponent(
+ window.location.href
+ )}`;
+ }, []);
+
+ if (loading) {
+ return (
+ <div className="flex flex-1 items-center justify-center text-white relative overflow-hidden">
+ <div className="absolute inset-0 opacity-30">
+ <div className="absolute top-[20%] left-[10%] w-[300px] h-[300px] bg-[#612BD3] rounded-full blur-[120px]" />
+ <div className="absolute bottom-[20%] right-[10%] w-[250px] h-[250px] bg-[#FC69FF] rounded-full blur-[120px]" />
+ </div>
+ <div className="relative z-10 text-center">
+ <div className="flex justify-center mb-[24px]">
+ <Logo />
+ </div>
+ <div className="text-[16px] text-gray-400">
+ Please wait...
+ </div>
+ <div className="mt-[32px] flex justify-center">
+ <div className="w-[48px] h-[48px] border-[3px] border-[#612BD3] border-t-transparent rounded-full animate-spin" />
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex flex-1 items-center justify-center text-white relative overflow-hidden">
+ <div className="absolute inset-0 opacity-30">
+ <div className="absolute top-[20%] left-[10%] w-[300px] h-[300px] bg-[#612BD3] rounded-full blur-[120px]" />
+ <div className="absolute bottom-[20%] right-[10%] w-[250px] h-[250px] bg-[#FC69FF] rounded-full blur-[120px]" />
+ </div>
+ <div className="relative z-10 text-center">
+ <div className="flex justify-center mb-[24px]">
+ <Logo />
+ </div>
+ <div className="w-[80px] h-[80px] mx-auto mb-[24px] rounded-full bg-red-500/20 flex items-center justify-center">
+ <svg
+ className="w-[40px] h-[40px] text-red-500"
+ fill="currentColor"
+ viewBox="0 0 20 20"
+ >
+ <path
+ fillRule="evenodd"
+ d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
+ clipRule="evenodd"
+ />
+ </svg>
+ </div>
+ <div className="text-[28px] font-semibold mb-[12px]">
+ Authorization Error
+ </div>
+ <div className="text-[16px] text-gray-400 max-w-[400px]">
+ {error}
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ if (!appInfo) {
+ return null;
+ }
+
+ return (
+ <div className="flex flex-1 items-center justify-center text-white relative overflow-hidden">
+ <div className="absolute inset-0 opacity-30">
+ <div className="absolute top-[20%] left-[10%] w-[300px] h-[300px] bg-[#612BD3] rounded-full blur-[120px]" />
+ <div className="absolute bottom-[20%] right-[10%] w-[250px] h-[250px] bg-[#FC69FF] rounded-full blur-[120px]" />
+ </div>
+
+ <div className="relative z-10 w-full max-w-[500px] mx-auto px-[20px]">
+ <div className="flex justify-center mb-[32px]">
+ <Logo />
+ </div>
+
+ <div className="bg-[#1A1919] rounded-[16px] p-[32px] flex flex-col gap-[24px]">
+ <div className="flex flex-col items-center gap-[16px]">
+ {appInfo.app.picture?.path ? (
+ <img
+ src={appInfo.app.picture.path}
+ alt={appInfo.app.name}
+ className="w-[64px] h-[64px] rounded-full object-cover"
+ />
+ ) : (
+ <div className="w-[64px] h-[64px] rounded-full bg-[#2A2929] flex items-center justify-center text-[24px] text-gray-400">
+ {appInfo.app.name?.[0]?.toUpperCase() || '?'}
+ </div>
+ )}
+ <h2 className="text-[24px] font-semibold text-center">
+ {appInfo.app.name}
+ </h2>
+ {appInfo.app.description && (
+ <div className="text-gray-400 text-center text-[14px]">
+ {appInfo.app.description}
+ </div>
+ )}
+ </div>
+
+ {selfHosted ? (
+ <OAuthSelfHosted
+ appName={appInfo.app.name}
+ askEmail={!!appInfo.selfHostedEmail}
+ params={{
+ client_id: clientId,
+ state,
+ redirect_uri: redirectUri,
+ code_challenge: codeChallenge,
+ code_challenge_method: codeChallengeMethod,
+ resource,
+ }}
+ onBack={() => setSelfHosted(false)}
+ />
+ ) : (
+ <>
+ <div className="border-t border-[#2A2929] pt-[16px]">
+ <div className="text-[14px] text-gray-400 mb-[12px]">
+ This application is requesting access to your Postiz
+ account. It will be able to:
+ </div>
+ <ul className="text-[14px] list-disc list-inside space-y-[4px]">
+ <li>Access your integrations and channels</li>
+ <li>Create and schedule posts on your behalf</li>
+ <li>Read your post analytics</li>
+ </ul>
+ </div>
+
+ {logged ? (
+ <div className="flex gap-[12px]">
+ <button
+ onClick={() => handleAction('approve')}
+ disabled={submitting}
+ className="flex-1 bg-[#612BD3] hover:bg-[#7B3FF2] disabled:opacity-50 text-white rounded-[8px] py-[10px] px-[16px] text-[14px] font-semibold transition-colors"
+ >
+ Authorize
+ </button>
+ <button
+ onClick={() => handleAction('deny')}
+ disabled={submitting}
+ className="flex-1 bg-[#2A2929] hover:bg-[#3A3939] disabled:opacity-50 text-white rounded-[8px] py-[10px] px-[16px] text-[14px] font-semibold transition-colors"
+ >
+ Deny
+ </button>
+ </div>
+ ) : (
+ <button
+ onClick={signIn}
+ className="bg-[#612BD3] hover:bg-[#7B3FF2] text-white rounded-[8px] py-[10px] px-[16px] text-[14px] font-semibold transition-colors"
+ >
+ Sign in to Postiz
+ </button>
+ )}
+
+ {!!appInfo.selfHosted && (
+ <button
+ onClick={() => setSelfHosted(true)}
+ disabled={submitting}
+ className="text-[14px] text-gray-400 hover:text-white disabled:opacity-50 transition-colors"
+ >
+ Use self-hosted
+ </button>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/apps/frontend/src/components/oauth/self.hosted.component.tsx b/apps/frontend/src/components/oauth/self.hosted.component.tsx
new file mode 100644
index 000000000..97c0f92ec
--- /dev/null
+++ b/apps/frontend/src/components/oauth/self.hosted.component.tsx
@@ -0,0 +1,166 @@
+'use client';
+
+import { FC, FormEvent, useCallback, useState } from 'react';
+import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
+import { Input } from '@gitroom/react/form/input';
+
+export const OAuthSelfHosted: FC<{
+ appName: string;
+ // clients that read the email from userinfo (ChatGPT) need one
+ askEmail: boolean;
+ params: {
+ client_id: string | null;
+ state: string | null;
+ redirect_uri: string | null;
+ code_challenge: string | null;
+ code_challenge_method: string | null;
+ resource: string | null;
+ };
+ onBack: () => void;
+}> = ({ appName, askEmail, params, onBack }) => {
+ const fetch = useFetch();
+ const [instanceUrl, setInstanceUrl] = useState('');
+ const [apiKey, setApiKey] = useState('');
+ const [email, setEmail] = useState('');
+ const [error, setError] = useState('');
+ const [submitting, setSubmitting] = useState(false);
+
+ const connect = useCallback(
+ async (e: FormEvent) => {
+ e.preventDefault();
+ setSubmitting(true);
+ setError('');
+ try {
+ const response = await fetch('/oauth/authorize/self-hosted', {
+ method: 'POST',
+ body: JSON.stringify({
+ client_id: params.client_id,
+ state: params.state,
+ ...(params.redirect_uri
+ ? { redirect_uri: params.redirect_uri }
+ : {}),
+ ...(params.code_challenge
+ ? { code_challenge: params.code_challenge }
+ : {}),
+ ...(params.code_challenge_method
+ ? { code_challenge_method: params.code_challenge_method }
+ : {}),
+ ...(params.resource ? { resource: params.resource } : {}),
+ instance_url: instanceUrl.trim(),
+ ...(apiKey.trim() ? { api_key: apiKey.trim() } : {}),
+ ...(askEmail && email.trim() ? { email: email.trim() } : {}),
+ }),
+ });
+ const data = await response.json();
+ if (data.redirect) {
+ window.location.href = data.redirect;
+ return;
+ }
+
+ setError(
+ response.status === 429
+ ? 'Too many attempts, try again later'
+ : (Array.isArray(data.message) ? data.message[0] : data.message) ||
+ 'Could not connect to your instance'
+ );
+ } catch {
+ setError('Could not connect to your instance');
+ }
+ setSubmitting(false);
+ },
+ [params, instanceUrl, apiKey, email, askEmail]
+ );
+
+ return (
+ <form
+ onSubmit={connect}
+ className="border-t border-[#2A2929] pt-[16px] flex flex-col gap-[16px]"
+ >
+ <div className="flex flex-col gap-[4px]">
+ <div className="text-[16px] font-semibold">Use self-hosted</div>
+ <div className="text-[14px] text-gray-400">
+ {appName} will work with your own Postiz instance. Postiz Cloud
+ relays its requests, and your API key is stored encrypted.
+ </div>
+ </div>
+
+ {/* plain text fields: a password field makes browsers autofill the
+ saved Postiz login (email + password) into this form */}
+ <Input
+ name="instance_url"
+ label="Instance URL"
+ disableForm={true}
+ removeError={true}
+ value={instanceUrl}
+ onChange={(e) => setInstanceUrl(e.target.value)}
+ placeholder="https://postiz.example.com"
+ inputMode="url"
+ autoComplete="off"
+ spellCheck={false}
+ />
+
+ <div className="flex flex-col gap-[6px]">
+ <Input
+ name="api_key"
+ label="API key"
+ disableForm={true}
+ removeError={true}
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ placeholder="Settings > Developers on your instance"
+ autoComplete="off"
+ spellCheck={false}
+ />
+ <div className="text-[12px] text-gray-400">
+ You can also paste the MCP URL from Settings &gt; Developers in the
+ Instance URL, it includes the key.
+ </div>
+ </div>
+
+ {askEmail && (
+ <div className="flex flex-col gap-[6px]">
+ <Input
+ name="email"
+ label="Email"
+ type="email"
+ disableForm={true}
+ removeError={true}
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ placeholder="[email protected]"
+ autoComplete="email"
+ />
+ <div className="text-[12px] text-gray-400">
+ {appName} uses it to identify your account.
+ </div>
+ </div>
+ )}
+
+ {!!error && <div className="text-[14px] text-red-400">{error}</div>}
+
+ <div className="flex gap-[12px]">
+ <button
+ type="submit"
+ disabled={
+ submitting || !instanceUrl.trim() || (askEmail && !email.trim())
+ }
+ className="flex-1 bg-[#612BD3] hover:bg-[#7B3FF2] disabled:opacity-50 text-white rounded-[8px] py-[10px] px-[16px] text-[14px] font-semibold transition-colors"
+ >
+ {submitting ? 'Connecting...' : 'Connect'}
+ </button>
+ <button
+ type="button"
+ onClick={onBack}
+ disabled={submitting}
+ className="flex-1 bg-[#2A2929] hover:bg-[#3A3939] disabled:opacity-50 text-white rounded-[8px] py-[10px] px-[16px] text-[14px] font-semibold transition-colors"
+ >
+ Back
+ </button>
+ </div>
+
+ <div className="text-[12px] text-gray-400 text-center">
+ Your instance has to be reachable from the internet over https.
+ </div>
+ </form>
+ );
+};
diff --git a/apps/frontend/src/components/onboarding/onboarding.modal.tsx b/apps/frontend/src/components/onboarding/onboarding.modal.tsx
index e5b81009f..619e7cb95 100644
--- a/apps/frontend/src/components/onboarding/onboarding.modal.tsx
+++ b/apps/frontend/src/components/onboarding/onboarding.modal.tsx
@@ -16,6 +16,7 @@ import {
CopyButton,
getMcpConfig,
isChatOnlyMcpClient,
+ isSelfHosted,
localCliSteps,
McpAuth,
McpClient,
@@ -293,6 +294,8 @@ const OnboardingStep2: FC<{ onBack: () => void; onNext: () => void }> = ({
const mcpBase = mcpUrl || backendUrl;
const apiKey = user?.publicApi || '';
const available = !!apiKey && !!user?.tier?.public_api;
+ // the official connectors work for self-hosted installs too
+ const officialConnectors = billingEnabled || isSelfHosted;
const { config, hint } =
agent === apiTab
@@ -308,22 +311,22 @@ const OnboardingStep2: FC<{ onBack: () => void; onNext: () => void }> = ({
);
const connector =
- agent === 'Claude' && billingEnabled
+ agent === 'Claude' && officialConnectors
? {
href: mcpConnectorUrls.Claude,
label: t('add_to_claude', 'Add to Claude'),
}
- : agent === 'ChatGPT' && billingEnabled
+ : agent === 'ChatGPT' && officialConnectors
? {
href: mcpConnectorUrls.ChatGPT,
label: t('add_to_chatgpt', 'Add to ChatGPT'),
}
- : agent === 'Cursor' && billingEnabled
+ : agent === 'Cursor' && officialConnectors
? {
href: mcpConnectorUrls.Cursor,
label: t('add_to_cursor', 'Add to Cursor'),
}
- : agent === 'Grok Bot' && billingEnabled
+ : agent === 'Grok Bot' && officialConnectors
? {
href: mcpConnectorUrls['Grok Bot'],
label: t('add_to_grok_bot', 'Add to Grok Bot'),
@@ -435,10 +438,16 @@ const OnboardingStep2: FC<{ onBack: () => void; onNext: () => void }> = ({
{t('connector', 'Connector')}
</div>
<div className="text-[13px] text-customColor18 mt-[2px]">
- {t(
- 'connector_onboarding_description',
- 'The fastest way: add Postiz with one click, you will be asked to sign in'
- )}
+ {isSelfHosted
+ ? t(
+ 'connector_self_hosted_description',
+ 'The official connector works with self-hosted Postiz too. When asked to sign in, choose "Use self-hosted" and enter {{url}} with your API key.',
+ { url: mcpBase, interpolation: { escapeValue: false } }
+ )
+ : t(
+ 'connector_onboarding_description',
+ 'The fastest way: add Postiz with one click, you will be asked to sign in'
+ )}
</div>
</div>
<a
diff --git a/apps/frontend/src/components/public-api/public.component.tsx b/apps/frontend/src/components/public-api/public.component.tsx
index 2378eb646..43c9a27d5 100644
--- a/apps/frontend/src/components/public-api/public.component.tsx
+++ b/apps/frontend/src/components/public-api/public.component.tsx
@@ -21,8 +21,9 @@ export const remoteMcpClients = {
'In ChatGPT go to Settings > Connectors > Create and paste this URL.',
} as const;
-// Official one-click connectors listed in the assistants' directories.
-// Only for the hosted Postiz (billingEnabled), they point at the public MCP server.
+// Official one-click connectors listed in the assistants' directories, they
+// point at the public MCP server: the hosted Postiz (billingEnabled), or a
+// self-hosted install through "Use self-hosted" on its sign-in page.
export const mcpConnectorUrls = {
Claude: 'https://claude.ai/directory/postiz',
ChatGPT:
@@ -61,6 +62,17 @@ export type AnyMcpClient = RemoteMcpClient | ChatOnlyMcpClient | McpClient;
// apikey: the organization API key, as a Bearer header (or inside the URL for remote clients)
export type McpAuth = 'oauth' | 'apikey';
+// Only the self-hosted docker images are built with a version
+export const isSelfHosted = !!process.env.NEXT_PUBLIC_VERSION;
+
+// The directory listings behind the "Official connector" tab
+const officialConnectorClients = [
+ 'Claude',
+ 'ChatGPT',
+ 'Cursor',
+ 'Grok Bot',
+] as const;
+
export const getMcpOauthUrl = (mcpBase: string) =>
`${mcpBase}/mcp-oauth-dynamic`;
@@ -305,7 +317,13 @@ const McpSection = ({
const t = useT();
const { billingEnabled } = useVariables();
const [activeClient, setActiveClient] = useState<AnyMcpClient>('Claude');
- const [auth, setAuth] = useState<McpAuth>('oauth');
+ const officialConnectors = billingEnabled || isSelfHosted;
+ // the directory connectors come first wherever they work
+ const tabs: Array<'official' | McpAuth> = officialConnectors
+ ? ['official', 'oauth', 'apikey']
+ : ['oauth', 'apikey'];
+ const [tab, setTab] = useState(tabs[0]);
+ const auth: McpAuth = tab === 'apikey' ? 'apikey' : 'oauth';
const [revealed, setRevealed] = useState(false);
const { config, hint } = getMcpConfig(
@@ -342,7 +360,7 @@ const McpSection = ({
</div>
</div>
<div className="flex flex-wrap gap-[6px] shrink-0 pt-[2px]">
- {billingEnabled && (
+ {officialConnectors && (
<>
<a
className="cursor-pointer px-[16px] h-[36px] bg-[#612BD3] hover:bg-[#5520CB] text-white transition-colors rounded-[8px] text-[13px] font-[600] flex items-center gap-[6px]"
@@ -373,25 +391,27 @@ const McpSection = ({
</div>
</div>
<div className="p-[20px] mobile:p-[14px] flex flex-col gap-[16px]">
- {!chatOnly && (
+ {(tab === 'official' || !chatOnly) && (
<div className="flex flex-col gap-[6px]">
<div className="text-[13px] font-[600] text-customColor18">
{t('auth_method', 'Authentication')}
</div>
- <div className="flex gap-[6px]">
- {(['oauth', 'apikey'] as const).map((m) => (
+ <div className="flex flex-wrap gap-[6px]">
+ {tabs.map((m) => (
<button
key={m}
type="button"
className={clsx(
'cursor-pointer px-[14px] h-[36px] text-[13px] font-[500] rounded-[8px] transition-colors',
- auth === m
+ tab === m
? 'bg-[#612BD3] text-white'
: 'bg-btnSimple text-customColor18 hover:bg-boxHover hover:text-textColor'
)}
- onClick={() => setAuth(m)}
+ onClick={() => setTab(m)}
>
- {m === 'oauth'
+ {m === 'official'
+ ? t('official_connector', 'Official connector')
+ : m === 'oauth'
? t('sign_in_no_api_key', 'Sign in with Postiz (no API key)')
: t('api_key', 'API Key')}
</button>
@@ -399,6 +419,42 @@ const McpSection = ({
</div>
</div>
)}
+ {tab === 'official' ? (
+ <div className="flex flex-col gap-[8px]">
+ <div className="text-[12px] text-customColor18 font-[500]">
+ {isSelfHosted
+ ? t(
+ 'connector_self_hosted_description',
+ 'The official connector works with self-hosted Postiz too. When asked to sign in, choose "Use self-hosted" and enter {{url}} with your API key.',
+ { url: mcpBase, interpolation: { escapeValue: false } }
+ )
+ : t(
+ 'connector_onboarding_description',
+ 'The fastest way: add Postiz with one click, you will be asked to sign in'
+ )}
+ </div>
+ <div className="flex flex-wrap gap-[8px]">
+ {officialConnectorClients.map((client) => (
+ <a
+ key={client}
+ className="cursor-pointer px-[16px] h-[36px] bg-[#612BD3] hover:bg-[#5520CB] text-white transition-colors rounded-[8px] text-[13px] font-[600] flex items-center gap-[8px]"
+ href={mcpConnectorUrls[client]}
+ target="_blank"
+ >
+ <McpClientIcon client={client} />
+ {client === 'Claude'
+ ? t('add_to_claude', 'Add to Claude')
+ : client === 'ChatGPT'
+ ? t('add_to_chatgpt', 'Add to ChatGPT')
+ : client === 'Cursor'
+ ? t('add_to_cursor', 'Add to Cursor')
+ : t('add_to_grok_bot', 'Add to Grok Bot')}
+ </a>
+ ))}
+ </div>
+ </div>
+ ) : (
+ <>
<div className="flex flex-col gap-[6px]">
<div className="text-[13px] font-[600] text-customColor18">
{t('mcp_client', 'Client')}
@@ -478,7 +534,7 @@ const McpSection = ({
{!isRemoteMcpClient(activeClient) && !chatOnly && (
<CopyButton text={baseUrl} label={t('copy_url', 'Copy URL')} />
)}
- {activeClient === 'Claude' && billingEnabled && (
+ {activeClient === 'Claude' && officialConnectors && (
<a
className="cursor-pointer px-[16px] h-[36px] bg-[#612BD3] hover:bg-[#5520CB] text-white transition-colors rounded-[8px] text-[13px] font-[600] flex items-center gap-[6px]"
href={mcpConnectorUrls.Claude}
@@ -488,7 +544,7 @@ const McpSection = ({
{t('add_to_claude', 'Add to Claude')}
</a>
)}
- {activeClient === 'ChatGPT' && billingEnabled && (
+ {activeClient === 'ChatGPT' && officialConnectors && (
<a
className="cursor-pointer px-[16px] h-[36px] bg-[#612BD3] hover:bg-[#5520CB] text-white transition-colors rounded-[8px] text-[13px] font-[600] flex items-center gap-[6px]"
href={mcpConnectorUrls.ChatGPT}
@@ -498,7 +554,7 @@ const McpSection = ({
{t('add_to_chatgpt', 'Add to ChatGPT')}
</a>
)}
- {activeClient === 'Grok Bot' && billingEnabled && (
+ {activeClient === 'Grok Bot' && officialConnectors && (
<a
className="cursor-pointer px-[16px] h-[36px] bg-[#612BD3] hover:bg-[#5520CB] text-white transition-colors rounded-[8px] text-[13px] font-[600] flex items-center gap-[6px]"
href={mcpConnectorUrls['Grok Bot']}
@@ -510,6 +566,8 @@ const McpSection = ({
)}
</div>
</div>
+ </>
+ )}
</div>
</div>
);
diff --git a/apps/frontend/src/proxy.ts b/apps/frontend/src/proxy.ts
index 360c937e3..74dcd310d 100644
--- a/apps/frontend/src/proxy.ts
+++ b/apps/frontend/src/proxy.ts
@@ -47,7 +47,10 @@ export async function proxy(request: NextRequest) {
nextUrl.pathname.startsWith('/uploads/') ||
nextUrl.pathname.startsWith('/p/') ||
nextUrl.pathname.startsWith('/provider/') ||
- nextUrl.pathname.startsWith('/icons/')
+ nextUrl.pathname.startsWith('/icons/') ||
+ // the consent screen of MCP / OAuth clients handles signed-out visitors
+ // itself (sign in and come back, or connect a self-hosted instance)
+ nextUrl.pathname.startsWith('/oauth/authorize')
) {
return topResponse;
}
diff --git a/i18n.lock b/i18n.lock
index d72791c37..1f9a81b9d 100644
--- a/i18n.lock
+++ b/i18n.lock
@@ -730,6 +730,8 @@ checksums:
chat_onboarding_description: 9da74037342cd6adb283e8205299b986
connector: 7abb5584501ce0e3cc51ba19f0561ca8
connector_onboarding_description: eb8027296b46bf58475f6b4925bd6351
+ official_connector: cdaaab2f023cb2eaea40b666e9859442
+ connector_self_hosted_description: c966620ed2df1d6ffeaa92969aaf30a6
mcp_onboarding_description: 5b33036d174222d86ac50039a3a31724
cli_onboarding_description: b4aba065e5a8410ee2c365ee4d7aa87c
agent_settings_later: bbdd45a80cc5218809363348e0b03a32
diff --git a/libraries/nestjs-libraries/src/chat/async.storage.ts b/libraries/nestjs-libraries/src/chat/async.storage.ts
index fff383ff1..bffed1f97 100644
--- a/libraries/nestjs-libraries/src/chat/async.storage.ts
+++ b/libraries/nestjs-libraries/src/chat/async.storage.ts
@@ -1,9 +1,12 @@
// context.ts
import { AsyncLocalStorage } from 'node:async_hooks';
+import type { SelfHostedInstance } from '@gitroom/nestjs-libraries/chat/mcp.relay.service';
type Ctx = {
requestId: string;
auth: any; // replace with your org type if you have it, e.g. Organization
+ // a self-hosted connection: where its tool calls are relayed to
+ relay?: SelfHostedInstance & { id: string };
};
const als = new AsyncLocalStorage<Ctx>();
@@ -22,4 +25,8 @@ export function getAuth<T = any>(): T | undefined {
export function getRequestId(): string | undefined {
return als.getStore()?.requestId;
+}
+
+export function getRelay(): Ctx['relay'] {
+ return als.getStore()?.relay;
}
\ No newline at end of file
diff --git a/libraries/nestjs-libraries/src/chat/chat.module.ts b/libraries/nestjs-libraries/src/chat/chat.module.ts
index ed5cc62da..87f1b0ec1 100644
--- a/libraries/nestjs-libraries/src/chat/chat.module.ts
+++ b/libraries/nestjs-libraries/src/chat/chat.module.ts
@@ -2,10 +2,11 @@ import { Global, Module } from '@nestjs/common';
import { LoadToolsService } from '@gitroom/nestjs-libraries/chat/load.tools.service';
import { MastraService } from '@gitroom/nestjs-libraries/chat/mastra.service';
import { toolList } from '@gitroom/nestjs-libraries/chat/tools/tool.list';
+import { McpRelayService } from '@gitroom/nestjs-libraries/chat/mcp.relay.service';
@Global()
@Module({
- providers: [MastraService, LoadToolsService, ...toolList],
+ providers: [MastraService, LoadToolsService, McpRelayService, ...toolList],
get exports() {
return this.providers;
},
diff --git a/libraries/nestjs-libraries/src/chat/mcp.relay.service.ts b/libraries/nestjs-libraries/src/chat/mcp.relay.service.ts
new file mode 100644
index 000000000..7cb0bd0a9
--- /dev/null
+++ b/libraries/nestjs-libraries/src/chat/mcp.relay.service.ts
@@ -0,0 +1,358 @@
+import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
+import { createTool } from '@mastra/core/tools';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import {
+ StreamableHTTPClientTransport,
+ StreamableHTTPError,
+} from '@modelcontextprotocol/sdk/client/streamableHttp.js';
+import {
+ CallToolResult,
+ ErrorCode,
+ McpError,
+} from '@modelcontextprotocol/sdk/types.js';
+import { getRelay } from '@gitroom/nestjs-libraries/chat/async.storage';
+import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
+import { isSafePublicHttpsUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
+import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
+import { LoadToolsService } from '@gitroom/nestjs-libraries/chat/load.tools.service';
+
+export interface SelfHostedInstance {
+ mcpUrl: string;
+ apiKey: string;
+}
+
+// Every Postiz MCP server since v2.19.0 (the first one with the API key /mcp
+// route) has these; a server without them is not a Postiz instance
+const requiredTools = ['integrationList', 'integrationSchedulePostTool'];
+
+// Tool results are small JSON, an instance never needs this server to hold
+// more than this in memory
+const maxResponseBytes = 10 * 1024 * 1024;
+
+// The address comes from a public endpoint: the pinned-DNS SSRF guard stays
+// on whatever DISABLE_SSRF_PROTECTION says, no redirects and a cap on the body
+const instanceFetch = async (url: string | URL, init?: RequestInit) => {
+ const response = await fetch(url, {
+ ...init,
+ redirect: 'error',
+ // @ts-ignore - undici option, not in lib.dom fetch types
+ dispatcher: ssrfSafeDispatcher,
+ });
+
+ if (Number(response.headers.get('content-length')) > maxResponseBytes) {
+ await response.body?.cancel();
+ throw new Error('The response of the instance is too large');
+ }
+ if (!response.body) {
+ return response;
+ }
+
+ let received = 0;
+ const capped = response.body.pipeThrough(
+ new TransformStream<Uint8Array, Uint8Array>({
+ transform(chunk, controller) {
+ received += chunk.byteLength;
+ if (received > maxResponseBytes) {
+ controller.error(
+ new Error('The response of the instance is too large')
+ );
+ return;
+ }
+ controller.enqueue(chunk);
+ },
+ })
+ );
+
+ return new Response(capped, {
+ status: response.status,
+ statusText: response.statusText,
+ headers: response.headers,
+ });
+};
+
+// Postiz Cloud relays the MCP connection of a self-hosted Postiz: the person
+// brings the instance and its API key on the consent screen ("Use
+// self-hosted"), and the tool calls of that connection run on the instance
+@Injectable()
+export class McpRelayService {
+ constructor(
+ private _oauthService: OAuthService,
+ private _loadToolsService: LoadToolsService
+ ) {}
+
+ // Turns what the person typed on the consent screen into the MCP endpoint
+ // of their instance, and checks that the API key works there
+ async connect(
+ instanceUrl: string,
+ apiKey?: string
+ ): Promise<SelfHostedInstance> {
+ const value = instanceUrl.trim();
+ let url: URL;
+ try {
+ url = new URL(
+ /^[a-z][a-z0-9+.-]*:\/\//i.test(value) ? value : `https://${value}`
+ );
+ } catch {
+ throw new HttpException(
+ 'Enter the address of your Postiz instance, for example https://postiz.example.com',
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ // An address with credentials (an email like [email protected] reads as
+ // user "me" on company.com) is never sent anywhere
+ if (url.username || url.password) {
+ throw new HttpException(
+ 'Enter the address of your Postiz instance, for example https://postiz.example.com',
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ // The MCP URL from Settings > Developers carries the API key:
+ // <backend>/mcp/<key>
+ const fromSettings = url.pathname.match(/^(.*?)\/mcp\/([^/]+)\/?$/);
+ const key =
+ apiKey?.trim() || (fromSettings && decodeURIComponent(fromSettings[2]));
+ if (!key) {
+ throw new HttpException(
+ 'Enter the API key of your Postiz instance',
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ if (!(await isSafePublicHttpsUrl(url.origin))) {
+ throw new HttpException(
+ 'Your Postiz instance must be reachable from the internet over https',
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ // The docker image serves the backend under /api of the same domain,
+ // a backend on its own domain answers on /mcp
+ const path = (fromSettings ? fromSettings[1] : url.pathname)
+ .replace(/\/+$/, '')
+ .replace(/\/mcp$/, '');
+ const candidates = path.endsWith('/api')
+ ? [`${url.origin}${path}/mcp`]
+ : [`${url.origin}${path}/api/mcp`, `${url.origin}${path}/mcp`];
+
+ for (const mcpUrl of candidates) {
+ let tools: string[];
+ try {
+ tools = await this.withClient({ mcpUrl, apiKey: key }, async (client) =>
+ (await client.listTools(undefined, { timeout: 10000 })).tools.map(
+ (tool) => tool.name
+ )
+ );
+ } catch (err) {
+ if (err instanceof StreamableHTTPError && err.code === 401) {
+ throw new HttpException(
+ 'Your Postiz instance rejected this API key',
+ HttpStatus.BAD_REQUEST
+ );
+ }
+ if (err instanceof StreamableHTTPError && err.code === 403) {
+ throw new HttpException(
+ 'Your Postiz instance refused the connection (403), make sure nothing in front of it blocks requests from Postiz Cloud',
+ HttpStatus.BAD_REQUEST
+ );
+ }
+ // nothing that speaks MCP at this address, try the next one
+ continue;
+ }
+
+ if (!requiredTools.every((name) => tools.includes(name))) {
+ throw new HttpException(
+ `${url.origin} does not look like a Postiz instance, or it runs a version older than v2.19.0`,
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ // Every tool this server lists has to run on the instance, an older one
+ // would answer some calls with errors
+ const missing = Object.keys(await this._loadToolsService.loadTools()).filter(
+ (name) => !tools.includes(name)
+ );
+ if (missing.length) {
+ throw new HttpException(
+ `Your Postiz instance is missing tools this connection needs (${missing.join(', ')}). Update it to the latest Postiz version and connect again`,
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ return { mcpUrl, apiKey: key };
+ }
+
+ throw new HttpException(
+ `Could not find a Postiz MCP server at ${url.origin}. Paste the MCP URL from Settings > Developers of your instance, and make sure it runs Postiz v2.19.0 or newer`,
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ // The same definitions this server serves everyone (the listing stays the
+ // reviewed one, and nothing an instance returns ends up in a description),
+ // run by the instance. Pass tools without ui:// widgets - those upload to
+ // this server - and _meta (a tool's widget link) is dropped too
+ tools(source: Record<string, any>) {
+ return Object.fromEntries(
+ Object.entries(source).map(([name, tool]) => [
+ name,
+ createTool({
+ id: tool.id,
+ description: tool.description,
+ inputSchema: tool.inputSchema,
+ outputSchema: tool.outputSchema,
+ mcp: { annotations: tool.mcp?.annotations },
+ execute: async (inputData: Record<string, unknown>, context: any) => {
+ const instance = getRelay();
+ if (!instance) {
+ throw new Error(
+ 'This connection is not linked to a self-hosted instance'
+ );
+ }
+
+ const result = await this.callTool(
+ instance,
+ name,
+ inputData,
+ context?.mcp?.extra?.signal
+ );
+ const text = this.text(result);
+ if (!tool.outputSchema) {
+ return text;
+ }
+
+ // The structured result is what the outputSchema describes;
+ // instances whose tool had no outputSchema yet answer with JSON text
+ let output: unknown = result.structuredContent;
+ if (output === undefined) {
+ try {
+ output = JSON.parse(text);
+ } catch {
+ throw new Error(
+ text ||
+ `${name} returned an unexpected answer from your Postiz instance`
+ );
+ }
+ }
+
+ // an instance on another Postiz version can answer in another shape
+ const check = await tool.outputSchema['~standard']?.validate(output);
+ if (check?.issues) {
+ throw new Error(
+ `Your Postiz instance answered ${name} in a format this connection does not know, update the instance to the latest Postiz version`
+ );
+ }
+
+ return output;
+ },
+ }),
+ ])
+ );
+ }
+
+ async callTool(
+ instance: SelfHostedInstance & { id?: string },
+ name: string,
+ args: Record<string, unknown>,
+ signal?: AbortSignal
+ ) {
+ let result: CallToolResult;
+ try {
+ result = (await this.withClient(instance, (client) =>
+ client.callTool({ name, arguments: args }, undefined, {
+ signal,
+ // under the 100 seconds Cloudflare gives a request to the MCP host
+ timeout: 90000,
+ })
+ )) as CallToolResult;
+ } catch (err) {
+ // The key was rotated (or the instance reset): the connection can never
+ // work again, so it goes away and the client asks to connect again
+ if (err instanceof StreamableHTTPError && err.code === 401 && instance.id) {
+ await this._oauthService.deleteSelfHostedAuthorization(instance.id);
+ }
+ throw new Error(this.describeError(instance, name, err));
+ }
+
+ if (result.isError) {
+ const text = this.text(result);
+ // an instance older than this server doesn't have every tool yet
+ if (text.startsWith('Unknown tool:')) {
+ throw new Error(
+ `Your Postiz instance does not have ${name} yet, update it to the latest Postiz version to use it`
+ );
+ }
+ // arguments this server validated but an older instance doesn't accept
+ if (text.startsWith('Tool validation failed')) {
+ throw new Error(
+ `Your Postiz instance runs an older version of ${name}, update it to the latest Postiz version to use it`
+ );
+ }
+ throw new Error(text || `${name} failed on your Postiz instance`);
+ }
+
+ return result;
+ }
+
+ private async withClient<T>(
+ instance: SelfHostedInstance,
+ run: (client: Client) => Promise<T>
+ ) {
+ const transport = new StreamableHTTPClientTransport(
+ new URL(instance.mcpUrl),
+ {
+ requestInit: {
+ headers: { Authorization: `Bearer ${instance.apiKey}` },
+ },
+ fetch: instanceFetch,
+ }
+ );
+ const client = new Client({ name: 'Postiz Cloud', version: '1.0.0' });
+
+ try {
+ await client.connect(transport, { timeout: 10000 });
+ return await run(client);
+ } finally {
+ // instances older than v2.23.0 keep a session per connection, end it
+ // so relayed calls don't pile them up
+ if (transport.sessionId) {
+ await transport.terminateSession().catch(() => {});
+ }
+ await client.close().catch(() => {});
+ }
+ }
+
+ private text(result: CallToolResult) {
+ return (result.content || [])
+ .filter((part) => part.type === 'text')
+ .map((part) => (part as { text: string }).text)
+ .join('\n')
+ .trim();
+ }
+
+ // What the model (and so the person) reads when the instance can't run a
+ // tool - it has to say what to do next
+ private describeError(
+ instance: SelfHostedInstance,
+ name: string,
+ err: unknown
+ ) {
+ const origin = new URL(instance.mcpUrl).origin;
+ if (err instanceof StreamableHTTPError && err.code === 401) {
+ return `Your Postiz instance (${origin}) rejected the saved API key, it was probably rotated, so this connection was removed. Connect Postiz again to keep using your instance`;
+ }
+ if (err instanceof StreamableHTTPError && err.code === 403) {
+ return `Your Postiz instance (${origin}) refused the request (403), make sure nothing in front of it blocks requests from Postiz Cloud`;
+ }
+ if (err instanceof McpError && err.code === ErrorCode.RequestTimeout) {
+ return `Your Postiz instance (${origin}) did not answer ${name} in time`;
+ }
+ if (err instanceof McpError) {
+ return `Your Postiz instance (${origin}) could not run ${name}: ${err.message}`;
+ }
+ return `Could not reach your Postiz instance (${origin}): ${
+ err instanceof Error ? err.message : String(err)
+ }. Make sure it is online and reachable from the internet`;
+ }
+}
diff --git a/libraries/nestjs-libraries/src/chat/start.mcp.ts b/libraries/nestjs-libraries/src/chat/start.mcp.ts
index 7dfb2ff47..b96c75d8a 100644
--- a/libraries/nestjs-libraries/src/chat/start.mcp.ts
+++ b/libraries/nestjs-libraries/src/chat/start.mcp.ts
@@ -4,12 +4,16 @@ import { MastraService } from '@gitroom/nestjs-libraries/chat/mastra.service';
import { LoadToolsService } from '@gitroom/nestjs-libraries/chat/load.tools.service';
import { MCPServer } from '@mastra/mcp';
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
-import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
+import {
+ OAuthService,
+ selfHostedRelayEnabled,
+} from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
import { runWithContext } from './async.storage';
import { createOAuthMiddleware } from './oauth-middleware';
import { UPLOAD_WIDGET_URI, uploadWidgetHtml } from '@gitroom/nestjs-libraries/chat/ui/upload.widget';
import { CLIPPING_WIDGET_URI, clippingWidgetHtml } from '@gitroom/nestjs-libraries/chat/ui/clipping.widget';
import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
+import { McpRelayService } from '@gitroom/nestjs-libraries/chat/mcp.relay.service';
const fixAcceptHeader = (req: Request) => {
const value = 'application/json, text/event-stream';
req.headers.accept = value;
@@ -34,6 +38,7 @@ export const startMcp = async (app: INestApplication) => {
const organizationService = app.get(OrganizationService, { strict: false });
const oauthService = app.get(OAuthService, { strict: false });
const loadToolsService = app.get(LoadToolsService, { strict: false });
+ const mcpRelayService = app.get(McpRelayService, { strict: false });
const resolveAuth = async (token: string) => {
if (token.startsWith('pos_')) {
@@ -44,10 +49,15 @@ export const startMcp = async (app: INestApplication) => {
return organizationService.getOrgByApiKey(token);
};
+ // psh_ tokens: a self-hosted Postiz this server relays to (McpRelayService)
+ const resolveSelfHosted = (token: string) =>
+ oauthService.getSelfHostedByAccessToken(token);
+
const mastra = await mastraService.mastra();
const agent = mastra.getAgent('postiz');
+ const agentTools = await agent.listTools();
const tools = {
- ...(await agent.listTools()),
+ ...agentTools,
// tools that only make sense inside an MCP host (ui:// widgets)
...(await loadToolsService.loadTools(true)),
};
@@ -66,9 +76,11 @@ export const startMcp = async (app: INestApplication) => {
'clippingStatusTool',
'clippingWidgetTicketTool',
];
- const claudeTools = Object.fromEntries(
- Object.entries(tools).filter(([name]) => !claudeHiddenTools.includes(name))
- ) as typeof tools;
+ const withoutClaudeHidden = <T extends Record<string, unknown>>(source: T) =>
+ Object.fromEntries(
+ Object.entries(source).filter(([name]) => !claudeHiddenTools.includes(name))
+ ) as T;
+ const claudeTools = withoutClaudeHidden(tools);
const backendUrl = process.env.NEXT_PUBLIC_OVERRIDE_BACKEND_URL || process.env.NEXT_PUBLIC_BACKEND_URL;
// this runs before the backend listens: a bucket url that doesn't parse only
@@ -143,6 +155,24 @@ export const startMcp = async (app: INestApplication) => {
appResources: claudeAppResources,
});
+ // Self-hosted connections, built from the agent tools so the ui:// widgets
+ // (which upload to this server) are left out
+ let selfHostedServer: MCPServer | undefined;
+ let claudeSelfHostedServer: MCPServer | undefined;
+ if (selfHostedRelayEnabled()) {
+ const selfHostedTools = mcpRelayService.tools(agentTools);
+ selfHostedServer = new MCPServer({
+ name: 'Postiz MCP',
+ version: '1.0.0',
+ tools: selfHostedTools,
+ });
+ claudeSelfHostedServer = new MCPServer({
+ name: 'Postiz MCP',
+ version: '1.0.0',
+ tools: withoutClaudeHidden(selfHostedTools),
+ });
+ }
+
// Two RFC 8414 path-based issuers backed by the same endpoints and code.
// /mcp-oauth-chatgpt is what the ChatGPT app submission points at: it does
// not advertise a registration_endpoint, so the OpenAI builder defaults to
@@ -190,7 +220,9 @@ export const startMcp = async (app: INestApplication) => {
authorizationServers: [authorizationServers[authorizationServer].issuer],
scopesSupported: oauthScopes,
validateToken: async (token: string) => {
- const org = await resolveAuth(token);
+ const org = token.startsWith('psh_')
+ ? await resolveSelfHosted(token)
+ : await resolveAuth(token);
if (!org) {
return { valid: false, error: 'invalid_token', errorDescription: 'Invalid API Key or OAuth token' };
}
@@ -202,17 +234,21 @@ export const startMcp = async (app: INestApplication) => {
const oauthResources: Record<
string,
- { middleware: ReturnType<typeof createOAuthMiddleware>; mcpServer: MCPServer }
+ {
+ middleware: ReturnType<typeof createOAuthMiddleware>;
+ mcpServer: MCPServer;
+ selfHostedServer?: MCPServer;
+ }
> = {
// ChatGPT app submission (pre-defined client credentials, no DCR)
- '/mcp-oauth-chatgpt': { middleware: createResourceMiddleware('/mcp-oauth-chatgpt', '/mcp-oauth-chatgpt'), mcpServer: oauthServer },
+ '/mcp-oauth-chatgpt': { middleware: createResourceMiddleware('/mcp-oauth-chatgpt', '/mcp-oauth-chatgpt'), mcpServer: oauthServer, selfHostedServer },
// Former ChatGPT path, kept for connectors that were created against it
- '/mcp-oauth': { middleware: createResourceMiddleware('/mcp-oauth', '/mcp-oauth-dynamic'), mcpServer: oauthServer },
+ '/mcp-oauth': { middleware: createResourceMiddleware('/mcp-oauth', '/mcp-oauth-dynamic'), mcpServer: oauthServer, selfHostedServer },
// Claude connector directory submission
- '/mcp-oauth-claude': { middleware: createResourceMiddleware('/mcp-oauth-claude', '/mcp-oauth-dynamic'), mcpServer: claudeOauthServer },
+ '/mcp-oauth-claude': { middleware: createResourceMiddleware('/mcp-oauth-claude', '/mcp-oauth-dynamic'), mcpServer: claudeOauthServer, selfHostedServer: claudeSelfHostedServer },
// Clients that register themselves through DCR (/oauth/register) - not
// directory-reviewed, so they get the full toolset (media generation included)
- '/mcp-oauth-dynamic': { middleware: createResourceMiddleware('/mcp-oauth-dynamic', '/mcp-oauth-dynamic'), mcpServer: oauthServer },
+ '/mcp-oauth-dynamic': { middleware: createResourceMiddleware('/mcp-oauth-dynamic', '/mcp-oauth-dynamic'), mcpServer: oauthServer, selfHostedServer },
};
if (process.env.OPENAI_APP_CHALLANGE) {
@@ -288,22 +324,25 @@ export const startMcp = async (app: INestApplication) => {
}
// baseUrl is the mount path that matched, e.g. /mcp-oauth-claude
- const { middleware, mcpServer } = oauthResources[req.baseUrl];
+ const { middleware, mcpServer, selfHostedServer } = oauthResources[req.baseUrl];
const url = new URL(req.baseUrl, process.env.NEXT_PUBLIC_BACKEND_URL);
const result = await middleware(req, res, url);
if (!result.proceed) return;
const token = result.tokenValidation?.subject;
- const auth = await resolveAuth(token!);
- if (!auth) {
+ // a self-hosted connection has no organization here
+ const selfHosted = token!.startsWith('psh_');
+ const relay = selfHosted ? await resolveSelfHosted(token!) : undefined;
+ const auth = selfHosted ? undefined : await resolveAuth(token!);
+ if (!auth && !(relay && selfHostedServer)) {
res.status(401).json({ error: 'invalid_token', error_description: 'Could not resolve organization' });
return;
}
fixAcceptHeader(req);
- await runWithContext({ requestId: token!, auth }, async () => {
- await mcpServer.startHTTP({
+ await runWithContext({ requestId: token!, auth, relay: relay || undefined }, async () => {
+ await (relay ? selfHostedServer! : mcpServer).startHTTP({
url: url,
httpPath: url.pathname,
options: {
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 e7fe30fcb..eb30f8f9a 100644
--- a/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.repository.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.repository.ts
@@ -5,7 +5,8 @@ import { PrismaRepository } from '@gitroom/nestjs-libraries/database/prisma/pris
export class OAuthRepository {
constructor(
private _oauthApp: PrismaRepository<'oAuthApp'>,
- private _oauthAuth: PrismaRepository<'oAuthAuthorization'>
+ private _oauthAuth: PrismaRepository<'oAuthAuthorization'>,
+ private _oauthSelfHosted: PrismaRepository<'oAuthSelfHostedAuthorization'>
) {}
getAppByOrgId(orgId: string) {
@@ -88,6 +89,7 @@ export class OAuthRepository {
dynamic: true,
createdAt: { lt: olderThan },
authorizations: { none: {} },
+ selfHostedAuthorizations: { none: {} },
},
});
}
@@ -294,7 +296,17 @@ export class OAuthRepository {
});
}
- revokeAllForApp(oauthAppId: string) {
+ async revokeAllForApp(oauthAppId: string) {
+ await this._oauthSelfHosted.model.oAuthSelfHostedAuthorization.updateMany({
+ where: {
+ oauthAppId,
+ revokedAt: null,
+ },
+ data: {
+ revokedAt: new Date(),
+ },
+ });
+
return this._oauthAuth.model.oAuthAuthorization.updateMany({
where: {
oauthAppId,
@@ -305,4 +317,121 @@ export class OAuthRepository {
},
});
}
+
+ // holds the instance API key, so only the id comes back
+ createSelfHostedAuthorization(data: {
+ oauthAppId: string;
+ mcpUrl: string;
+ apiKey: string;
+ email?: string;
+ authorizationCode: string;
+ codeExpiresAt: Date;
+ codeChallenge?: string;
+ codeChallengeMethod?: string;
+ redirectUri?: string;
+ }) {
+ return this._oauthSelfHosted.model.oAuthSelfHostedAuthorization.create({
+ select: {
+ id: true,
+ },
+ data: {
+ oauthAppId: data.oauthAppId,
+ mcpUrl: data.mcpUrl,
+ apiKey: data.apiKey,
+ email: data.email || null,
+ authorizationCode: data.authorizationCode,
+ codeExpiresAt: data.codeExpiresAt,
+ codeChallenge: data.codeChallenge || null,
+ codeChallengeMethod: data.codeChallengeMethod || null,
+ redirectUri: data.redirectUri || null,
+ },
+ });
+ }
+
+ // Abandoned consent flows leave rows (and API keys) that never got a token
+ deleteAbandonedSelfHostedAuthorizations(olderThan: Date) {
+ return this._oauthSelfHosted.model.oAuthSelfHostedAuthorization.deleteMany(
+ {
+ where: {
+ accessToken: null,
+ createdAt: { lt: olderThan },
+ },
+ }
+ );
+ }
+
+ findSelfHostedByCode(encryptedCode: string) {
+ return this._oauthSelfHosted.model.oAuthSelfHostedAuthorization.findFirst({
+ where: {
+ authorizationCode: encryptedCode,
+ revokedAt: null,
+ },
+ select: {
+ id: true,
+ oauthAppId: true,
+ codeExpiresAt: true,
+ codeChallenge: true,
+ redirectUri: true,
+ },
+ });
+ }
+
+ exchangeSelfHostedCodeForToken(id: string, encryptedToken: string) {
+ return this._oauthSelfHosted.model.oAuthSelfHostedAuthorization.update({
+ where: { id },
+ select: {
+ id: true,
+ },
+ data: {
+ accessToken: encryptedToken,
+ authorizationCode: null,
+ codeExpiresAt: null,
+ codeChallenge: null,
+ codeChallengeMethod: null,
+ redirectUri: null,
+ },
+ });
+ }
+
+ findSelfHostedByAccessToken(encryptedToken: string) {
+ return this._oauthSelfHosted.model.oAuthSelfHostedAuthorization.findFirst({
+ where: {
+ accessToken: encryptedToken,
+ revokedAt: null,
+ },
+ select: {
+ id: true,
+ mcpUrl: true,
+ apiKey: true,
+ },
+ });
+ }
+
+ findSelfHostedUserInfo(encryptedToken: string) {
+ return this._oauthSelfHosted.model.oAuthSelfHostedAuthorization.findFirst({
+ where: {
+ accessToken: encryptedToken,
+ revokedAt: null,
+ },
+ select: {
+ id: true,
+ email: true,
+ oauthApp: {
+ select: {
+ clientId: true,
+ dynamic: true,
+ redirectUris: true,
+ },
+ },
+ },
+ });
+ }
+
+ deleteSelfHostedAuthorization(id: string) {
+ return this._oauthSelfHosted.model.oAuthSelfHostedAuthorization.deleteMany(
+ {
+ where: { id },
+ }
+ );
+ }
}
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 4bd1c27a9..6e401157f 100644
--- a/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/oauth/oauth.service.ts
@@ -8,12 +8,17 @@ import { AuthService } from '@gitroom/helpers/auth/auth.service';
import { extractBearerToken } from '@gitroom/nestjs-libraries/chat/oauth-types';
import { createHash } from 'crypto';
import { OAuthApp } from '@prisma/client';
+import type { SelfHostedInstance } from '@gitroom/nestjs-libraries/chat/mcp.relay.service';
const openAiOAuthClientId = () =>
process.env.OPENAI_OAUTH_CLIENT_ID?.trim();
const enableOidcEmailClaims = () => Boolean(openAiOAuthClientId());
+// Postiz Cloud only, a self-hosted install has nothing to relay to
+export const selfHostedRelayEnabled = () =>
+ process.env.MCP_SELF_HOSTED_RELAY === 'true';
+
// Verified-domain match: exact host or a subdomain of it (spoof-safe, the
// leading dot means evilclaude.ai and claude.ai.evil.com are both rejected)
const isVerifiedHost = (host: string, verifiedDomains: string[]) =>
@@ -259,6 +264,54 @@ export class OAuthService {
].join(' ');
}
+ // Only MCP connections can be relayed to an instance: dynamically registered
+ // clients (registration is only advertised to MCP clients), the ChatGPT app,
+ // or a client asking for one of the /mcp-oauth resources (RFC 8707). Apps
+ // that use Postiz OAuth for the public API never get the option, a relayed
+ // token doesn't work there
+ allowsSelfHosted(
+ app: Pick<OAuthApp, 'clientId' | 'dynamic'>,
+ resource?: string
+ ) {
+ if (!selfHostedRelayEnabled()) {
+ return false;
+ }
+ if (app.dynamic || app.clientId === openAiOAuthClientId()) {
+ return true;
+ }
+ try {
+ return !!resource && new URL(resource).pathname.startsWith('/mcp-oauth');
+ } catch {
+ return false;
+ }
+ }
+
+ // The ChatGPT app reads the email from userinfo; a self-hosted connection
+ // has no cloud user to take it from, so the consent screen asks for one
+ selfHostedRequiresEmail(app: Pick<OAuthApp, 'clientId'>) {
+ return enableOidcEmailClaims() && app.clientId === openAiOAuthClientId();
+ }
+
+ // On top of validateAuthorizationRequest, for a self-hosted connection
+ validateSelfHostedRequest(
+ app: Pick<OAuthApp, 'clientId' | 'dynamic'>,
+ options: { resource?: string; email?: string }
+ ) {
+ if (!this.allowsSelfHosted(app, options.resource)) {
+ throw new HttpException(
+ 'This application can not connect to a self-hosted instance',
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ if (!options.email && this.selfHostedRequiresEmail(app)) {
+ throw new HttpException(
+ 'Enter your email address',
+ HttpStatus.BAD_REQUEST
+ );
+ }
+ }
+
async validateAuthorizationRequest(
clientId: string,
options?: {
@@ -328,6 +381,40 @@ export class OAuthService {
return code;
}
+ async createSelfHostedAuthorizationCode(
+ oauthAppId: string,
+ instance: SelfHostedInstance & { email?: string },
+ pkce?: {
+ codeChallenge?: string;
+ codeChallengeMethod?: string;
+ redirectUri?: string;
+ }
+ ) {
+ this._oauthRepository
+ .deleteAbandonedSelfHostedAuthorizations(
+ new Date(Date.now() - 24 * 60 * 60 * 1000)
+ )
+ .catch(() => {});
+
+ // The prefix sends the code to the self-hosted table at the token
+ // endpoint (regular codes use the same alphabet, without an underscore)
+ const code = 'psc_' + makeSecureId(32);
+
+ await this._oauthRepository.createSelfHostedAuthorization({
+ oauthAppId,
+ mcpUrl: instance.mcpUrl,
+ apiKey: AuthService.fixedEncryption(instance.apiKey),
+ email: instance.email,
+ authorizationCode: AuthService.fixedEncryption(code),
+ codeExpiresAt: new Date(Date.now() + 10 * 60 * 1000),
+ codeChallenge: pkce?.codeChallenge,
+ codeChallengeMethod: pkce?.codeChallengeMethod,
+ redirectUri: pkce?.redirectUri,
+ });
+
+ return code;
+ }
+
async exchangeCodeForToken(
code: string,
clientId: string,
@@ -359,6 +446,15 @@ export class OAuthService {
}
}
+ if (code.startsWith('psc_')) {
+ return this.exchangeSelfHostedCodeForToken(
+ app,
+ code,
+ codeVerifier,
+ redirectUri
+ );
+ }
+
const encryptedCode = AuthService.fixedEncryption(code);
const auth = await this._oauthRepository.findByCode(encryptedCode);
if (!auth || auth.oauthAppId !== app.id) {
@@ -368,6 +464,38 @@ export class OAuthService {
);
}
+ this.verifyCodeGrant(auth, codeVerifier, redirectUri);
+
+ const token = 'pos_' + makeSecureId(40);
+ const encryptedToken = AuthService.fixedEncryption(token);
+ const {
+ organizationId,
+ organization: { paymentId },
+ } = await this._oauthRepository.exchangeCodeForToken(
+ auth.id,
+ encryptedToken
+ );
+
+ return {
+ id: organizationId,
+ cus: paymentId,
+ access_token: token,
+ token_type: 'bearer',
+ scope: this.grantedScope(app),
+ };
+ }
+
+ // Expiry, PKCE and redirect_uri checks of an authorization code, shared by
+ // cloud and self-hosted authorizations
+ private verifyCodeGrant(
+ auth: {
+ codeExpiresAt: Date | null;
+ codeChallenge: string | null;
+ redirectUri: string | null;
+ },
+ codeVerifier?: string,
+ redirectUri?: string
+ ) {
if (!auth.codeExpiresAt || new Date() > auth.codeExpiresAt) {
throw new HttpException(
{ error: 'invalid_grant', error_description: 'Code has expired' },
@@ -397,26 +525,66 @@ export class OAuthService {
HttpStatus.BAD_REQUEST
);
}
+ }
- const token = 'pos_' + makeSecureId(40);
- const encryptedToken = AuthService.fixedEncryption(token);
- const {
- organizationId,
- organization: { paymentId },
- } = await this._oauthRepository.exchangeCodeForToken(
+ // A self-hosted connection has no organization (or payment) to return,
+ // only the token
+ private async exchangeSelfHostedCodeForToken(
+ app: OAuthApp,
+ code: string,
+ codeVerifier?: string,
+ redirectUri?: string
+ ) {
+ const auth = await this._oauthRepository.findSelfHostedByCode(
+ AuthService.fixedEncryption(code)
+ );
+ if (!auth || auth.oauthAppId !== app.id) {
+ throw new HttpException(
+ { error: 'invalid_grant' },
+ HttpStatus.BAD_REQUEST
+ );
+ }
+
+ this.verifyCodeGrant(auth, codeVerifier, redirectUri);
+
+ const token = 'psh_' + makeSecureId(40);
+ await this._oauthRepository.exchangeSelfHostedCodeForToken(
auth.id,
- encryptedToken
+ AuthService.fixedEncryption(token)
);
return {
- id: organizationId,
- cus: paymentId,
access_token: token,
token_type: 'bearer',
scope: this.grantedScope(app),
};
}
+ // null when the relay is off or the token is unknown or revoked
+ async getSelfHostedByAccessToken(token: string) {
+ if (!selfHostedRelayEnabled()) {
+ return null;
+ }
+
+ const authorization =
+ await this._oauthRepository.findSelfHostedByAccessToken(
+ AuthService.fixedEncryption(token)
+ );
+ if (!authorization) {
+ return null;
+ }
+
+ return {
+ id: authorization.id,
+ mcpUrl: authorization.mcpUrl,
+ apiKey: AuthService.fixedDecryption(authorization.apiKey),
+ };
+ }
+
+ deleteSelfHostedAuthorization(id: string) {
+ return this._oauthRepository.deleteSelfHostedAuthorization(id);
+ }
+
async getOrgByOAuthToken(token: string) {
const encrypted = AuthService.fixedEncryption(token);
return this._oauthRepository.findByAccessToken(encrypted);
@@ -441,6 +609,10 @@ export class OAuthService {
);
}
+ if (token.startsWith('psh_')) {
+ return this.getSelfHostedUserInfo(token);
+ }
+
const authorizationRecord = await this.getOrgByOAuthToken(token);
if (!authorizationRecord) {
throw new HttpException(
@@ -468,6 +640,40 @@ export class OAuthService {
};
}
+ // A self-hosted connection has no cloud user: the subject is the connection
+ // and the email is the one typed on the consent screen, which nobody verified
+ private async getSelfHostedUserInfo(token: string) {
+ const selfHosted = selfHostedRelayEnabled()
+ ? await this._oauthRepository.findSelfHostedUserInfo(
+ AuthService.fixedEncryption(token)
+ )
+ : null;
+ if (!selfHosted) {
+ throw new HttpException(
+ { error: 'invalid_token', error_description: 'Token is invalid or revoked' },
+ HttpStatus.UNAUTHORIZED
+ );
+ }
+
+ if (!this.allowsEmailClaims(selfHosted.oauthApp)) {
+ throw new HttpException(
+ {
+ error: 'insufficient_scope',
+ error_description:
+ 'This OAuth client is not authorized to access email claims',
+ },
+ HttpStatus.FORBIDDEN
+ );
+ }
+
+ return {
+ sub: selfHosted.id,
+ ...(selfHosted.email
+ ? { email: selfHosted.email, email_verified: false }
+ : {}),
+ };
+ }
+
async getApprovedApps(userId: string) {
return this._oauthRepository.getApprovedApps(userId);
}
diff --git a/libraries/nestjs-libraries/src/database/prisma/schema.prisma b/libraries/nestjs-libraries/src/database/prisma/schema.prisma
index 328b0db42..a64416474 100644
--- a/libraries/nestjs-libraries/src/database/prisma/schema.prisma
+++ b/libraries/nestjs-libraries/src/database/prisma/schema.prisma
@@ -1679,23 +1679,24 @@ model mastra_workspaces {
}
model OAuthApp {
- id String @id @default(uuid())
- organizationId String?
- name String
- description String?
- pictureId String?
- redirectUrl String
- redirectUris String?
- clientId String @unique
- clientSecret String?
- dynamic Boolean @default(false)
- tokenEndpointAuthMethod String?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- deletedAt DateTime?
- organization Organization? @relation(fields: [organizationId], references: [id])
- picture Media? @relation(fields: [pictureId], references: [id])
- authorizations OAuthAuthorization[]
+ id String @id @default(uuid())
+ organizationId String?
+ name String
+ description String?
+ pictureId String?
+ redirectUrl String
+ redirectUris String?
+ clientId String @unique
+ clientSecret String?
+ dynamic Boolean @default(false)
+ tokenEndpointAuthMethod String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ deletedAt DateTime?
+ organization Organization? @relation(fields: [organizationId], references: [id])
+ picture Media? @relation(fields: [pictureId], references: [id])
+ authorizations OAuthAuthorization[]
+ selfHostedAuthorizations OAuthSelfHostedAuthorization[]
@@unique([organizationId, deletedAt])
@@index([clientId])
@@ -1731,6 +1732,28 @@ model OAuthAuthorization {
@@index([revokedAt])
}
+model OAuthSelfHostedAuthorization {
+ id String @id @default(uuid())
+ oauthAppId String
+ mcpUrl String
+ apiKey String
+ email String?
+ accessToken String?
+ authorizationCode String?
+ codeExpiresAt DateTime?
+ codeChallenge String?
+ codeChallengeMethod String?
+ redirectUri String?
+ revokedAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ oauthApp OAuthApp @relation(fields: [oauthAppId], references: [id])
+
+ @@index([accessToken])
+ @@index([authorizationCode])
+ @@index([oauthAppId])
+}
+
enum OrderStatus {
PENDING
ACCEPTED
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 87e3e6458..bb80847c6 100644
--- a/libraries/nestjs-libraries/src/dtos/oauth/authorize-oauth.dto.ts
+++ b/libraries/nestjs-libraries/src/dtos/oauth/authorize-oauth.dto.ts
@@ -1,4 +1,11 @@
-import { IsDefined, IsIn, IsOptional, IsString } from 'class-validator';
+import {
+ IsDefined,
+ IsEmail,
+ IsIn,
+ IsOptional,
+ IsString,
+ MaxLength,
+} from 'class-validator';
export class AuthorizeOAuthQueryDto {
@IsString()
@@ -31,6 +38,12 @@ export class AuthorizeOAuthQueryDto {
@IsString()
@IsOptional()
scope?: string;
+
+ // RFC 8707 resource indicator sent by MCP clients, only used to tell if
+ // the connection can be relayed to a self-hosted instance
+ @IsString()
+ @IsOptional()
+ resource?: string;
}
export class ApproveOAuthDto {
@@ -61,3 +74,49 @@ export class ApproveOAuthDto {
@IsOptional()
code_challenge_method?: string;
}
+
+export class AuthorizeSelfHostedDto {
+ @IsString()
+ @IsDefined()
+ client_id: string;
+
+ @IsString()
+ @IsOptional()
+ state?: string;
+
+ @IsString()
+ @IsOptional()
+ redirect_uri?: string;
+
+ @IsString()
+ @IsOptional()
+ code_challenge?: string;
+
+ // Not validated with IsIn, same as ApproveOAuthDto
+ @IsString()
+ @IsOptional()
+ code_challenge_method?: string;
+
+ @IsString()
+ @IsOptional()
+ resource?: string;
+
+ // The instance as the person knows it: its address, its backend address or
+ // the MCP URL from Settings > Developers (resolved in McpRelayService)
+ @IsString()
+ @IsDefined()
+ @MaxLength(2048)
+ instance_url: string;
+
+ // Optional because the MCP URL from Settings > Developers carries the key
+ @IsString()
+ @IsOptional()
+ @MaxLength(512)
+ api_key?: string;
+
+ // Required (in the controller) for clients that read the email from
+ // userinfo, like ChatGPT
+ @IsEmail()
+ @IsOptional()
+ email?: string;
+}
diff --git a/libraries/react-shared-libraries/src/translation/locales/ar/translation.json b/libraries/react-shared-libraries/src/translation/locales/ar/translation.json
index 7935a7f33..b8a6dd6e2 100644
--- a/libraries/react-shared-libraries/src/translation/locales/ar/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/ar/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "لا حاجة لإعدادات MCP أو CLI. الصق هذا في الدردشة، سيقوم الوكيل بتثبيت Postiz CLI ويطلب منك مفتاح API الخاص بك.",
"connector": "موصل",
"connector_onboarding_description": "الأسرع: أضف Postiz بنقرة واحدة، سيطلب منك تسجيل الدخول",
+ "official_connector": "الموصل الرسمي",
+ "connector_self_hosted_description": "يعمل الموصل الرسمي أيضًا مع Postiz المستضاف ذاتيًا. عند طلب تسجيل الدخول، اختر \"Use self-hosted\" وأدخل {{url}} مع مفتاح API الخاص بك.",
"mcp_onboarding_description": "زود وكيلك بأدوات Postiz لإنشاء وجدولة وإدارة المنشورات",
"cli_onboarding_description": "ثبّت Postiz CLI والمهارة التي تعلم وكيلك كيفية استخدامها",
"agent_settings_later": "المزيد من الوكلاء والتعليمات الكاملة متوفرة في الإعدادات > المطورون",
diff --git a/libraries/react-shared-libraries/src/translation/locales/bn/translation.json b/libraries/react-shared-libraries/src/translation/locales/bn/translation.json
index d028c353d..4f65a827a 100644
--- a/libraries/react-shared-libraries/src/translation/locales/bn/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/bn/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "MCP বা CLI সেটিংসের প্রয়োজন নেই। এটি চ্যাটে পেস্ট করুন, এজেন্টটি Postiz CLI ইনস্টল করবে এবং আপনার API কী চাইবে।",
"connector": "কনেক্টর",
"connector_onboarding_description": "সবচেয়ে দ্রুত উপায়: এক ক্লিকে Postiz যোগ করুন, আপনাকে সাইন ইন করতে বলা হবে",
+ "official_connector": "অফিসিয়াল কানেক্টর",
+ "connector_self_hosted_description": "অফিসিয়াল কানেক্টর সেলফ-হোস্টেড Postiz-এর সাথেও কাজ করে। সাইন ইন করতে বলা হলে, \"Use self-hosted\" বেছে নিন এবং আপনার API কী সহ {{url}} লিখুন।",
"mcp_onboarding_description": "আপনার এজেন্টকে Postiz টুল দিন যাতে সে পোস্ট তৈরি, নির্ধারণ এবং পরিচালনা করতে পারে",
"cli_onboarding_description": "Postiz CLI এবং সেই স্কিল ইনস্টল করুন যা আপনার এজেন্টকে এটি ব্যবহার করতে শেখায়",
"agent_settings_later": "আরও এজেন্ট এবং সম্পূর্ণ নির্দেশিকা সেটিংস > ডেভেলপারস-এ পাওয়া যাবে",
diff --git a/libraries/react-shared-libraries/src/translation/locales/de/translation.json b/libraries/react-shared-libraries/src/translation/locales/de/translation.json
index 9166878e5..37a07c121 100644
--- a/libraries/react-shared-libraries/src/translation/locales/de/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/de/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "Kein MCP oder CLI Setup nötig. Füge das in den Chat ein und der Agent installiert das Postiz CLI und fragt dich nach deinem API-Schlüssel.",
"connector": "Konnektor",
"connector_onboarding_description": "Am schnellsten: Füge Postiz mit einem Klick hinzu, du wirst zur Anmeldung aufgefordert.",
+ "official_connector": "Offizieller Connector",
+ "connector_self_hosted_description": "Der offizielle Connector funktioniert auch mit selbst gehostetem Postiz. Wenn du dich anmelden sollst, wähle \"Use self-hosted\" und gib {{url}} zusammen mit deinem API-Schlüssel ein.",
"mcp_onboarding_description": "Gib deinem Agenten Postiz-Tools, um Beiträge zu erstellen, zu planen und zu verwalten.",
"cli_onboarding_description": "Installiere das Postiz CLI und das Skill, das deinem Agenten beibringt, wie es zu nutzen ist.",
"agent_settings_later": "Weitere Agenten und vollständige Anweisungen findest du unter Einstellungen > Entwickler.",
diff --git a/libraries/react-shared-libraries/src/translation/locales/en/translation.json b/libraries/react-shared-libraries/src/translation/locales/en/translation.json
index b7729393f..8c860883b 100644
--- a/libraries/react-shared-libraries/src/translation/locales/en/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/en/translation.json
@@ -728,6 +728,8 @@
"chat_onboarding_description": "No MCP or CLI settings needed. Paste this into the chat, the agent installs the Postiz CLI and asks you for your API key.",
"connector": "Connector",
"connector_onboarding_description": "The fastest way: add Postiz with one click, you will be asked to sign in",
+ "official_connector": "Official connector",
+ "connector_self_hosted_description": "The official connector works with self-hosted Postiz too. When asked to sign in, choose \"Use self-hosted\" and enter {{url}} with your API key.",
"mcp_onboarding_description": "Give your agent Postiz tools to create, schedule and manage posts",
"cli_onboarding_description": "Install the Postiz CLI and the skill that teaches your agent how to use it",
"agent_settings_later": "More agents and full instructions are available under Settings > Developers",
diff --git a/libraries/react-shared-libraries/src/translation/locales/es/translation.json b/libraries/react-shared-libraries/src/translation/locales/es/translation.json
index c5d398bf8..21f23c814 100644
--- a/libraries/react-shared-libraries/src/translation/locales/es/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/es/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "No necesitas configuraciones de MCP ni de CLI. Pega esto en el chat, el agente instalará el CLI de Postiz y te pedirá tu clave API.",
"connector": "Conector",
"connector_onboarding_description": "La forma más rápida: agrega Postiz con un clic, se te pedirá iniciar sesión",
+ "official_connector": "Conector oficial",
+ "connector_self_hosted_description": "El conector oficial también funciona con Postiz autoalojado. Cuando te pida iniciar sesión, elige \"Use self-hosted\" e introduce {{url}} con tu clave de API.",
"mcp_onboarding_description": "Dale a tu agente las herramientas de Postiz para crear, programar y gestionar publicaciones",
"cli_onboarding_description": "Instala el CLI de Postiz y la habilidad que enseña a tu agente cómo utilizarlo",
"agent_settings_later": "Más agentes y las instrucciones completas están disponibles en Configuración > Desarrolladores",
diff --git a/libraries/react-shared-libraries/src/translation/locales/fr/translation.json b/libraries/react-shared-libraries/src/translation/locales/fr/translation.json
index 94de4a792..330c69db2 100644
--- a/libraries/react-shared-libraries/src/translation/locales/fr/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/fr/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "Aucun paramétrage MCP ou CLI nécessaire. Collez ceci dans le chat, l’agent installe le CLI Postiz et vous demande votre clé API.",
"connector": "Connecteur",
"connector_onboarding_description": "La façon la plus rapide : ajoutez Postiz en un clic, vous serez invité à vous connecter",
+ "official_connector": "Connecteur officiel",
+ "connector_self_hosted_description": "Le connecteur officiel fonctionne aussi avec Postiz auto-hébergé. Lorsqu'on vous demande de vous connecter, choisissez \"Use self-hosted\" et saisissez {{url}} avec votre clé API.",
"mcp_onboarding_description": "Donnez à votre agent des outils Postiz pour créer, programmer et gérer des publications",
"cli_onboarding_description": "Installez le CLI Postiz et la compétence qui apprend à votre agent à l’utiliser",
"agent_settings_later": "Plus d’agents et les instructions complètes sont disponibles dans Paramètres > Développeurs",
diff --git a/libraries/react-shared-libraries/src/translation/locales/he/translation.json b/libraries/react-shared-libraries/src/translation/locales/he/translation.json
index e0556c9a4..ae20db6ce 100644
--- a/libraries/react-shared-libraries/src/translation/locales/he/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/he/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "אין צורך ב-MCP או הגדרות CLI. העתיקו את זה לצ'אט, הסוכן יתקין את Postiz CLI וישאל אתכם את מפתח ה-API שלכם.",
"connector": "מחבר",
"connector_onboarding_description": "הדרך המהירה ביותר: הוסיפו את Postiz בלחיצה אחת, תתבקשו להתחבר",
+ "official_connector": "מחבר רשמי",
+ "connector_self_hosted_description": "המחבר הרשמי עובד גם עם Postiz באירוח עצמי. כשתתבקש להתחבר, בחר \"Use self-hosted\" והזן את {{url}} יחד עם מפתח ה-API שלך.",
"mcp_onboarding_description": "העניקו לסוכן שלכם כלים של Postiz ליצירת, תזמון וניהול פוסטים",
"cli_onboarding_description": "התקינו את Postiz CLI ואת המיומנות שמלמדת את הסוכן איך להשתמש בו",
"agent_settings_later": "סוכנים נוספים והוראות מלאות זמינים תחת הגדרות > מפתחים",
diff --git a/libraries/react-shared-libraries/src/translation/locales/it/translation.json b/libraries/react-shared-libraries/src/translation/locales/it/translation.json
index 92f5e5bfe..5aa352e70 100644
--- a/libraries/react-shared-libraries/src/translation/locales/it/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/it/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "Nessuna impostazione MCP o CLI necessaria. Incolla questo nella chat, l'agente installerà il Postiz CLI e ti chiederà la tua API key.",
"connector": "Connettore",
"connector_onboarding_description": "Il modo più veloce: aggiungi Postiz con un clic, ti verrà chiesto di accedere",
+ "official_connector": "Connettore ufficiale",
+ "connector_self_hosted_description": "Il connettore ufficiale funziona anche con Postiz self-hosted. Quando ti viene chiesto di accedere, scegli \"Use self-hosted\" e inserisci {{url}} con la tua chiave API.",
"mcp_onboarding_description": "Dai al tuo agente gli strumenti Postiz per creare, programmare e gestire post",
"cli_onboarding_description": "Installa il Postiz CLI e la skill che insegna al tuo agente come usarlo",
"agent_settings_later": "Altri agenti e istruzioni complete sono disponibili in Impostazioni > Sviluppatori",
diff --git a/libraries/react-shared-libraries/src/translation/locales/ja/translation.json b/libraries/react-shared-libraries/src/translation/locales/ja/translation.json
index 7883d3c1d..36c0534dc 100644
--- a/libraries/react-shared-libraries/src/translation/locales/ja/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/ja/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "MCPやCLIの設定は不要です。これをチャットに貼り付けるだけで、エージェントがPostiz CLIをインストールし、APIキーを尋ねます。",
"connector": "コネクタ",
"connector_onboarding_description": "最速の方法: ワンクリックでPostizを追加、サインインが求められます。",
+ "official_connector": "公式コネクタ",
+ "connector_self_hosted_description": "公式コネクタはセルフホストの Postiz でも使えます。サインインを求められたら「Use self-hosted」を選び、{{url}} と API キーを入力してください。",
"mcp_onboarding_description": "エージェントにPostizのツールを使わせて、投稿の作成やスケジュール管理をさせましょう。",
"cli_onboarding_description": "Postiz CLIと、それを使い方をエージェントに教えるスキルをインストールします。",
"agent_settings_later": "その他のエージェントや詳細な手順は、設定 > 開発者 から利用できます。",
diff --git a/libraries/react-shared-libraries/src/translation/locales/ko/translation.json b/libraries/react-shared-libraries/src/translation/locales/ko/translation.json
index 266fa2c3f..c88a6eb3c 100644
--- a/libraries/react-shared-libraries/src/translation/locales/ko/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/ko/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "MCP나 CLI 설정이 필요 없습니다. 채팅에 이 내용을 붙여넣으면 에이전트가 Postiz CLI를 설치하고 API 키를 입력받습니다.",
"connector": "커넥터",
"connector_onboarding_description": "가장 빠른 방법: 한 번의 클릭으로 Postiz를 추가하고, 로그인 요청을 받게 됩니다.",
+ "official_connector": "공식 커넥터",
+ "connector_self_hosted_description": "공식 커넥터는 자체 호스팅 Postiz에서도 작동합니다. 로그인하라는 메시지가 나타나면 \"Use self-hosted\"를 선택하고 {{url}}과 API 키를 입력하세요.",
"mcp_onboarding_description": "에이전트에게 Postiz 도구를 제공해 게시물을 생성, 예약, 관리할 수 있습니다.",
"cli_onboarding_description": "Postiz CLI와 에이전트에게 사용법을 알려주는 스킬을 설치하세요.",
"agent_settings_later": "더 많은 에이전트와 전체 안내는 설정 > 개발자에서 볼 수 있습니다.",
diff --git a/libraries/react-shared-libraries/src/translation/locales/pt/translation.json b/libraries/react-shared-libraries/src/translation/locales/pt/translation.json
index 336ae9ecf..f259f7fa7 100644
--- a/libraries/react-shared-libraries/src/translation/locales/pt/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/pt/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "Não precisa de configurações MCP ou CLI. Cole isso no chat, o agente instala o Postiz CLI e pede sua chave de API.",
"connector": "Conector",
"connector_onboarding_description": "A forma mais rápida: adicione o Postiz com um clique, será solicitado que você faça login",
+ "official_connector": "Conector oficial",
+ "connector_self_hosted_description": "O conector oficial também funciona com o Postiz auto-hospedado. Quando for solicitado o login, escolha \"Use self-hosted\" e informe {{url}} com sua chave de API.",
"mcp_onboarding_description": "Dê ao seu agente as ferramentas Postiz para criar, agendar e gerenciar posts",
"cli_onboarding_description": "Instale o Postiz CLI e a skill que ensina seu agente como usá-lo",
"agent_settings_later": "Mais agentes e instruções completas estão disponíveis em Configurações > Desenvolvedores",
diff --git a/libraries/react-shared-libraries/src/translation/locales/ru/translation.json b/libraries/react-shared-libraries/src/translation/locales/ru/translation.json
index 412110759..f041fdf4b 100644
--- a/libraries/react-shared-libraries/src/translation/locales/ru/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/ru/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "Не нужны MCP или настройки CLI. Вставьте это в чат, агент установит Postiz CLI и спросит у вас API-ключ.",
"connector": "Коннектор",
"connector_onboarding_description": "Самый быстрый способ: добавьте Postiz одним кликом, вам предложат войти в систему",
+ "official_connector": "Официальный коннектор",
+ "connector_self_hosted_description": "Официальный коннектор работает и с Postiz на собственном сервере. Когда вас попросят войти, выберите \"Use self-hosted\" и введите {{url}} и ваш API-ключ.",
"mcp_onboarding_description": "Дайте вашему агенту инструменты Postiz для создания, планирования и управления публикациями",
"cli_onboarding_description": "Установите Postiz CLI и навык, который научит вашего агента им пользоваться",
"agent_settings_later": "Больше агентов и полные инструкции доступны в разделе Настройки > Разработчики",
diff --git a/libraries/react-shared-libraries/src/translation/locales/tr/translation.json b/libraries/react-shared-libraries/src/translation/locales/tr/translation.json
index 6dc594ae5..813cc3925 100644
--- a/libraries/react-shared-libraries/src/translation/locales/tr/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/tr/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "MCP veya CLI ayarlarına gerek yok. Bunu sohbete yapıştırın, ajan Postiz CLI'yı yükler ve sizden API anahtarınızı ister.",
"connector": "Konnektör",
"connector_onboarding_description": "En hızlı yol: Postiz'i tek tıkla ekleyin, giriş yapmanız istenecektir",
+ "official_connector": "Resmi bağlayıcı",
+ "connector_self_hosted_description": "Resmi bağlayıcı, kendi sunucunuzda barındırdığınız Postiz ile de çalışır. Giriş yapmanız istendiğinde \"Use self-hosted\" seçeneğini seçin ve API anahtarınızla birlikte {{url}} adresini girin.",
"mcp_onboarding_description": "Ajanınıza gönderi oluşturma, zamanlama ve yönetme araçları verin",
"cli_onboarding_description": "Postiz CLI ve ajanınıza bunun nasıl kullanılacağını öğreten beceriyi kurun",
"agent_settings_later": "Daha fazla ajan ve tam talimatlar Ayarlar > Geliştiriciler bölümünde mevcuttur",
diff --git a/libraries/react-shared-libraries/src/translation/locales/vi/translation.json b/libraries/react-shared-libraries/src/translation/locales/vi/translation.json
index b9eb25bbc..21a367798 100644
--- a/libraries/react-shared-libraries/src/translation/locales/vi/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/vi/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "Không cần cài đặt MCP hoặc CLI. Dán dòng này vào chat, Agent sẽ cài đặt Postiz CLI và yêu cầu API key của bạn.",
"connector": "Connector",
"connector_onboarding_description": "Nhanh nhất: thêm Postiz chỉ với một cú nhấp, bạn sẽ được yêu cầu đăng nhập",
+ "official_connector": "Trình kết nối chính thức",
+ "connector_self_hosted_description": "Trình kết nối chính thức cũng hoạt động với Postiz tự lưu trữ. Khi được yêu cầu đăng nhập, hãy chọn \"Use self-hosted\" và nhập {{url}} cùng khóa API của bạn.",
"mcp_onboarding_description": "Cung cấp cho Agent của bạn các công cụ của Postiz để tạo, lên lịch và quản lý bài đăng",
"cli_onboarding_description": "Cài đặt Postiz CLI và kỹ năng hướng dẫn Agent của bạn cách sử dụng nó",
"agent_settings_later": "Thêm nhiều Agent và hướng dẫn đầy đủ có tại Cài đặt > Nhà phát triển",
diff --git a/libraries/react-shared-libraries/src/translation/locales/zh/translation.json b/libraries/react-shared-libraries/src/translation/locales/zh/translation.json
index 449a805b5..9b8d1b20d 100644
--- a/libraries/react-shared-libraries/src/translation/locales/zh/translation.json
+++ b/libraries/react-shared-libraries/src/translation/locales/zh/translation.json
@@ -726,6 +726,8 @@
"chat_onboarding_description": "无需 MCP 或 CLI 设置。将此粘贴到聊天中,代理会安装 Postiz CLI 并向您索取 API 密钥。",
"connector": "连接器",
"connector_onboarding_description": "最快捷的方法:一键添加 Postiz,系统会要求您登录",
+ "official_connector": "官方连接器",
+ "connector_self_hosted_description": "官方连接器同样适用于自托管的 Postiz。在要求登录时,选择“Use self-hosted”,然后输入 {{url}} 和你的 API 密钥。",
"mcp_onboarding_description": "为您的代理提供 Postiz 工具,以创建、安排和管理帖子",
"cli_onboarding_description": "安装 Postiz CLI 以及教您的代理如何使用的技能",
"agent_settings_later": "更多代理和完整说明可在 设置 > 开发者 下查看",