⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: a separate public origin for incoming Git webhooks (#592)
Allie5c6ca8c17f2c
diff --git a/.env.example b/.env.exampleindex 4ad499d7..410e71d9 100644--- a/.env.example+++ b/.env.example@@ -20,6 +20,10 @@ DATABASE_URL=postgres://itsaplan:itsaplan@localhost:5432/itsaplan# APP_URL — web origin: CORS/auth trusted origins, passkey, email links.API_URL=http://localhost:3000APP_URL=http://localhost:3001+# Public origin Git providers deliver repository webhooks to, for an instance whose+# API_URL is reachable only from a private network. It changes only the payload URL+# (<origin>/webhooks/git/<id>); unset, the payload URL uses API_URL.+# GIT_WEBHOOK_BASE_URL=https://hooks.example.com# ── Legal document URLs ──# Shown on the logged-out screens; Google OAuth sign-in requires the privacy policydiff --git a/apps/api/src/modules/git/__tests__/integration/git-managed-webhooks.test.ts b/apps/api/src/modules/git/__tests__/integration/git-managed-webhooks.test.tsnew file mode 100644index 00000000..5e171b89--- /dev/null+++ b/apps/api/src/modules/git/__tests__/integration/git-managed-webhooks.test.ts@@ -0,0 +1,193 @@+import { describe, it, expect, beforeEach, afterEach } from 'bun:test';+import { authedApi, type Api, createProject } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';++// Webhooks the instance manages through a provider connection, against a provider served+// on localhost. The SSRF guard refuses http and loopback hosts under NODE_ENV=test, so+// each case runs as development, the way the @repo/net tests reach a local server.++type FakeProvider = 'github' | 'gitea' | 'gitlab';++const API_PREFIX: Record<FakeProvider, string> = {+ github: '/api/v3',+ gitea: '/api/v1',+ gitlab: '/api/v4',+};++interface Hook {+ id: number;+ url: string;+ secret: string;+}++function fakeProvider(provider: FakeProvider) {+ const hooks = new Map<number, Hook>();+ let nextId = 1;+ const prefix = API_PREFIX[provider];+ const hooksPath = provider === 'gitlab' ? '/projects/1/hooks' : '/repos/acme/site/hooks';+ const show = (hook: Hook) =>+ provider === 'gitlab'+ ? { id: hook.id, url: hook.url }+ : { id: hook.id, config: { url: hook.url, content_type: 'json' } };+ const read = (body: Record<string, unknown>) => {+ if (provider === 'gitlab') return { url: body.url as string, secret: body.token as string };+ const config = body.config as Record<string, string>;+ return { url: config.url!, secret: config.secret! };+ };++ const server = Bun.serve({+ port: 0,+ async fetch(req) {+ const path = new URL(req.url).pathname.slice(prefix.length);+ if (path === '/user') return Response.json({ login: 'octo', username: 'octo' });+ if (path === '/repositories/1' || path === '/projects/1') {+ return Response.json({+ id: 1,+ full_name: 'acme/site',+ path_with_namespace: 'acme/site',+ html_url: 'https://git.example/acme/site',+ web_url: 'https://git.example/acme/site',+ permissions: { admin: true },+ });+ }+ if (path === hooksPath && req.method === 'GET') {+ return Response.json([...hooks.values()].map(show));+ }+ if (path === hooksPath && req.method === 'POST') {+ const hook = { id: nextId++, ...read((await req.json()) as Record<string, unknown>) };+ hooks.set(hook.id, hook);+ return Response.json(show(hook), { status: 201 });+ }+ const match = path.match(/\/hooks\/(\d+)$/);+ const hook = match ? hooks.get(Number(match[1])) : undefined;+ if (match && (req.method === 'PATCH' || req.method === 'PUT')) {+ if (!hook) return Response.json({ message: 'Not Found' }, { status: 404 });+ Object.assign(hook, read((await req.json()) as Record<string, unknown>));+ return Response.json(show(hook));+ }+ return Response.json({ message: 'Not Found' }, { status: 404 });+ },+ });+ return { baseUrl: `http://127.0.0.1:${server.port}`, hooks, stop: () => server.stop(true) };+}++async function setup(provider: FakeProvider, fake: ReturnType<typeof fakeProvider>) {+ const owner = await signUpTestUser({ name: 'Owner' });+ const asOwner = authedApi(owner.cookie);+ const created = await createProject(asOwner, { key: 'MKT', name: 'Marketing' });+ const teamId = created.data!.teamId;+ const connection = await saveToken(asOwner, teamId, provider, fake.baseUrl);+ const connected = await asOwner+ .projects({ projectKey: 'MKT' })+ .settings.git.connections({ connectionId: connection.id })+ .repositories.post({ externalIds: ['1'] });+ expect(connected.status).toBe(200);+ return { asOwner, teamId };+}++async function saveToken(asOwner: Api, teamId: number, provider: FakeProvider, baseUrl: string) {+ const response = await asOwner+ .teams({ teamId })+ .settings.git.connections.post({ provider, baseUrl, token: 'token-1' });+ expect(response.status).toBe(201);+ return response.data!;+}++async function settings(asOwner: Api) {+ return (await asOwner.projects({ projectKey: 'MKT' }).settings.git.get()).data!;+}++describe('Managed repository webhooks', () => {+ const environment = { ...process.env };+ let fake: ReturnType<typeof fakeProvider> | null = null;++ beforeEach(async () => {+ await resetDb();+ process.env.NODE_ENV = 'development';+ delete process.env.GIT_WEBHOOK_BASE_URL;+ });++ afterEach(() => {+ fake?.stop();+ fake = null;+ process.env.NODE_ENV = environment.NODE_ENV;+ if (environment.GIT_WEBHOOK_BASE_URL === undefined) delete process.env.GIT_WEBHOOK_BASE_URL;+ else process.env.GIT_WEBHOOK_BASE_URL = environment.GIT_WEBHOOK_BASE_URL;+ });++ it('builds the payload URL from API_URL when GIT_WEBHOOK_BASE_URL is unset', async () => {+ fake = fakeProvider('github');+ const { asOwner } = await setup('github', fake);++ const current = await settings(asOwner);+ expect(current.payloadUrl).toBe(`${process.env.API_URL}/webhooks/git/${current.webhookId}`);+ expect([...fake.hooks.values()]).toMatchObject([{ url: current.payloadUrl }]);+ });++ it('builds the payload URL from GIT_WEBHOOK_BASE_URL when it is set', async () => {+ process.env.GIT_WEBHOOK_BASE_URL = 'https://hooks.example.com/';+ fake = fakeProvider('github');+ const { asOwner } = await setup('github', fake);++ const current = await settings(asOwner);+ expect(current.payloadUrl).toBe(`https://hooks.example.com/webhooks/git/${current.webhookId}`);+ expect([...fake.hooks.values()]).toMatchObject([{ url: current.payloadUrl }]);+ });++ for (const provider of ['github', 'gitea', 'gitlab'] as const) {+ it(`updates the stored ${provider} hook in place when the base URL changes`, async () => {+ fake = fakeProvider(provider);+ const { asOwner, teamId } = await setup(provider, fake);++ process.env.GIT_WEBHOOK_BASE_URL = 'https://hooks.example.com';+ await saveToken(asOwner, teamId, provider, fake.baseUrl);++ const current = await settings(asOwner);+ expect(current.payloadUrl).toStartWith('https://hooks.example.com/webhooks/git/');+ expect([...fake.hooks.values()]).toMatchObject([{ id: 1, url: current.payloadUrl }]);+ });+ }++ it('updates a hook whose URL was edited by hand instead of adding a second one', async () => {+ fake = fakeProvider('github');+ const { asOwner, teamId } = await setup('github', fake);+ fake.hooks.get(1)!.url = 'https://edited.example.com/webhooks/git/x';++ await saveToken(asOwner, teamId, 'github', fake.baseUrl);++ const current = await settings(asOwner);+ expect([...fake.hooks.values()]).toMatchObject([{ id: 1, url: current.payloadUrl }]);+ });++ it('sends a regenerated secret to the stored hook', async () => {+ fake = fakeProvider('github');+ const { asOwner } = await setup('github', fake);+ process.env.GIT_WEBHOOK_BASE_URL = 'https://hooks.example.com';++ const regenerated = await asOwner.projects({ projectKey: 'MKT' }).settings.git.secret.post();++ expect(regenerated.data!.payloadUrl).toStartWith('https://hooks.example.com/webhooks/git/');+ expect([...fake.hooks.values()]).toEqual([+ { id: 1, url: regenerated.data!.payloadUrl, secret: regenerated.data!.secret },+ ]);+ });++ it('creates the hook again when the stored one is gone', async () => {+ fake = fakeProvider('github');+ const { asOwner } = await setup('github', fake);+ fake.hooks.delete(1);++ const regenerated = await asOwner.projects({ projectKey: 'MKT' }).settings.git.secret.post();++ expect([...fake.hooks.values()]).toEqual([+ { id: 2, url: regenerated.data!.payloadUrl, secret: regenerated.data!.secret },+ ]);+ const connections = await asOwner+ .projects({ projectKey: 'MKT' })+ .settings.git.connections.get();+ expect(connections.data![0]!.repositories).toMatchObject([+ { fullName: 'acme/site', status: 'connected', lastError: null },+ ]);+ });+});diff --git a/apps/api/src/modules/git/connections-provider.ts b/apps/api/src/modules/git/connections-provider.tsindex a1339232..113e3e4c 100644--- a/apps/api/src/modules/git/connections-provider.ts+++ b/apps/api/src/modules/git/connections-provider.ts@@ -182,7 +182,7 @@ export function providerErrorMessage(async function providerRequest(input: ProviderConnectionInput,path: string,- init: RequestInit = {},+ init: RequestInit & { allowMissing?: boolean } = {},): Promise<Response> {const headers = providerHeaders(input.provider, input.token);if (init.body !== undefined) headers.set('content-type', 'application/json');@@ -201,8 +201,8 @@ async function providerRequest(`${PROVIDER_LABEL[input.provider]} could not be reached. Check the provider URL and network access.`,);}- const missingDelete = init.method === 'DELETE' && response.status === 404;- if (!response.ok && !missingDelete) {+ const missing = response.status === 404 && (init.method === 'DELETE' || init.allowMissing);+ if (!response.ok && !missing) {const body = record(await response.clone()@@ -721,27 +721,38 @@ export async function createProviderPullRequest(};}-export async function installProviderWebhook(- input: ProviderConnectionInput,+interface ProviderWebhookApi {+ hooksPath: string;+ listQuery: string;+ updateMethod: 'PATCH' | 'PUT';+ hooks(body: unknown): unknown[];+ url(hook: Record<string, unknown> | null): string | null;+ id(hook: Record<string, unknown> | null): string | null;+ body(create: boolean): unknown;+}++function numericId(hook: Record<string, unknown> | null): string | null {+ const id = hook?.id;+ return typeof id === 'number' || typeof id === 'string' ? String(id) : null;+}++function providerWebhookApi(+ provider: GitProvider,repository: ProviderRepository,payloadUrl: string,secret: string,-): Promise<string> {- if (input.provider === 'gitlab') {- const hooksPath = `/projects/${encodeURIComponent(repository.externalId)}/hooks`;- const hooksResponse = await providerRequest(input, `${hooksPath}?per_page=100`);- const hooks: unknown = await hooksResponse.json();- const existing = Array.isArray(hooks)- ? hooks.map(record).find((hook) => text(hook?.url) === payloadUrl)- : undefined;- const existingId = existing?.id;- const path =- typeof existingId === 'number' || typeof existingId === 'string'- ? `${hooksPath}/${encodeURIComponent(String(existingId))}`- : hooksPath;- const response = await providerRequest(input, path, {- method: existing ? 'PUT' : 'POST',- body: JSON.stringify({+): ProviderWebhookApi {+ const arrayBody = (body: unknown) => (Array.isArray(body) ? body : []);+ const configUrl = (hook: Record<string, unknown> | null) => text(record(hook?.config)?.url);+ if (provider === 'gitlab') {+ return {+ hooksPath: `/projects/${encodeURIComponent(repository.externalId)}/hooks`,+ listQuery: '?per_page=100',+ updateMethod: 'PUT',+ hooks: arrayBody,+ url: (hook) => text(hook?.url),+ id: numericId,+ body: () => ({url: payloadUrl,token: secret,merge_requests_events: true,@@ -749,52 +760,33 @@ export async function installProviderWebhook(push_events: true,enable_ssl_verification: true,}),- });- const id = record(await response.json())?.id;- if (typeof id !== 'number' && typeof id !== 'string')- throw new HttpError(502, 'GitLab returned an invalid webhook');- return String(id);+ };}-- if (input.provider === 'gitea' || input.provider === 'forgejo') {- const hooksPath = `${githubRepoPath(repository.fullName)}/hooks`;- const hooksResponse = await providerRequest(input, `${hooksPath}?limit=100`);- const hooks: unknown = await hooksResponse.json();- const existing = Array.isArray(hooks)- ? hooks.map(record).find((hook) => text(record(hook?.config)?.url) === payloadUrl)- : undefined;- const existingId = existing?.id;- const path =- typeof existingId === 'number' || typeof existingId === 'string'- ? `${hooksPath}/${encodeURIComponent(String(existingId))}`- : hooksPath;- const response = await providerRequest(input, path, {- method: existing ? 'PATCH' : 'POST',- body: JSON.stringify({- ...(existing ? {} : { type: 'gitea' }),+ if (provider === 'gitea' || provider === 'forgejo') {+ return {+ hooksPath: `${githubRepoPath(repository.fullName)}/hooks`,+ listQuery: '?limit=100',+ updateMethod: 'PATCH',+ hooks: arrayBody,+ url: configUrl,+ id: numericId,+ body: (create) => ({+ ...(create ? { type: 'gitea' } : {}),active: true,events: ['pull_request', 'create', 'delete'],config: { url: payloadUrl, content_type: 'json', secret },}),- });- const id = record(await response.json())?.id;- if (typeof id !== 'number' && typeof id !== 'string')- throw new HttpError(502, `${input.provider} returned an invalid webhook`);- return String(id);+ };}-- if (input.provider === 'bitbucket') {- const hooksPath = `${bitbucketRepoPath(repository.fullName)}/hooks`;- const hooksResponse = await providerRequest(input, `${hooksPath}?pagelen=100`);- const hooks = record(await hooksResponse.json())?.values;- const existing = Array.isArray(hooks)- ? hooks.map(record).find((hook) => text(hook?.url) === payloadUrl)- : undefined;- const existingId = text(existing?.uuid);- const path = existingId ? `${hooksPath}/${encodeURIComponent(existingId)}` : hooksPath;- const response = await providerRequest(input, path, {- method: existing ? 'PUT' : 'POST',- body: JSON.stringify({+ if (provider === 'bitbucket') {+ return {+ hooksPath: `${bitbucketRepoPath(repository.fullName)}/hooks`,+ listQuery: '?pagelen=100',+ updateMethod: 'PUT',+ hooks: (body) => arrayBody(record(body)?.values),+ url: (hook) => text(hook?.url),+ id: (hook) => text(hook?.uuid),+ body: () => ({description: "It's a Plan",url: payloadUrl,active: true,@@ -808,36 +800,61 @@ export async function installProviderWebhook('repo:branch_deleted',],}),- });- const id = text(record(await response.json())?.uuid);- if (!id) throw new HttpError(502, 'Bitbucket returned an invalid webhook');- return id;+ };}-- const hooksPath = `${githubRepoPath(repository.fullName)}/hooks`;- const hooksResponse = await providerRequest(input, `${hooksPath}?per_page=100`);- const hooks: unknown = await hooksResponse.json();- const existing = Array.isArray(hooks)- ? hooks.map(record).find((hook) => text(record(hook?.config)?.url) === payloadUrl)- : undefined;- const existingId = existing?.id;- const path =- typeof existingId === 'number' || typeof existingId === 'string'- ? `${hooksPath}/${encodeURIComponent(String(existingId))}`- : hooksPath;- const response = await providerRequest(input, path, {- method: existing ? 'PATCH' : 'POST',- body: JSON.stringify({- ...(existing ? {} : { name: 'web' }),+ return {+ hooksPath: `${githubRepoPath(repository.fullName)}/hooks`,+ listQuery: '?per_page=100',+ updateMethod: 'PATCH',+ hooks: arrayBody,+ url: configUrl,+ id: numericId,+ body: (create) => ({+ ...(create ? { name: 'web' } : {}),active: true,events: ['pull_request', 'check_run', 'create', 'delete'],config: { url: payloadUrl, content_type: 'json', insecure_ssl: '0', secret },}),+ };+}++// Updates the hook stored as `webhookExternalId` in place, whatever URL it has now.+// Without a stored id (first install) it reuses a hook with this exact URL. A stored+// hook the provider no longer has is created again.+export async function installProviderWebhook(+ input: ProviderConnectionInput,+ repository: ProviderRepository,+ payloadUrl: string,+ secret: string,+ webhookExternalId: string | null,+): Promise<string> {+ const api = providerWebhookApi(input.provider, repository, payloadUrl, secret);+ let existingId = webhookExternalId;+ if (existingId === null) {+ const hooksResponse = await providerRequest(input, `${api.hooksPath}${api.listQuery}`);+ const existing = api+ .hooks(await hooksResponse.json())+ .map(record)+ .find((hook) => api.url(hook) === payloadUrl);+ existingId = existing ? api.id(existing) : null;+ }+ let response: Response | null = null;+ if (existingId !== null) {+ response = await providerRequest(input, `${api.hooksPath}/${encodeURIComponent(existingId)}`, {+ method: api.updateMethod,+ body: JSON.stringify(api.body(false)),+ allowMissing: true,+ });+ if (response.status === 404) response = null;+ }+ response ??= await providerRequest(input, api.hooksPath, {+ method: 'POST',+ body: JSON.stringify(api.body(true)),});- const id = record(await response.json())?.id;- if (typeof id !== 'number' && typeof id !== 'string')- throw new HttpError(502, 'GitHub returned an invalid webhook');- return String(id);+ const id = api.id(record(await response.json()));+ if (!id)+ throw new HttpError(502, `${PROVIDER_LABEL[input.provider]} returned an invalid webhook`);+ return id;}export async function deleteProviderWebhook(diff --git a/apps/api/src/modules/git/connections-service.ts b/apps/api/src/modules/git/connections-service.tsindex 5f1214e7..005d30ec 100644--- a/apps/api/src/modules/git/connections-service.ts+++ b/apps/api/src/modules/git/connections-service.ts@@ -351,37 +351,46 @@ async function reconcileConnectionWebhooks(.where(eq(gitManagedRepository.connectionId, connectionId));const settingsByProject = new Map<number, GitSettings>();for (const repository of repositories) {- try {- let settings = settingsByProject.get(repository.projectId);- if (!settings) {- settings = await getOrCreateGitSettings(repository.projectId);- settingsByProject.set(repository.projectId, settings);- }- const webhookExternalId = await installProviderWebhook(- input,- {- externalId: repository.externalId,- fullName: repository.fullName,- webUrl: repository.webUrl,- private: false,- },- webhookPayloadUrl(settings),- settings.secret,- );- await db- .update(gitManagedRepository)- .set({ webhookExternalId, status: 'connected', lastError: null, updatedAt: new Date() })- .where(eq(gitManagedRepository.id, repository.id));- } catch (error) {- await db- .update(gitManagedRepository)- .set({- status: 'error',- lastError: error instanceof Error ? error.message : 'Webhook update failed',- updatedAt: new Date(),- })- .where(eq(gitManagedRepository.id, repository.id));+ let settings = settingsByProject.get(repository.projectId);+ if (!settings) {+ settings = await getOrCreateGitSettings(repository.projectId);+ settingsByProject.set(repository.projectId, settings);}+ await reconcileRepositoryWebhook(input, repository, settings);+ }+}++async function reconcileRepositoryWebhook(+ input: ProviderConnectionInput,+ repository: typeof gitManagedRepository.$inferSelect,+ settings: GitSettings,+): Promise<void> {+ try {+ const webhookExternalId = await installProviderWebhook(+ input,+ {+ externalId: repository.externalId,+ fullName: repository.fullName,+ webUrl: repository.webUrl,+ private: false,+ },+ settings.payloadUrl,+ settings.secret,+ repository.webhookExternalId,+ );+ await db+ .update(gitManagedRepository)+ .set({ webhookExternalId, status: 'connected', lastError: null, updatedAt: new Date() })+ .where(eq(gitManagedRepository.id, repository.id));+ } catch (error) {+ await db+ .update(gitManagedRepository)+ .set({+ status: 'error',+ lastError: error instanceof Error ? error.message : 'Webhook update failed',+ updatedAt: new Date(),+ })+ .where(eq(gitManagedRepository.id, repository.id));}}@@ -412,12 +421,6 @@ export async function listAvailableRepositories(};}-function webhookPayloadUrl(settings: GitSettings): string {- const apiUrl = process.env.API_URL;- if (!apiUrl) throw new HttpError(500, 'API_URL is not configured');- return `${apiUrl.replace(/\/$/, '')}/webhooks/git/${settings.webhookId}`;-}-export async function connectRepositories(projectId: number,connectionId: number,@@ -439,15 +442,15 @@ export async function connectRepositories();const existingIds = new Set(existing.map((repo) => repo.externalId));const settings = await getOrCreateGitSettings(projectId);- const payloadUrl = webhookPayloadUrl(settings);for (const externalId of ids) {if (existingIds.has(externalId)) continue;const repository = await getProviderRepository(providerInput(connection), externalId);const webhookExternalId = await installProviderWebhook(providerInput(connection),repository,- payloadUrl,+ settings.payloadUrl,settings.secret,+ null,);await db.insert(gitManagedRepository).values({projectId,@@ -525,33 +528,19 @@ export async function reconcileManagedWebhooks(settings: GitSettings,): Promise<void> {const connections = await listGitProviderConnections(projectId);- const payloadUrl = webhookPayloadUrl(settings);for (const item of connections) {- const connection = await connectionSecret(item.id, projectId);- for (const repository of item.repositories) {- try {- const webhookExternalId = await installProviderWebhook(- providerInput(connection),- {- externalId: repository.externalId,- fullName: repository.fullName,- webUrl: repository.webUrl,- private: false,- },- payloadUrl,- settings.secret,- );- await db- .update(gitManagedRepository)- .set({ webhookExternalId, status: 'connected', lastError: null, updatedAt: new Date() })- .where(eq(gitManagedRepository.id, repository.id));- } catch (error) {- const message = error instanceof Error ? error.message : 'Webhook update failed';- await db- .update(gitManagedRepository)- .set({ status: 'error', lastError: message, updatedAt: new Date() })- .where(eq(gitManagedRepository.id, repository.id));- }+ const input = providerInput(await connectionSecret(item.id, projectId));+ const repositories = await db+ .select()+ .from(gitManagedRepository)+ .where(+ and(+ eq(gitManagedRepository.projectId, projectId),+ eq(gitManagedRepository.connectionId, item.id),+ ),+ );+ for (const repository of repositories) {+ await reconcileRepositoryWebhook(input, repository, settings);}}}diff --git a/apps/api/src/modules/git/model.ts b/apps/api/src/modules/git/model.tsindex 546faba9..55842101 100644--- a/apps/api/src/modules/git/model.ts+++ b/apps/api/src/modules/git/model.ts@@ -53,6 +53,7 @@ export const DevelopmentLinkResponse = t.Object({export const GitSettingsResponse = t.Object({enabled: t.Boolean(),webhookId: t.String(),+ payloadUrl: t.String(),secret: t.String(),onMergeColumnId: t.Nullable(t.Number()),onOpenColumnId: t.Nullable(t.Number()),diff --git a/apps/api/src/modules/git/service.ts b/apps/api/src/modules/git/service.tsindex 4c399849..255deecd 100644--- a/apps/api/src/modules/git/service.ts+++ b/apps/api/src/modules/git/service.ts@@ -46,6 +46,7 @@ export interface GitRepository {export interface GitSettings {enabled: boolean;webhookId: string;+ payloadUrl: string;secret: string;onMergeColumnId: number | null;onOpenColumnId: number | null;@@ -53,10 +54,19 @@ export interface GitSettings {repositories: GitRepository[];}+// GIT_WEBHOOK_BASE_URL is the public origin for an instance whose API_URL is reachable+// only from a private network.+function webhookPayloadUrl(webhookId: string): string {+ const base = process.env.GIT_WEBHOOK_BASE_URL || process.env.API_URL;+ if (!base) throw new HttpError(500, 'API_URL is not configured');+ return `${base.replace(/\/+$/, '')}/webhooks/git/${webhookId}`;+}+function toDto(stored: StoredGitSettings): GitSettings {const { recentDeliveries: _internal, ...rest } = stored;return {...rest,+ payloadUrl: webhookPayloadUrl(stored.webhookId),linkbackComments: stored.linkbackComments ?? true,secret: decryptSecret(stored.secret),repositories: stored.repositories ?? [],diff --git a/apps/web/src/features/settings/components/git/GitConnectionCard.tsx b/apps/web/src/features/settings/components/git/GitConnectionCard.tsxindex 418e0dcc..8cf7e9e9 100644--- a/apps/web/src/features/settings/components/git/GitConnectionCard.tsx+++ b/apps/web/src/features/settings/components/git/GitConnectionCard.tsx@@ -2,7 +2,6 @@ import { useState } from 'react';import { toast } from 'sonner';import { useTranslations } from 'next-intl';import type { GitSettings } from '@/lib/api/endpoints/git';-import { API_URL } from '@/lib/api/core/client';import SettingsCard from '@/components/common/page/SettingsCard';import SettingsSection from '@/components/common/page/SettingsSection';import { Button } from '@/components/ui/button';@@ -44,7 +43,6 @@ export default function GitConnectionCard({const t = useTranslations('settings.git');const regenerate = useRegenerateGitSecret(projectKey);const [tab, setTab] = useState<ProviderKey>(() => initialTab(settings.repositories[0]?.provider));- const payloadUrl = `${API_URL}/webhooks/git/${settings.webhookId}`;async function regenerateSecret() {await regenerate.mutateAsync();@@ -77,7 +75,7 @@ export default function GitConnectionCard({{/* One URL and one secret serve every host — they sit above the tabs,which carry nothing but each host's instructions. */}<div className="space-y-4 p-4">- <GitCopyField label={t('payloadUrl')} value={payloadUrl} />+ <GitCopyField label={t('payloadUrl')} value={settings.payloadUrl} /><GitCopyFieldlabel={t('webhookSecret')}value={settings.secret}@@ -105,10 +103,10 @@ export default function GitConnectionCard({<TabsContent key={p.key} value={p.key} className="mt-4 space-y-4">{hint(p.hint)}{p.key === 'github' && (- <GithubCliCommand payloadUrl={payloadUrl} secret={settings.secret} />+ <GithubCliCommand payloadUrl={settings.payloadUrl} secret={settings.secret} />)}{p.key === 'gitlab' && (- <GitlabCliCommand payloadUrl={payloadUrl} secret={settings.secret} />+ <GitlabCliCommand payloadUrl={settings.payloadUrl} secret={settings.secret} />)}</TabsContent>))}diff --git a/apps/web/src/lib/api/endpoints/git.ts b/apps/web/src/lib/api/endpoints/git.tsindex e56ebe99..e3904011 100644--- a/apps/web/src/lib/api/endpoints/git.ts+++ b/apps/web/src/lib/api/endpoints/git.ts@@ -1,13 +1,14 @@import { request } from '@/lib/api/core/client';// Per-project repository integration settings, shared by every provider.-// webhookId is the path segment of the payload URL registered on the repository;-// secret authenticates its deliveries. onMergeColumnId is where an issue closed by a merged pull+// payloadUrl is the URL registered on the repository, and webhookId its last path+// segment; secret authenticates its deliveries. onMergeColumnId is where an issue closed by a merged pull// request moves (null = the first completed state); onOpenColumnId is where an// issue moves when a linked pull request is opened (null = no action).export interface GitSettings {enabled: boolean;webhookId: string;+ payloadUrl: string;secret: string;onMergeColumnId: number | null;onOpenColumnId: number | null;diff --git a/charts/itsaplan/README.md b/charts/itsaplan/README.mdindex 467c4e45..cc5b7d11 100644--- a/charts/itsaplan/README.md+++ b/charts/itsaplan/README.md@@ -184,6 +184,7 @@ bot:| `api.env.API_URL` | Public API origin | `""` || `api.env.APP_URL` | Public web origin | `""` || `api.env.COOKIE_DOMAIN` | Cookie domain override | (unset) |+| `api.env.GIT_WEBHOOK_BASE_URL` | Public origin for incoming Git webhooks | (unset, uses `API_URL`) || `api.env.S3_BUCKET` | S3 bucket name | `""` || `api.env.S3_REGION` | S3 region | `us-east-1` || `api.env.S3_FORCE_PATH_STYLE` | S3 path-style access | `"true"` |diff --git a/charts/itsaplan/templates/configmap.yaml b/charts/itsaplan/templates/configmap.yamlindex b5546864..3a61b160 100644--- a/charts/itsaplan/templates/configmap.yaml+++ b/charts/itsaplan/templates/configmap.yaml@@ -14,6 +14,9 @@ data:{{- with .Values.api.env.COOKIE_DOMAIN }}COOKIE_DOMAIN: {{ . | quote }}{{- end }}+ {{- with .Values.api.env.GIT_WEBHOOK_BASE_URL }}+ GIT_WEBHOOK_BASE_URL: {{ . | quote }}+ {{- end }}S3_BUCKET: {{ .Values.api.env.S3_BUCKET | quote }}S3_REGION: {{ .Values.api.env.S3_REGION | quote }}S3_ENDPOINT: {{ include "itsaplan.s3Endpoint" . | quote }}diff --git a/charts/itsaplan/values.yaml b/charts/itsaplan/values.yamlindex 5898ac6d..36f84430 100644--- a/charts/itsaplan/values.yaml+++ b/charts/itsaplan/values.yaml@@ -40,6 +40,8 @@ api:API_URL: ""APP_URL: ""# COOKIE_DOMAIN: ""+ # Public origin for incoming Git webhooks when API_URL is private; unset uses API_URL.+ # GIT_WEBHOOK_BASE_URL: ""S3_BUCKET: ""S3_REGION: "us-east-1"S3_FORCE_PATH_STYLE: "true"diff --git a/docker-compose.coolify-images.yml b/docker-compose.coolify-images.ymlindex a297510e..0850a65c 100644--- a/docker-compose.coolify-images.yml+++ b/docker-compose.coolify-images.yml@@ -135,6 +135,8 @@ services:- APP_URL=${SERVICE_URL_WEB}# To override the cookie parent domain (multi-label TLDs / deep subdomains),# add a COOKIE_DOMAIN env in Coolify — the code reads it if present.+ # Public origin for incoming Git webhooks when API_URL is private; empty uses API_URL.+ - GIT_WEBHOOK_BASE_URL=${GIT_WEBHOOK_BASE_URL:-}- S3_ENDPOINT=http://minio:9000- S3_BUCKET=${S3_BUCKET:-planner-attachments}- S3_ACCESS_KEY_ID=${SERVICE_USER_MINIO}diff --git a/docker-compose.coolify.yml b/docker-compose.coolify.ymlindex d1abb242..e07a84c1 100644--- a/docker-compose.coolify.yml+++ b/docker-compose.coolify.yml@@ -132,6 +132,8 @@ services:APP_URL: ${SERVICE_URL_WEB:-http://localhost:3001}# To override the cookie parent domain (multi-label TLDs / deep subdomains),# add a COOKIE_DOMAIN env in Coolify — the code reads it if present.+ # Public origin for incoming Git webhooks when API_URL is private; empty uses API_URL.+ GIT_WEBHOOK_BASE_URL: ${GIT_WEBHOOK_BASE_URL:-}S3_ENDPOINT: http://minio:9000S3_BUCKET: ${S3_BUCKET:-planner-attachments}S3_ACCESS_KEY_ID: ${SERVICE_USER_MINIO}diff --git a/docker-compose.yml b/docker-compose.ymlindex d43f45ca..30017a41 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -132,6 +132,8 @@ services:# Set COOKIE_DOMAIN only to override the parent domain derived from# APP_URL (multi-label TLDs, deep subdomains).COOKIE_DOMAIN: ${COOKIE_DOMAIN:-}+ # Public origin for incoming Git webhooks when API_URL is private; empty uses API_URL.+ GIT_WEBHOOK_BASE_URL: ${GIT_WEBHOOK_BASE_URL:-}S3_ENDPOINT: http://minio:9000S3_BUCKET: ${S3_BUCKET:-planner-attachments}S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID}diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 81a9ec83..1c935143 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -76,6 +76,24 @@ The OAuth redirect URIs that god mode shows include the path. An api on a differregistrable domain than the web app (`api.other.com`) does not work: the session cookiecannot be shared across sites.+### Git webhooks on a private instance++GitHub, GitLab, Gitea, Forgejo and Bitbucket deliver repository webhooks to+`<API_URL>/webhooks/git/<id>`. When `API_URL` is reachable only over a VPN or a private+network, expose that one route on a public hostname at the reverse proxy and set+`GIT_WEBHOOK_BASE_URL` to its origin:++```+GIT_WEBHOOK_BASE_URL=https://hooks.example.com+https://hooks.example.com/webhooks/git/* -> api:3000/webhooks/git/*+```++It changes only the payload URL: the settings page shows it, and the webhooks the instance+manages through a provider connection are created with it. A connected repository's existing+webhook is updated in place on the next reconcile: saving the provider token again, or+regenerating the project's webhook secret. Deliveries are still authenticated by the+project's secret. Auth, email links, the browser and MCP keep using `API_URL`.+The instance sends password resets, address confirmations, sign-in links and invites through