Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(scm): GitHub App ingress, install flow and change-request tracking (#19721)

Arvin Xuf17ee0df57ca
diff --git a/.env.example b/.env.example
index 2b596fc730d..e8d8a3b38b2 100644
--- a/.env.example
+++ b/.env.example
@@ -375,6 +375,20 @@ OPENAI_API_KEY=sk-xxxxxxxxx
# GITHUB_CLIENT_ID=Ov23xxxxxxxxxxxxx
# GITHUB_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+# GitHub App (SCM integration: CI results, reviews and merges flow back to LobeHub)
+# Create the app at https://github.com/settings/apps (or under your org) with:
+# - Webhook URL: https://yourdomain.com/api/webhooks/github
+# - Callback URL: https://yourdomain.com/api/webhooks/github/oauth/callback
+# - Setup URL: https://yourdomain.com/api/webhooks/github/setup (Redirect on update)
+# - "Request user authorization (OAuth) during installation" enabled
+# The private key is the .pem base64-encoded once: `base64 -i key.pem | tr -d '\n'`
+# GITHUB_APP_ID=123456
+# GITHUB_APP_SLUG=lobehub
+# GITHUB_APP_CLIENT_ID=Iv23xxxxxxxxxxxxx
+# GITHUB_APP_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+# GITHUB_APP_PRIVATE_KEY=LS0tLS1CRUdJTi...
+# GITHUB_APP_WEBHOOK_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+
# AWS Cognito OAuth Configuration (for Better-Auth)
# Get credentials from: https://console.aws.amazon.com/cognito
# Setup steps:
diff --git a/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts b/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts
index f5a0f2967c4..7ff6e15241d 100644
--- a/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts
+++ b/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts
@@ -12,6 +12,9 @@ import app from '../index';
* the db clients, which is far more than a routing assertion needs.
*/
vi.mock('../handlers/casdoor', () => ({ casdoorWebhook: vi.fn() }));
+vi.mock('../handlers/github', () => ({ githubWebhook: vi.fn() }));
+vi.mock('../handlers/githubInstall', () => ({ githubInstall: vi.fn() }));
+vi.mock('../handlers/githubSetup', () => ({ githubSetup: vi.fn() }));
vi.mock('../handlers/logto', () => ({ logtoWebhook: vi.fn() }));
vi.mock('../handlers/memoryExtraction', () => ({ memoryExtractionWebhook: vi.fn() }));
vi.mock('../handlers/memoryExtractionBenchmarkLocomo', () => ({
@@ -31,6 +34,7 @@ describe('webhooks hono routes', () => {
expect([...new Set(paths)].sort()).toEqual([
'/api/webhooks/casdoor',
+ '/api/webhooks/github',
'/api/webhooks/logto',
'/api/webhooks/memory-extraction',
'/api/webhooks/memory-extraction/benchmark-locomo',
@@ -39,4 +43,14 @@ describe('webhooks hono routes', () => {
'/api/webhooks/video/:provider',
]);
});
+
+ it('serves the GitHub App install and setup redirects as GET', () => {
+ const paths = app.routes.filter((route) => route.method === 'GET').map((route) => route.path);
+
+ expect([...new Set(paths)].sort()).toEqual([
+ '/api/webhooks/github/install',
+ '/api/webhooks/github/oauth/callback',
+ '/api/webhooks/github/setup',
+ ]);
+ });
});
diff --git a/apps/server/src/router-hono/webhooks/handlers/__tests__/github.test.ts b/apps/server/src/router-hono/webhooks/handlers/__tests__/github.test.ts
new file mode 100644
index 00000000000..a415389bb26
--- /dev/null
+++ b/apps/server/src/router-hono/webhooks/handlers/__tests__/github.test.ts
@@ -0,0 +1,127 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { Hono } from 'hono';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ScmChangeRequestModel, ScmInstallationModel } from '@/database/models/scm';
+import { scmWebhookDeliveries, users } from '@/database/schemas';
+import * as fx from '@/server/services/scm/github/__tests__/fixtures';
+import { signGitHubPayload } from '@/server/services/scm/github/signature';
+
+import { githubWebhook } from '../github';
+
+const serverDB = await getTestDB();
+const secret = 'webhook-secret';
+const userId = 'scm-webhook-user';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(async () => serverDB),
+}));
+
+vi.mock('@/envs/scm', () => ({
+ scmEnv: { ENABLED_GITHUB_APP: true, GITHUB_APP_WEBHOOK_SECRET: 'webhook-secret' },
+}));
+
+const app = new Hono().post('/github', githubWebhook);
+
+const deliver = (
+ event: string,
+ payload: Record<string, unknown>,
+ options: { deliveryId?: string; signature?: string } = {},
+) => {
+ const body = JSON.stringify(payload);
+ return app.request('/github', {
+ body,
+ headers: {
+ 'content-type': 'application/json',
+ 'x-github-delivery': options.deliveryId ?? `delivery-${Math.random()}`,
+ 'x-github-event': event,
+ 'x-hub-signature-256': options.signature ?? signGitHubPayload(body, secret),
+ },
+ method: 'POST',
+ });
+};
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await ScmInstallationModel.bind(serverDB, {
+ accountExternalId: '1',
+ accountLogin: 'lobehub',
+ accountType: 'organization',
+ installationId: String(fx.installation.id),
+ provider: 'github',
+ repositorySelection: 'all',
+ userId,
+ });
+});
+
+afterEach(async () => {
+ await serverDB.delete(scmWebhookDeliveries);
+ await serverDB.delete(users);
+});
+
+describe('githubWebhook', () => {
+ it('rejects a bad signature before touching the database', async () => {
+ const res = await deliver('pull_request', fx.pullRequestEvent('opened'), {
+ signature: 'sha256=deadbeef',
+ });
+ expect(res.status).toBe(401);
+ expect(await serverDB.select().from(scmWebhookDeliveries)).toHaveLength(0);
+ });
+
+ it('rejects a delivery without event headers', async () => {
+ const body = JSON.stringify(fx.pullRequestEvent('opened'));
+ const res = await app.request('/github', {
+ body,
+ headers: { 'x-hub-signature-256': signGitHubPayload(body, secret) },
+ method: 'POST',
+ });
+ expect(res.status).toBe(400);
+ });
+
+ it('processes a signed delivery once and answers duplicates without re-applying', async () => {
+ const first = await deliver('pull_request', fx.pullRequestEvent('opened'), {
+ deliveryId: 'd-1',
+ });
+ expect(first.status).toBe(200);
+ expect(await first.json()).toMatchObject({ ok: true, status: 'processed' });
+
+ const row = await ScmChangeRequestModel.findByIdentity(
+ serverDB,
+ 'github',
+ 'lobehub/lobehub',
+ 19_719,
+ );
+ expect(row?.state).toBe('open');
+
+ const again = await deliver(
+ 'pull_request',
+ fx.pullRequestEvent('closed', { state: 'closed' }),
+ {
+ deliveryId: 'd-1',
+ },
+ );
+ expect(again.status).toBe(200);
+ expect(await again.json()).toMatchObject({ duplicate: true });
+ expect(
+ (await ScmChangeRequestModel.findByIdentity(serverDB, 'github', 'lobehub/lobehub', 19_719))
+ ?.state,
+ ).toBe('open');
+
+ const ledger = await serverDB.select().from(scmWebhookDeliveries);
+ expect(ledger).toHaveLength(1);
+ expect(ledger[0]).toMatchObject({
+ action: 'opened',
+ event: 'pull_request',
+ status: 'processed',
+ });
+ });
+
+ it('records ignored events as skipped with the reason', async () => {
+ const res = await deliver('ping', { zen: 'Keep it logically awesome.' }, { deliveryId: 'd-2' });
+ expect(res.status).toBe(200);
+ const [ledger] = await serverDB.select().from(scmWebhookDeliveries);
+ expect(ledger).toMatchObject({ status: 'skipped' });
+ expect(ledger.error).toContain('not tracked');
+ });
+});
diff --git a/apps/server/src/router-hono/webhooks/handlers/__tests__/githubInstall.test.ts b/apps/server/src/router-hono/webhooks/handlers/__tests__/githubInstall.test.ts
new file mode 100644
index 00000000000..e30e1eba002
--- /dev/null
+++ b/apps/server/src/router-hono/webhooks/handlers/__tests__/githubInstall.test.ts
@@ -0,0 +1,88 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { Hono } from 'hono';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { users, workspaceMembers, workspaces } from '@/database/schemas';
+
+import { githubInstall } from '../githubInstall';
+
+const serverDB = await getTestDB();
+const userId = 'scm-install-user';
+
+const mocks = vi.hoisted(() => ({
+ getSession: vi.fn(),
+ issueState: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => serverDB) }));
+vi.mock('@/envs/scm', () => ({ scmEnv: { ENABLED_GITHUB_APP: true, GITHUB_APP_SLUG: 'dev' } }));
+vi.mock('@/auth', () => ({ auth: { api: { getSession: mocks.getSession } } }));
+vi.mock('@/server/services/scm/oauth/stateStore', () => ({
+ issueScmInstallState: mocks.issueState,
+}));
+vi.mock('@/server/services/scm/github/app', () => ({
+ buildGitHubInstallUrl: (state: string) =>
+ `https://github.com/apps/dev/installations/new?state=${state}`,
+}));
+
+const app = new Hono().get('/install', githubInstall);
+const install = (query: Record<string, string>) =>
+ app.request(`http://localhost/install?${new URLSearchParams(query)}`);
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ mocks.getSession.mockResolvedValue({ user: { id: userId } });
+ mocks.issueState.mockResolvedValue('state-1');
+});
+
+afterEach(async () => {
+ await serverDB.delete(workspaces);
+ await serverDB.delete(users);
+ vi.clearAllMocks();
+});
+
+describe('githubInstall', () => {
+ it('issues a state for the session user and sends them to GitHub', async () => {
+ const res = await install({ returnTo: '/settings/integrations/github' });
+ expect(res.status).toBe(302);
+ expect(res.headers.get('location')).toBe(
+ 'https://github.com/apps/dev/installations/new?state=state-1',
+ );
+ expect(mocks.issueState).toHaveBeenCalledWith({
+ lobeUserId: userId,
+ returnTo: '/settings/integrations/github',
+ workspaceId: null,
+ });
+ });
+
+ it('drops a cross-origin returnTo before it reaches the state', async () => {
+ await install({ returnTo: 'https://evil.example/phish' });
+ expect(mocks.issueState).toHaveBeenCalledWith(expect.objectContaining({ returnTo: undefined }));
+ });
+
+ it('lets members install into a workspace but not viewers', async () => {
+ const [workspace] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'ws', primaryOwnerId: userId, slug: 'scm-install-ws' })
+ .returning();
+
+ await serverDB
+ .insert(workspaceMembers)
+ .values({ role: 'viewer', userId, workspaceId: workspace.id });
+ const denied = await install({ workspaceId: workspace.id });
+ expect(denied.status).toBe(403);
+ expect(mocks.issueState).not.toHaveBeenCalled();
+
+ await serverDB
+ .update(workspaceMembers)
+ .set({ role: 'member' })
+ .where(eq(workspaceMembers.workspaceId, workspace.id));
+ const allowed = await install({ workspaceId: workspace.id });
+ expect(allowed.status).toBe(302);
+ expect(mocks.issueState).toHaveBeenCalledWith(
+ expect.objectContaining({ workspaceId: workspace.id }),
+ );
+ });
+});
diff --git a/apps/server/src/router-hono/webhooks/handlers/__tests__/githubSetup.test.ts b/apps/server/src/router-hono/webhooks/handlers/__tests__/githubSetup.test.ts
new file mode 100644
index 00000000000..4a540a527bf
--- /dev/null
+++ b/apps/server/src/router-hono/webhooks/handlers/__tests__/githubSetup.test.ts
@@ -0,0 +1,255 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { Hono } from 'hono';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ScmIdentityModel, ScmInstallationModel } from '@/database/models/scm';
+import { scmWebhookDeliveries, users } from '@/database/schemas';
+
+import { githubSetup } from '../githubSetup';
+
+const serverDB = await getTestDB();
+const userId = 'scm-setup-user';
+
+const mocks = vi.hoisted(() => ({
+ consumeState: vi.fn(),
+ issueClaim: vi.fn(),
+ scmEnv: { ENABLED_GITHUB_APP: true, ENABLED_GITHUB_APP_OAUTH: true },
+ canAccessInstallation: vi.fn(),
+ exchangeCode: vi.fn(),
+ fetchInstallation: vi.fn(),
+ getSession: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => serverDB) }));
+vi.mock('@/envs/scm', () => ({ scmEnv: mocks.scmEnv }));
+vi.mock('@/auth', () => ({ auth: { api: { getSession: mocks.getSession } } }));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: async () => undefined },
+}));
+vi.mock('@/server/services/scm/oauth/stateStore', () => ({
+ consumeScmInstallState: mocks.consumeState,
+ issueScmInstallClaim: mocks.issueClaim,
+}));
+vi.mock('@/server/services/scm/github/app', () => ({
+ exchangeGitHubUserCode: mocks.exchangeCode,
+ fetchGitHubInstallation: mocks.fetchInstallation,
+ userCanAccessInstallation: mocks.canAccessInstallation,
+}));
+
+const app = new Hono().get('/setup', githubSetup);
+const setup = (query: Record<string, string>) =>
+ app.request(`http://localhost/setup?${new URLSearchParams(query)}`);
+
+const snapshot = {
+ accountExternalId: '1',
+ accountLogin: 'arvinxx',
+ accountType: 'user' as const,
+ installationId: '777',
+ provider: 'github' as const,
+ repositorySelection: 'selected' as const,
+ repositories: [{ externalId: '9', fullName: 'arvinxx/sandbox' }],
+};
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: userId }, { id: 'scm-setup-other' }]);
+ mocks.consumeState.mockResolvedValue(null);
+ mocks.issueClaim.mockResolvedValue('claim-token');
+ mocks.getSession.mockResolvedValue(null);
+ mocks.scmEnv.ENABLED_GITHUB_APP_OAUTH = true;
+ mocks.fetchInstallation.mockResolvedValue(snapshot);
+ mocks.canAccessInstallation.mockResolvedValue(true);
+ mocks.exchangeCode.mockResolvedValue({
+ accessToken: 'ghu_token',
+ user: { externalId: '42', login: 'arvinxx' },
+ });
+});
+
+afterEach(async () => {
+ await serverDB.delete(scmWebhookDeliveries);
+ await serverDB.delete(users);
+ vi.clearAllMocks();
+});
+
+describe('githubSetup', () => {
+ it('bounces to sign-in when neither state nor session identifies a user', async () => {
+ const res = await setup({ code: 'c', installation_id: '777' });
+ expect(res.status).toBe(302);
+ expect(res.headers.get('location')).toContain('/signin?callbackUrl=');
+ });
+
+ it('binds the installation and identity on the code leg using the state user', async () => {
+ mocks.consumeState.mockResolvedValue({ lobeUserId: userId, ts: 1 });
+
+ const res = await setup({ code: 'c', installation_id: '777', state: 's' });
+ expect(res.status).toBe(302);
+ const location = new URL(res.headers.get('location')!);
+ expect(location.pathname).toBe('/settings/integrations/github');
+ expect(Object.fromEntries(location.searchParams)).toEqual({
+ account: 'arvinxx',
+ installed: 'ok',
+ });
+
+ const installation = await ScmInstallationModel.findByProviderInstallationId(
+ serverDB,
+ 'github',
+ '777',
+ );
+ expect(installation).toMatchObject({
+ installedByExternalLogin: 'arvinxx',
+ repositories: snapshot.repositories,
+ userId,
+ workspaceId: null,
+ });
+ expect(await ScmIdentityModel.findByExternalUser(serverDB, 'github', '42')).toMatchObject({
+ externalLogin: 'arvinxx',
+ userId,
+ });
+ });
+
+ it('never binds or links without our state: a known own installation is refreshed, anything else is handed over as pending', async () => {
+ mocks.getSession.mockResolvedValue({ user: { id: userId } });
+
+ // Unknown installation, no state: no bind, no code exchange, confirm in the app.
+ const first = await setup({
+ code: 'attacker-code',
+ installation_id: '777',
+ setup_action: 'install',
+ });
+ const firstLocation = new URL(first.headers.get('location')!);
+ // The confirmation carries a single-use claim, never the raw id.
+ expect(Object.fromEntries(firstLocation.searchParams)).toEqual({
+ account: 'arvinxx',
+ pending: 'claim-token',
+ });
+ expect(mocks.issueClaim).toHaveBeenCalledWith({
+ installationId: '777',
+ lobeUserId: userId,
+ provider: 'github',
+ });
+ expect(mocks.exchangeCode).not.toHaveBeenCalled();
+ expect(
+ await ScmInstallationModel.findByProviderInstallationId(serverDB, 'github', '777'),
+ ).toBeNull();
+
+ // Someone else's installation: also pending, never refreshed into their row.
+ await ScmInstallationModel.bind(serverDB, { ...snapshot, userId: 'scm-setup-other' });
+ const theirs = await setup({ installation_id: '777', setup_action: 'update' });
+ expect(new URL(theirs.headers.get('location')!).searchParams.get('pending')).toBe(
+ 'claim-token',
+ );
+ expect(
+ (await ScmInstallationModel.findByProviderInstallationId(serverDB, 'github', '777'))
+ ?.repositories,
+ ).toEqual(snapshot.repositories);
+
+ // The session user's own installation is refreshed from the API.
+ await ScmInstallationModel.bind(serverDB, { ...snapshot, userId });
+ mocks.fetchInstallation.mockResolvedValue({ ...snapshot, repositories: [] });
+ const second = await setup({ installation_id: '777', setup_action: 'update' });
+ expect(new URL(second.headers.get('location')!).searchParams.get('installed')).toBe('updated');
+ const refreshed = await ScmInstallationModel.findByProviderInstallationId(
+ serverDB,
+ 'github',
+ '777',
+ );
+ expect(refreshed?.repositories).toEqual([]);
+ });
+
+ it('binds without linking an identity when the deployment has no OAuth credentials', async () => {
+ mocks.scmEnv.ENABLED_GITHUB_APP_OAUTH = false;
+ mocks.consumeState.mockResolvedValue({ lobeUserId: userId, ts: 1 });
+
+ // GitHub still appends a code when the App asks for user authorization;
+ // exchanging it without credentials can only fail, so the install
+ // proceeds and only the identity link is skipped.
+ const res = await setup({ code: 'c', installation_id: '777', state: 's' });
+ expect(new URL(res.headers.get('location')!).searchParams.get('installed')).toBe('ok');
+ expect(mocks.exchangeCode).not.toHaveBeenCalled();
+ expect(
+ await ScmInstallationModel.findByProviderInstallationId(serverDB, 'github', '777'),
+ ).toMatchObject({ installedByExternalLogin: null, userId });
+ });
+
+ it('binds without an identity when the state is valid but GitHub sent no code', async () => {
+ mocks.consumeState.mockResolvedValue({ lobeUserId: userId, ts: 1 });
+
+ const res = await setup({ installation_id: '777', setup_action: 'install', state: 's' });
+ expect(new URL(res.headers.get('location')!).searchParams.get('installed')).toBe('ok');
+ expect(mocks.exchangeCode).not.toHaveBeenCalled();
+ expect(
+ await ScmInstallationModel.findByProviderInstallationId(serverDB, 'github', '777'),
+ ).toMatchObject({ installedByExternalLogin: null, userId });
+ });
+
+ it('only follows same-origin return destinations from the state', async () => {
+ mocks.consumeState.mockResolvedValue({
+ lobeUserId: userId,
+ returnTo: 'https://evil.example/phish',
+ ts: 1,
+ });
+
+ const res = await setup({ code: 'c', installation_id: '777', state: 's' });
+ const location = new URL(res.headers.get('location')!);
+ expect(location.origin).toBe('http://localhost');
+ expect(location.pathname).toBe('/settings/integrations/github');
+ });
+
+ it('refuses an installation the authorizing GitHub user cannot see', async () => {
+ mocks.consumeState.mockResolvedValue({ lobeUserId: userId, ts: 1 });
+ mocks.canAccessInstallation.mockResolvedValue(false);
+
+ // A valid state of one's own plus a guessed installation id would
+ // otherwise move someone else's installation into this scope.
+ const res = await setup({ code: 'c', installation_id: '777', state: 's' });
+ expect(new URL(res.headers.get('location')!).searchParams.get('error')).toBe(
+ 'installation_not_yours',
+ );
+ expect(
+ await ScmInstallationModel.findByProviderInstallationId(serverDB, 'github', '777'),
+ ).toBeNull();
+ });
+
+ it('never rebinds an installation that is connected elsewhere', async () => {
+ await serverDB.insert(users).values({ id: 'scm-setup-owner' });
+ await ScmInstallationModel.bind(serverDB, { ...snapshot, userId: 'scm-setup-owner' });
+ mocks.consumeState.mockResolvedValue({ lobeUserId: userId, ts: 1 });
+
+ const res = await setup({ code: 'c', installation_id: '777', state: 's' });
+ expect(new URL(res.headers.get('location')!).searchParams.get('error')).toBe(
+ 'installation_taken',
+ );
+ expect(
+ (await ScmInstallationModel.findByProviderInstallationId(serverDB, 'github', '777'))?.userId,
+ ).toBe('scm-setup-owner');
+ });
+
+ it('refuses to move a GitHub identity to a second LobeHub account', async () => {
+ await serverDB.insert(users).values({ id: 'scm-setup-first' });
+ mocks.consumeState.mockResolvedValue({ lobeUserId: 'scm-setup-first', ts: 1 });
+ await setup({ code: 'c', installation_id: '777', state: 's' });
+ expect(await ScmIdentityModel.findByExternalUser(serverDB, 'github', '42')).toMatchObject({
+ userId: 'scm-setup-first',
+ });
+
+ // The same GitHub account authorizing from another LobeHub account must
+ // not carry the stored token across; the row keeps its owner.
+ mocks.consumeState.mockResolvedValue({ lobeUserId: userId, ts: 1 });
+ const res = await setup({ code: 'c', installation_id: '778', state: 's' });
+ expect(new URL(res.headers.get('location')!).searchParams.get('error')).toBe('identity_taken');
+ expect(await ScmIdentityModel.findByExternalUser(serverDB, 'github', '42')).toMatchObject({
+ userId: 'scm-setup-first',
+ });
+ });
+
+ it('reports a failed code exchange instead of binding', async () => {
+ mocks.consumeState.mockResolvedValue({ lobeUserId: userId, ts: 1 });
+ mocks.exchangeCode.mockRejectedValue(new Error('bad_verification_code'));
+
+ const res = await setup({ code: 'expired', installation_id: '777', state: 's' });
+ expect(new URL(res.headers.get('location')!).searchParams.get('error')).toBe('exchange_failed');
+ expect(
+ await ScmInstallationModel.findByProviderInstallationId(serverDB, 'github', '777'),
+ ).toBeNull();
+ });
+});
diff --git a/apps/server/src/router-hono/webhooks/handlers/github.ts b/apps/server/src/router-hono/webhooks/handlers/github.ts
new file mode 100644
index 00000000000..8997c85bb54
--- /dev/null
+++ b/apps/server/src/router-hono/webhooks/handlers/github.ts
@@ -0,0 +1,107 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { getServerDB } from '@/database/core/db-adaptor';
+import { ScmWebhookDeliveryModel } from '@/database/models/scm';
+import { scmEnv } from '@/envs/scm';
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+import {
+ describeGitHubDelivery,
+ normalizeGitHubEvent,
+} from '@/server/services/scm/github/normalize';
+import { verifyGitHubSignature } from '@/server/services/scm/github/signature';
+import { ScmIngestService } from '@/server/services/scm/ScmIngestService';
+
+/**
+ * The ledger grows with every accepted delivery, so it is swept from the
+ * ingress itself rather than from a scheduler this deployment may not run.
+ * A Redis claim keeps it to one sweep a day across every instance; without
+ * Redis the sweep is skipped rather than run on every request.
+ */
+const pruneDeliveryLedger = async (db: Awaited<ReturnType<typeof getServerDB>>) => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return;
+ if ((await redis.set('scm:delivery-prune', '1', 'EX', 86_400, 'NX')) !== 'OK') return;
+
+ const before = new Date(Date.now() - ScmWebhookDeliveryModel.RETENTION_DAYS * 86_400_000);
+ const pruned = await ScmWebhookDeliveryModel.pruneBefore(db, before);
+ log('pruned %d webhook deliveries received before %s', pruned, before.toISOString());
+};
+
+const log = debug('lobe-server:scm:github-webhook');
+
+/**
+ * Inbound GitHub App webhook. Order matters:
+ *
+ * 1. Verify the signature over the raw bytes β€” before parsing, before any
+ * database read, so an unsigned request costs nothing.
+ * 2. Claim the delivery id. GitHub retries and redelivers; the ledger's
+ * primary key makes the second copy a no-op 200.
+ * 3. Normalize + apply. A thrown handler settles the ledger row as `failed`
+ * and answers 500 so the delivery shows red in the App's delivery log and
+ * can be redelivered (with a fresh id) once the cause is fixed.
+ */
+export const githubWebhook = async (c: Context): Promise<Response> => {
+ const secret = scmEnv.GITHUB_APP_WEBHOOK_SECRET;
+ if (!secret) return c.json({ error: 'GitHub App webhook is not configured' }, 503);
+
+ const rawBody = await c.req.text();
+ const verified = verifyGitHubSignature({
+ rawBody,
+ secret,
+ signature: c.req.header('x-hub-signature-256'),
+ });
+ if (!verified) return c.json({ error: 'invalid signature' }, 401);
+
+ const event = c.req.header('x-github-event');
+ const deliveryId = c.req.header('x-github-delivery');
+ if (!event || !deliveryId) return c.json({ error: 'missing event headers' }, 400);
+
+ let payload: Record<string, any>;
+ try {
+ payload = JSON.parse(rawBody);
+ } catch {
+ return c.json({ error: 'invalid JSON body' }, 400);
+ }
+
+ const db = await getServerDB();
+ const described = describeGitHubDelivery(payload);
+ const claimed = await ScmWebhookDeliveryModel.claim(db, {
+ ...described,
+ deliveryId,
+ event,
+ provider: 'github',
+ });
+ if (!claimed) {
+ log('duplicate delivery %s (%s.%s)', deliveryId, event, described.action ?? '-');
+ return c.json({ duplicate: true, ok: true });
+ }
+
+ const key = { deliveryId, provider: 'github' as const };
+ try {
+ const normalized = normalizeGitHubEvent(event, payload);
+ const outcome = await new ScmIngestService(db).apply(normalized);
+ await ScmWebhookDeliveryModel.settle(db, key, {
+ error: outcome.detail,
+ status: outcome.status,
+ });
+ log(
+ '%s.%s delivery=%s -> %s %s',
+ event,
+ described.action ?? '-',
+ deliveryId,
+ outcome.status,
+ outcome.detail ?? '',
+ );
+ // After the response path is settled, not before: retention must never
+ // decide whether a delivery is accepted.
+ await pruneDeliveryLedger(db).catch((error) => log('delivery prune failed: %O', error));
+
+ return c.json({ ok: true, ...outcome });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log('%s.%s delivery=%s failed: %O', event, described.action ?? '-', deliveryId, error);
+ await ScmWebhookDeliveryModel.settle(db, key, { error: message, status: 'failed' });
+ return c.json({ error: message, ok: false }, 500);
+ }
+};
diff --git a/apps/server/src/router-hono/webhooks/handlers/githubInstall.ts b/apps/server/src/router-hono/webhooks/handlers/githubInstall.ts
new file mode 100644
index 00000000000..01c9ef5c60e
--- /dev/null
+++ b/apps/server/src/router-hono/webhooks/handlers/githubInstall.ts
@@ -0,0 +1,67 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { auth } from '@/auth';
+import { getServerDB } from '@/database/core/db-adaptor';
+import { scmEnv } from '@/envs/scm';
+import { buildGitHubInstallUrl } from '@/server/services/scm/github/app';
+import { issueScmInstallState } from '@/server/services/scm/oauth/stateStore';
+import { canWriteScmScope, sanitizeReturnTo } from '@/server/services/scm/scope';
+
+const log = debug('lobe-server:scm:github-install');
+
+export const GITHUB_INSTALL_PATH = '/api/webhooks/github/install';
+
+/**
+ * Entry point for "Connect GitHub". Always reached from a signed-in LobeHub
+ * page, so the session tells us which user (and optionally which workspace)
+ * the installation should bind to; that binding is carried through GitHub in
+ * the single-use `state` and consumed by the callback.
+ */
+export const githubInstall = async (c: Context): Promise<Response> => {
+ if (!scmEnv.ENABLED_GITHUB_APP) {
+ return new Response('GitHub App is not configured on this LobeHub deployment.', {
+ status: 503,
+ });
+ }
+
+ const req = c.req.raw;
+ const url = new URL(req.url);
+ const workspaceId = url.searchParams.get('workspaceId');
+ const returnTo = sanitizeReturnTo(url.searchParams.get('returnTo'));
+
+ let session: Awaited<ReturnType<typeof auth.api.getSession>>;
+ try {
+ session = await auth.api.getSession({ headers: req.headers });
+ } catch (error) {
+ log('getSession failed: %O', error);
+ session = null;
+ }
+ if (!session?.user?.id) {
+ const callbackUrl = encodeURIComponent(`${GITHUB_INSTALL_PATH}${url.search}`);
+ return Response.redirect(new URL(`/signin?callbackUrl=${callbackUrl}`, url.origin), 302);
+ }
+ const userId = session.user.id;
+
+ // Viewers read a workspace; binding an installation writes into it.
+ if (workspaceId && !(await canWriteScmScope(await getServerDB(), userId, workspaceId))) {
+ return c.json({ error: 'installing into this workspace needs the member role' }, 403);
+ }
+
+ // The install hand-off parks the caller's identity in Redis; a deployment
+ // that configured the App but no Redis would otherwise 500 here.
+ let state: string;
+ try {
+ state = await issueScmInstallState({ lobeUserId: userId, returnTo, workspaceId });
+ } catch (error) {
+ log('cannot issue install state: %O', error);
+ return new Response('Connecting GitHub needs Redis (REDIS_URL) on this LobeHub deployment.', {
+ status: 503,
+ });
+ }
+ const installUrl = buildGitHubInstallUrl(state);
+ if (!installUrl) return new Response('GitHub App slug is not configured.', { status: 503 });
+
+ log('redirecting user=%s workspace=%s to install', userId, workspaceId ?? '-');
+ return Response.redirect(installUrl, 302);
+};
diff --git a/apps/server/src/router-hono/webhooks/handlers/githubSetup.ts b/apps/server/src/router-hono/webhooks/handlers/githubSetup.ts
new file mode 100644
index 00000000000..f4bc9e9f1cb
--- /dev/null
+++ b/apps/server/src/router-hono/webhooks/handlers/githubSetup.ts
@@ -0,0 +1,247 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { auth } from '@/auth';
+import { getServerDB } from '@/database/core/db-adaptor';
+import { ScmIdentityModel, ScmInstallationModel } from '@/database/models/scm';
+import { scmEnv } from '@/envs/scm';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import {
+ exchangeGitHubUserCode,
+ fetchGitHubInstallation,
+ userCanAccessInstallation,
+} from '@/server/services/scm/github/app';
+import {
+ consumeScmInstallState,
+ issueScmInstallClaim,
+} from '@/server/services/scm/oauth/stateStore';
+import { canWriteScmScope, sanitizeReturnTo } from '@/server/services/scm/scope';
+
+const log = debug('lobe-server:scm:github-setup');
+
+/**
+ * Where the user lands after connecting; the page reads `installed=…`,
+ * `error=…` or `pending=…` from the query.
+ *
+ * That page ships with the settings half of this stack. Until it lands the
+ * path renders the bare settings shell β€” which no user reaches, because the
+ * install entry is only linked from that same page and the App stays
+ * disabled without its environment variables.
+ */
+const SETTINGS_PATH = '/settings/integrations/github';
+
+const redirectToSettings = (origin: string, params: Record<string, string>, returnTo?: string) => {
+ const target = new URL(sanitizeReturnTo(returnTo) ?? SETTINGS_PATH, origin);
+ for (const [key, value] of Object.entries(params)) target.searchParams.set(key, value);
+ return Response.redirect(target, 302);
+};
+
+/**
+ * GitHub sends the user here after installing (Callback URL, with `code`)
+ * and after changing an installation's repositories (Setup URL, without
+ * `code`). One handler covers both:
+ *
+ * - **With our `state`** (the flow started from "Connect" in LobeHub): the
+ * state names the user and scope; the code, when present, is exchanged
+ * for the user's identity and the installation is bound.
+ * - **Without `state`** (the flow started on github.com, or the state
+ * expired): nothing is bound automatically. A known installation owned by
+ * the session user is refreshed; anything else is handed to the settings
+ * page as a single-use claim, which the user redeems from a signed-in
+ * request to finish the connection. The `code` is never exchanged here: a
+ * stateless callback could be an attacker's authorization URL forwarded to
+ * a signed-in victim, and linking that identity would hand the victim's
+ * account to the attacker.
+ */
+export const githubSetup = async (c: Context): Promise<Response> => {
+ const url = new URL(c.req.url);
+ const installationId = url.searchParams.get('installation_id');
+ const code = url.searchParams.get('code');
+ const state = url.searchParams.get('state');
+ const setupAction = url.searchParams.get('setup_action');
+
+ if (!scmEnv.ENABLED_GITHUB_APP) {
+ return new Response('GitHub App is not configured on this LobeHub deployment.', {
+ status: 503,
+ });
+ }
+ if (!installationId) {
+ return redirectToSettings(url.origin, { error: 'missing_installation' });
+ }
+
+ const db = await getServerDB();
+ const statePayload = state ? await consumeScmInstallState(state) : null;
+
+ // ---- Stateless leg: refresh what the user already owns, confirm the rest.
+ if (!statePayload) {
+ let userId: string | undefined;
+ try {
+ const session = await auth.api.getSession({ headers: c.req.raw.headers });
+ userId = session?.user?.id;
+ } catch (error) {
+ log('getSession failed: %O', error);
+ }
+ if (!userId) {
+ // Bounce through sign-in and come back with the same query.
+ const callbackUrl = encodeURIComponent(`${url.pathname}${url.search}`);
+ return Response.redirect(new URL(`/signin?callbackUrl=${callbackUrl}`, url.origin), 302);
+ }
+
+ let snapshot: Awaited<ReturnType<typeof fetchGitHubInstallation>>;
+ try {
+ snapshot = await fetchGitHubInstallation(installationId);
+ } catch (error) {
+ log('fetch installation %s failed: %O', installationId, error);
+ return redirectToSettings(url.origin, { error: 'installation_fetch_failed' });
+ }
+
+ const existing = await ScmInstallationModel.findByProviderInstallationId(
+ db,
+ 'github',
+ installationId,
+ );
+ if (
+ existing &&
+ (existing.workspaceId
+ ? await canWriteScmScope(db, userId, existing.workspaceId)
+ : existing.userId === userId)
+ ) {
+ await ScmInstallationModel.refreshSnapshot(db, existing.id, snapshot);
+ return redirectToSettings(url.origin, { installed: 'updated' });
+ }
+
+ // The confirmation carries a claim, not the raw id: redeeming it is the
+ // proof that this user came back from GitHub holding this installation.
+ const claim = await issueScmInstallClaim({
+ installationId,
+ lobeUserId: userId,
+ provider: 'github',
+ });
+ if (!claim) return redirectToSettings(url.origin, { error: 'claim_unavailable' });
+
+ log(
+ 'installation %s (%s) arrived without state for user=%s; asking for confirmation',
+ installationId,
+ snapshot.accountLogin,
+ userId,
+ );
+ return redirectToSettings(url.origin, { account: snapshot.accountLogin, pending: claim });
+ }
+
+ // ---- Stateful leg: the user and scope come from the state we issued.
+ const userId = statePayload.lobeUserId;
+ const workspaceId = statePayload.workspaceId ?? null;
+ const returnTo = statePayload.returnTo;
+
+ // Membership can change between the click and the callback; recheck.
+ if (!(await canWriteScmScope(db, userId, workspaceId))) {
+ return redirectToSettings(url.origin, { error: 'workspace_forbidden' }, returnTo);
+ }
+
+ let installedBy: { login: string; userId: string } | undefined;
+ // Identity linking is its own capability: without OAuth credentials the
+ // exchange can only fail, so bind the installation and skip it.
+ if (code && !scmEnv.ENABLED_GITHUB_APP_OAUTH) {
+ log('skipping identity link for installation %s: OAuth is not configured', installationId);
+ } else if (code) {
+ let authorization: Awaited<ReturnType<typeof exchangeGitHubUserCode>>;
+ try {
+ authorization = await exchangeGitHubUserCode(code);
+ } catch (error) {
+ log('code exchange failed: %O', error);
+ return redirectToSettings(url.origin, { error: 'exchange_failed' }, returnTo);
+ }
+
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ try {
+ await ScmIdentityModel.upsert(
+ db,
+ {
+ credentials: {
+ accessToken: authorization.accessToken,
+ refreshToken: authorization.refreshToken,
+ refreshTokenExpiresAt: authorization.refreshTokenExpiresAt,
+ },
+ externalLogin: authorization.user.login,
+ externalUserId: authorization.user.externalId,
+ metadata: {
+ avatarUrl: authorization.user.avatarUrl,
+ email: authorization.user.email ?? undefined,
+ },
+ provider: 'github',
+ tokenExpiresAt: authorization.expiresAt ? new Date(authorization.expiresAt) : null,
+ userId,
+ },
+ gateKeeper,
+ );
+ } catch (error) {
+ // The unique index on (provider, external_user_id) fires when this GitHub
+ // account is already someone else's identity.
+ log('identity upsert failed for %s: %O', authorization.user.login, error);
+ return redirectToSettings(url.origin, { error: 'identity_taken' }, returnTo);
+ }
+ // App-level access proves the installation belongs to this App, not that
+ // the person finishing the flow has anything to do with it. Without this
+ // check a valid state of one's own plus a guessed installation id would
+ // move someone else's installation into the attacker's scope.
+ if (!(await userCanAccessInstallation(authorization.accessToken, installationId))) {
+ log(
+ 'user %s cannot access installation %s; refusing to bind',
+ authorization.user.login,
+ installationId,
+ );
+ return redirectToSettings(url.origin, { error: 'installation_not_yours' }, returnTo);
+ }
+
+ installedBy = { login: authorization.user.login, userId: authorization.user.externalId };
+ }
+
+ let snapshot: Awaited<ReturnType<typeof fetchGitHubInstallation>>;
+ try {
+ snapshot = await fetchGitHubInstallation(installationId);
+ } catch (error) {
+ log('fetch installation %s failed: %O', installationId, error);
+ return redirectToSettings(url.origin, { error: 'installation_fetch_failed' }, returnTo);
+ }
+
+ // Binding moves the row's scope, so an installation that already belongs
+ // to someone else is never taken over from here β€” whoever holds it has to
+ // disconnect it first. (With a code we have already proved access, but the
+ // owner still decides.)
+ const bound = await ScmInstallationModel.findByProviderInstallationId(
+ db,
+ 'github',
+ installationId,
+ );
+ const ownedByCaller =
+ !bound ||
+ !!bound.revokedAt ||
+ (bound.userId === userId && (bound.workspaceId ?? null) === workspaceId);
+ if (!ownedByCaller) {
+ log('installation %s is connected elsewhere; refusing to rebind', installationId);
+ return redirectToSettings(url.origin, { error: 'installation_taken' }, returnTo);
+ }
+
+ const installation = await ScmInstallationModel.bind(db, {
+ ...snapshot,
+ installedByExternalLogin: installedBy?.login,
+ installedByExternalUserId: installedBy?.userId,
+ userId,
+ workspaceId,
+ });
+
+ log(
+ 'bound installation %s (%s) to user=%s workspace=%s action=%s identity=%s',
+ installation.id,
+ snapshot.accountLogin,
+ userId,
+ workspaceId ?? '-',
+ setupAction ?? '-',
+ installedBy ? 'linked' : 'none',
+ );
+ return redirectToSettings(
+ url.origin,
+ { account: snapshot.accountLogin, installed: 'ok' },
+ returnTo,
+ );
+};
diff --git a/apps/server/src/router-hono/webhooks/index.ts b/apps/server/src/router-hono/webhooks/index.ts
index 791c061e643..74b2d0202e0 100644
--- a/apps/server/src/router-hono/webhooks/index.ts
+++ b/apps/server/src/router-hono/webhooks/index.ts
@@ -1,6 +1,9 @@
import { Hono } from 'hono';
import { casdoorWebhook } from './handlers/casdoor';
+import { githubWebhook } from './handlers/github';
+import { githubInstall } from './handlers/githubInstall';
+import { githubSetup } from './handlers/githubSetup';
import { logtoWebhook } from './handlers/logto';
import { memoryExtractionWebhook } from './handlers/memoryExtraction';
import { memoryExtractionBenchmarkLocomo } from './handlers/memoryExtractionBenchmarkLocomo';
@@ -36,4 +39,12 @@ app.post(
// Async video generation callback; the token is verified per asyncTask.
app.post('/video/:provider', videoWebhook);
+// GitHub App: signed event ingress plus the install / setup redirects GitHub
+// sends the user through. The GET routes share the prefix because the App's
+// Callback URL and Setup URL are registered on GitHub next to the webhook URL.
+app.post('/github', githubWebhook);
+app.get('/github/install', githubInstall);
+app.get('/github/setup', githubSetup);
+app.get('/github/oauth/callback', githubSetup);
+
export default app;
diff --git a/apps/server/src/routers/lambda/__tests__/scm.test.ts b/apps/server/src/routers/lambda/__tests__/scm.test.ts
new file mode 100644
index 00000000000..86bce8c188e
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/scm.test.ts
@@ -0,0 +1,272 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ ScmChangeRequestModel,
+ ScmIdentityModel,
+ ScmInstallationModel,
+} from '@/database/models/scm';
+import { scmWebhookDeliveries, users, workspaceMembers, workspaces } from '@/database/schemas';
+
+import { scmRouter } from '../scm';
+
+const serverDB = await getTestDB();
+const userId = 'scm-router-user';
+const otherUserId = 'scm-router-user-2';
+
+vi.mock('@/envs/scm', () => ({
+ scmEnv: { ENABLED_GITHUB_APP: true, GITHUB_APP_SLUG: 'lobehub-dev' },
+}));
+
+const mocks = vi.hoisted(() => ({ consumeClaim: vi.fn(), fetchInstallation: vi.fn() }));
+vi.mock('@/server/services/scm/oauth/stateStore', () => ({
+ consumeScmInstallClaim: mocks.consumeClaim,
+}));
+vi.mock('@/server/services/scm/github/app', () => ({
+ fetchGitHubInstallation: mocks.fetchInstallation,
+}));
+
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ return { wsCompatProcedure: mod.trpc.procedure };
+});
+
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: async (opts: any) => opts.next({ ctx: { ...opts.ctx, serverDB } }),
+}));
+
+const caller = (ctx: { userId: string; workspaceId?: string | null }) =>
+ scmRouter.createCaller({ ...ctx, serverDB } as any);
+
+const bind = (installationId: string, scope: { userId: string; workspaceId?: string | null }) =>
+ ScmInstallationModel.bind(serverDB, {
+ accountExternalId: installationId,
+ accountLogin: `acct-${installationId}`,
+ accountType: 'user',
+ installationId,
+ provider: 'github',
+ repositorySelection: 'all',
+ ...scope,
+ });
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(scmWebhookDeliveries);
+ await serverDB.delete(workspaces);
+ await serverDB.delete(users);
+});
+
+describe('scmRouter', () => {
+ it('reports the connect configuration', async () => {
+ expect(await caller({ userId }).getConfig()).toEqual({
+ github: {
+ appSlug: 'lobehub-dev',
+ enabled: true,
+ installPath: '/api/webhooks/github/install',
+ },
+ });
+ });
+
+ it('returns the identity without credentials, or null', async () => {
+ expect(await caller({ userId }).getIdentity({ provider: 'github' })).toBeNull();
+
+ await ScmIdentityModel.upsert(serverDB, {
+ credentials: { accessToken: 'secret' },
+ externalLogin: 'arvinxx',
+ externalUserId: '42',
+ metadata: { avatarUrl: 'https://a/b.png' },
+ provider: 'github',
+ userId,
+ });
+ const identity = await caller({ userId }).getIdentity({ provider: 'github' });
+ expect(identity).toEqual({
+ avatarUrl: 'https://a/b.png',
+ externalLogin: 'arvinxx',
+ externalUserId: '42',
+ provider: 'github',
+ });
+ expect(JSON.stringify(identity)).not.toContain('secret');
+ });
+
+ it('lists only the installations and change requests in the caller scope', async () => {
+ const [workspace] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'ws', primaryOwnerId: userId, slug: 'scm-ws' })
+ .returning();
+
+ const personal = await bind('1', { userId });
+ const theirs = await bind('2', { userId: otherUserId });
+ const shared = await bind('3', { userId, workspaceId: workspace.id });
+
+ const base = { provider: 'github' as const, state: 'open' as const };
+ await ScmChangeRequestModel.upsert(serverDB, {
+ ...base,
+ links: { installationId: personal.id },
+ number: 1,
+ repoFullName: 'a/personal',
+ url: 'https://github.com/a/personal/pull/1',
+ userId,
+ });
+ await ScmChangeRequestModel.upsert(serverDB, {
+ ...base,
+ links: { installationId: theirs.id },
+ number: 2,
+ repoFullName: 'b/theirs',
+ url: 'https://github.com/b/theirs/pull/2',
+ userId: otherUserId,
+ });
+ await ScmChangeRequestModel.upsert(serverDB, {
+ ...base,
+ links: { installationId: shared.id },
+ number: 3,
+ repoFullName: 'c/shared',
+ url: 'https://github.com/c/shared/pull/3',
+ userId,
+ workspaceId: workspace.id,
+ });
+
+ const mine = caller({ userId });
+ expect((await mine.listInstallations()).map((i) => i.id)).toEqual([personal.id]);
+ expect((await mine.listChangeRequests()).map((r) => r.repoFullName)).toEqual(['a/personal']);
+
+ const ws = caller({ userId, workspaceId: workspace.id });
+ expect((await ws.listInstallations()).map((i) => i.id)).toEqual([shared.id]);
+ expect((await ws.listChangeRequests({ limit: 10 })).map((r) => r.repoFullName)).toEqual([
+ 'c/shared',
+ ]);
+ });
+
+ it('refuses a claim that is expired or was minted for someone else', async () => {
+ mocks.fetchInstallation.mockResolvedValue({
+ accountExternalId: '9',
+ accountLogin: 'arvinxx',
+ accountType: 'user',
+ installationId: '900',
+ provider: 'github',
+ repositorySelection: 'all',
+ });
+
+ // Expired or replayed: the store hands back nothing.
+ mocks.consumeClaim.mockResolvedValueOnce(null);
+ await expect(caller({ userId }).connectInstallation({ claim: 'gone' })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+
+ // Minted for another user: knowing the token is not enough.
+ mocks.consumeClaim.mockResolvedValueOnce({
+ installationId: '900',
+ lobeUserId: otherUserId,
+ provider: 'github',
+ ts: 1,
+ });
+ await expect(caller({ userId }).connectInstallation({ claim: 'theirs' })).rejects.toMatchObject(
+ { code: 'FORBIDDEN' },
+ );
+
+ // Neither attempt reached GitHub or the database.
+ expect(mocks.fetchInstallation).not.toHaveBeenCalled();
+ expect(
+ await ScmInstallationModel.findByProviderInstallationId(serverDB, 'github', '900'),
+ ).toBeNull();
+ });
+
+ it('connects a pending installation into the caller scope, but never one bound elsewhere', async () => {
+ mocks.consumeClaim.mockResolvedValue({
+ installationId: '900',
+ lobeUserId: userId,
+ provider: 'github',
+ ts: 1,
+ });
+ mocks.fetchInstallation.mockResolvedValue({
+ accountExternalId: '9',
+ accountLogin: 'arvinxx',
+ accountType: 'user',
+ installationId: '900',
+ provider: 'github',
+ repositorySelection: 'all',
+ });
+
+ const mine = caller({ userId });
+ const bound = await mine.connectInstallation({ claim: 'c1' });
+ expect(bound).toMatchObject({ accountLogin: 'arvinxx', userId, workspaceId: null });
+ expect(mocks.fetchInstallation).toHaveBeenCalledWith('900');
+
+ // Re-confirming in the same scope is a refresh, not an error.
+ await expect(mine.connectInstallation({ claim: 'c2' })).resolves.toMatchObject({
+ id: bound.id,
+ });
+
+ // Another user holding a claim of their own cannot pull it into their account.
+ mocks.consumeClaim.mockResolvedValueOnce({
+ installationId: '900',
+ lobeUserId: otherUserId,
+ provider: 'github',
+ ts: 1,
+ });
+ await expect(
+ caller({ userId: otherUserId }).connectInstallation({ claim: 'c3' }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+
+ // An installation GitHub does not know binds nothing.
+ mocks.consumeClaim.mockResolvedValueOnce({
+ installationId: '404',
+ lobeUserId: userId,
+ provider: 'github',
+ ts: 1,
+ });
+ mocks.fetchInstallation.mockRejectedValueOnce(new Error('404'));
+ await expect(mine.connectInstallation({ claim: 'c4' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ expect(
+ await ScmInstallationModel.findByProviderInstallationId(serverDB, 'github', '404'),
+ ).toBeNull();
+ });
+
+ it('requires the member role to connect into a workspace', async () => {
+ const [workspace] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'ws', primaryOwnerId: userId, slug: 'scm-ws-connect' })
+ .returning();
+ await serverDB
+ .insert(workspaceMembers)
+ .values({ role: 'viewer', userId: otherUserId, workspaceId: workspace.id });
+ mocks.fetchInstallation.mockResolvedValue({
+ accountExternalId: '10',
+ accountLogin: 'org',
+ accountType: 'organization',
+ installationId: '901',
+ provider: 'github',
+ repositorySelection: 'all',
+ });
+
+ mocks.consumeClaim.mockResolvedValue({
+ installationId: '901',
+ lobeUserId: otherUserId,
+ provider: 'github',
+ ts: 1,
+ });
+ await expect(
+ caller({ userId: otherUserId, workspaceId: workspace.id }).connectInstallation({
+ claim: 'c5',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ await serverDB
+ .insert(workspaceMembers)
+ .values({ role: 'member', userId, workspaceId: workspace.id });
+ mocks.consumeClaim.mockResolvedValue({
+ installationId: '901',
+ lobeUserId: userId,
+ provider: 'github',
+ ts: 1,
+ });
+ await expect(
+ caller({ userId, workspaceId: workspace.id }).connectInstallation({ claim: 'c6' }),
+ ).resolves.toMatchObject({ userId, workspaceId: workspace.id });
+ });
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index a2c99c6cd77..6ca56a27c09 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -83,6 +83,7 @@ import { ragEvalRouter } from './ragEval';
import { recentRouter } from './recent';
import { resourcePermissionRouter } from './resourcePermission';
import { resourceTransferRequestRouter } from './resourceTransferRequest';
+import { scmRouter } from './scm';
import { searchRouter } from './search';
import { sessionRouter } from './session';
import { sessionGroupRouter } from './sessionGroup';
@@ -170,6 +171,7 @@ export const lambdaRouter = router({
resourcePermission: resourcePermissionRouter,
resourceTransferRequest: resourceTransferRequestRouter,
search: searchRouter,
+ scm: scmRouter,
session: sessionRouter,
sessionGroup: sessionGroupRouter,
share: shareRouter,
diff --git a/apps/server/src/routers/lambda/scm.ts b/apps/server/src/routers/lambda/scm.ts
new file mode 100644
index 00000000000..36cf30da6d0
--- /dev/null
+++ b/apps/server/src/routers/lambda/scm.ts
@@ -0,0 +1,129 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import {
+ ScmChangeRequestModel,
+ ScmIdentityModel,
+ ScmInstallationModel,
+} from '@/database/models/scm';
+import { scmEnv } from '@/envs/scm';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { fetchGitHubInstallation } from '@/server/services/scm/github/app';
+import { consumeScmInstallClaim } from '@/server/services/scm/oauth/stateStore';
+import { canWriteScmScope } from '@/server/services/scm/scope';
+
+/** Path the "Connect GitHub" button navigates to; the server route owns the redirect. */
+export const GITHUB_INSTALL_PATH = '/api/webhooks/github/install';
+
+const scmProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ return opts.next({
+ ctx: { scope: { userId: ctx.userId, workspaceId: ctx.workspaceId ?? null } },
+ });
+});
+
+/**
+ * The SCM integration for the settings page and acceptance views. Reads,
+ * plus the one write a signed-in user confirms in the app: connecting an
+ * installation that reached the callback without our state (started on
+ * github.com). Everything else is written by provider webhooks and the
+ * install callback.
+ */
+export const scmRouter = router({
+ /**
+ * Finish an installation that reached the callback without our state, by
+ * redeeming the single-use claim that callback issued. The claim is what
+ * authorizes the bind: an installation id proves nothing on its own β€” it
+ * is a small integer, and naming someone else's would hand their
+ * repositories to the caller β€” so a claim minted for another user, or a
+ * replayed one, is refused. A workspace additionally needs the member
+ * role. No identity is linked here; "Connect account" does that.
+ */
+ connectInstallation: scmProcedure
+ .input(z.object({ claim: z.string().min(1) }))
+ .mutation(async ({ ctx, input }) => {
+ if (!scmEnv.ENABLED_GITHUB_APP) {
+ throw new TRPCError({
+ code: 'PRECONDITION_FAILED',
+ message: 'GitHub App is not configured',
+ });
+ }
+
+ const claim = await consumeScmInstallClaim(input.claim);
+ if (!claim || claim.lobeUserId !== ctx.userId) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'this installation claim is expired or was issued for another user',
+ });
+ }
+ if (!(await canWriteScmScope(ctx.serverDB, ctx.userId, ctx.scope.workspaceId))) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'workspace member role required' });
+ }
+
+ let snapshot: Awaited<ReturnType<typeof fetchGitHubInstallation>>;
+ try {
+ snapshot = await fetchGitHubInstallation(claim.installationId);
+ } catch {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'installation not found on GitHub' });
+ }
+
+ const existing = await ScmInstallationModel.findByProviderInstallationId(
+ ctx.serverDB,
+ claim.provider,
+ claim.installationId,
+ );
+ // An installation already bound elsewhere stays there: re-binding it
+ // would pull another tenant's repositories into this one.
+ if (existing && !existing.revokedAt) {
+ const sameScope =
+ existing.userId === ctx.userId &&
+ (existing.workspaceId ?? null) === ctx.scope.workspaceId;
+ if (!sameScope) {
+ throw new TRPCError({ code: 'CONFLICT', message: 'installation is connected elsewhere' });
+ }
+ }
+
+ return ScmInstallationModel.bind(ctx.serverDB, {
+ ...snapshot,
+ userId: ctx.userId,
+ workspaceId: ctx.scope.workspaceId,
+ });
+ }),
+
+ /** What the client needs to render the connect button. */
+ getConfig: scmProcedure.query(async () => ({
+ github: {
+ appSlug: scmEnv.GITHUB_APP_SLUG ?? null,
+ enabled: scmEnv.ENABLED_GITHUB_APP,
+ installPath: GITHUB_INSTALL_PATH,
+ },
+ })),
+
+ /** The caller's own provider identity, without credentials. */
+ getIdentity: scmProcedure
+ .input(z.object({ provider: z.enum(['github']) }))
+ .query(async ({ ctx, input }) => {
+ const identity = await ScmIdentityModel.findByUser(ctx.serverDB, input.provider, ctx.userId);
+ if (!identity) return null;
+ return {
+ avatarUrl: identity.metadata.avatarUrl ?? null,
+ externalLogin: identity.externalLogin,
+ externalUserId: identity.externalUserId,
+ provider: identity.provider,
+ };
+ }),
+
+ listChangeRequests: scmProcedure
+ .input(z.object({ limit: z.number().int().min(1).max(200).optional() }).optional())
+ .query(async ({ ctx, input }) =>
+ ScmChangeRequestModel.listByScope(ctx.serverDB, ctx.scope, { limit: input?.limit }),
+ ),
+
+ listInstallations: scmProcedure.query(async ({ ctx }) =>
+ ScmInstallationModel.listByScope(ctx.serverDB, ctx.scope),
+ ),
+});
+
+export type ScmRouter = typeof scmRouter;
diff --git a/apps/server/src/services/scm/ScmIngestService.ts b/apps/server/src/services/scm/ScmIngestService.ts
new file mode 100644
index 00000000000..f1d69d88974
--- /dev/null
+++ b/apps/server/src/services/scm/ScmIngestService.ts
@@ -0,0 +1,305 @@
+import debug from 'debug';
+
+import { isFailingCheck, ScmChangeRequestModel, ScmInstallationModel } from '@/database/models/scm';
+import type { ScmChangeRequestItem, ScmInstallationItem } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { resolveChangeRequestLinks } from './links';
+import type { ScmInboundEvent, ScmIngestOutcome } from './types';
+
+const log = debug('lobe-server:scm:ingest');
+
+/**
+ * Apply one normalized provider event to the database. This is the whole
+ * "state" half of the closed loop: installations, change requests, CI
+ * rollups and review decisions end up in `scm_*` tables. The "control"
+ * half (accept the acceptance on merge, wake the agent on CI failure) hangs
+ * off {@link ScmIngestService.onChangeRequestEvent} and ships separately.
+ *
+ * Every branch is idempotent: replaying a delivery converges to the same
+ * rows, which is what lets the delivery ledger reject duplicates cheaply
+ * instead of guarding each write.
+ */
+export class ScmIngestService {
+ constructor(private db: LobeChatDatabase) {}
+
+ /**
+ * Hook for the control half: called after a change-request-level event
+ * has been persisted, with the row it landed on. Default is a no-op.
+ */
+ onChangeRequestEvent: (params: {
+ event: Extract<ScmInboundEvent, { type: 'change_request' | 'checks' | 'review' }>;
+ kind: string;
+ row: ScmChangeRequestItem;
+ }) => Promise<void> = async () => {};
+
+ apply = async (event: ScmInboundEvent): Promise<ScmIngestOutcome> => {
+ switch (event.type) {
+ case 'ignored': {
+ return { detail: event.reason, status: 'skipped' };
+ }
+ case 'installation': {
+ return this.applyInstallation(event);
+ }
+ case 'installation_repositories': {
+ return this.applyInstallationRepositories(event);
+ }
+ case 'change_request': {
+ return this.applyChangeRequest(event);
+ }
+ case 'checks': {
+ return this.applyChecks(event);
+ }
+ case 'review': {
+ return this.applyReview(event);
+ }
+ }
+ };
+
+ // --------------- Installations ---------------
+
+ /**
+ * Webhook-side installation lifecycle. A `created` event for an
+ * installation LobeHub has never bound is *not* inserted: the row needs a
+ * LobeHub user, which only the install callback knows. Until that
+ * callback runs, events for the installation are skipped as unbound.
+ */
+ private applyInstallation = async (
+ event: Extract<ScmInboundEvent, { type: 'installation' }>,
+ ): Promise<ScmIngestOutcome> => {
+ const { installation, action } = event;
+ const existing = await ScmInstallationModel.findByProviderInstallationId(
+ this.db,
+ installation.provider,
+ installation.installationId,
+ );
+
+ if (!existing) {
+ return {
+ detail: `installation ${installation.installationId} is not bound to a LobeHub scope`,
+ status: 'skipped',
+ };
+ }
+
+ switch (action) {
+ case 'deleted': {
+ await ScmInstallationModel.markRevoked(this.db, existing.id);
+ break;
+ }
+ case 'suspend': {
+ await ScmInstallationModel.setSuspended(this.db, existing.id, true);
+ break;
+ }
+ case 'unsuspend': {
+ await ScmInstallationModel.setSuspended(this.db, existing.id, false);
+ break;
+ }
+ case 'created':
+ case 'new_permissions_accepted': {
+ await ScmInstallationModel.refreshSnapshot(this.db, existing.id, {
+ accountExternalId: installation.accountExternalId,
+ accountLogin: installation.accountLogin,
+ accountType: installation.accountType,
+ metadata: { ...existing.metadata, ...installation.metadata },
+ repositories: installation.repositories?.length
+ ? installation.repositories
+ : existing.repositories,
+ repositorySelection: installation.repositorySelection,
+ suspendedAt: installation.suspendedAt ?? null,
+ });
+ break;
+ }
+ }
+
+ return { detail: `installation ${existing.id} ${action}`, status: 'processed' };
+ };
+
+ private applyInstallationRepositories = async (
+ event: Extract<ScmInboundEvent, { type: 'installation_repositories' }>,
+ ): Promise<ScmIngestOutcome> => {
+ const existing = await ScmInstallationModel.findByProviderInstallationId(
+ this.db,
+ 'github',
+ event.installationId,
+ );
+ if (!existing) {
+ return { detail: `installation ${event.installationId} is not bound`, status: 'skipped' };
+ }
+
+ await ScmInstallationModel.applyRepositoryChange(this.db, existing.id, {
+ added: event.added,
+ removed: event.removed,
+ });
+ return {
+ detail: `installation ${existing.id}: +${event.added.length} -${event.removed.length}`,
+ status: 'processed',
+ };
+ };
+
+ // --------------- Change requests ---------------
+
+ private resolveBoundInstallation = async (
+ installationId: string,
+ ): Promise<ScmInstallationItem | null> => {
+ const installation = await ScmInstallationModel.findByProviderInstallationId(
+ this.db,
+ 'github',
+ installationId,
+ );
+ if (!installation || installation.revokedAt) return null;
+ return installation;
+ };
+
+ private applyChangeRequest = async (
+ event: Extract<ScmInboundEvent, { type: 'change_request' }>,
+ ): Promise<ScmIngestOutcome> => {
+ const installation = await this.resolveBoundInstallation(event.installationId);
+ if (!installation) {
+ return { detail: `installation ${event.installationId} is not bound`, status: 'skipped' };
+ }
+
+ const scope = { userId: installation.userId, workspaceId: installation.workspaceId };
+ const links = await resolveChangeRequestLinks(this.db, {
+ body: event.body,
+ number: event.changeRequest.number,
+ repoFullName: event.changeRequest.repoFullName,
+ scope,
+ url: event.changeRequest.url,
+ });
+
+ const row = await ScmChangeRequestModel.upsert(this.db, {
+ ...event.changeRequest,
+ eventAt: event.occurredAt,
+ eventKind: event.kind,
+ links: { ...links, installationId: installation.id },
+ userId: scope.userId,
+ workspaceId: scope.workspaceId,
+ });
+
+ log(
+ '%s %s#%d -> %s (acceptance=%s topic=%s)',
+ event.kind,
+ row.repoFullName,
+ row.number,
+ row.id,
+ row.acceptanceId ?? '-',
+ row.topicId ?? '-',
+ );
+
+ await this.onChangeRequestEvent({ event, kind: event.kind, row });
+ return { detail: `${row.id} ${event.kind}`, status: 'processed' };
+ };
+
+ private applyChecks = async (
+ event: Extract<ScmInboundEvent, { type: 'checks' }>,
+ ): Promise<ScmIngestOutcome> => {
+ const installation = await this.resolveBoundInstallation(event.installationId);
+ if (!installation) {
+ return { detail: `installation ${event.installationId} is not bound`, status: 'skipped' };
+ }
+
+ // Resolve target rows: by number when the provider attached them, else by head sha.
+ const rows: ScmChangeRequestItem[] = [];
+ for (const number of event.numbers) {
+ const row = await ScmChangeRequestModel.findByIdentity(
+ this.db,
+ 'github',
+ event.repoFullName,
+ number,
+ );
+ if (row) rows.push(row);
+ }
+ if (rows.length === 0) {
+ rows.push(
+ ...(await ScmChangeRequestModel.findByHeadSha(
+ this.db,
+ 'github',
+ event.repoFullName,
+ event.headSha,
+ )),
+ );
+ }
+ if (rows.length === 0) {
+ return {
+ detail: `no tracked change request for ${event.repoFullName}@${event.headSha.slice(0, 7)}`,
+ status: 'skipped',
+ };
+ }
+
+ const touched: string[] = [];
+ for (const row of rows) {
+ const result = await ScmChangeRequestModel.applyChecks(this.db, row.id, {
+ checks: event.checks,
+ headSha: event.headSha,
+ });
+ if (!result?.applied) continue;
+ touched.push(row.id);
+
+ // Emit per-check failure the moment it lands, and the green rollup once
+ // nothing is pending β€” those two are what the control half acts on.
+ const failedNow = event.checks.some(isFailingCheck);
+ const kind = failedNow
+ ? 'ci_failed'
+ : result.ciStatus === 'success' && result.previousCiStatus !== 'success'
+ ? 'ci_passed'
+ : null;
+ if (kind) {
+ await ScmChangeRequestModel.recordEvent(this.db, row.id, kind);
+ await this.onChangeRequestEvent({ event, kind, row: result.row });
+ }
+ }
+
+ return touched.length > 0
+ ? { detail: touched.join(','), status: 'processed' }
+ : { detail: `stale checks for ${event.headSha.slice(0, 7)}`, status: 'skipped' };
+ };
+
+ private applyReview = async (
+ event: Extract<ScmInboundEvent, { type: 'review' }>,
+ ): Promise<ScmIngestOutcome> => {
+ const installation = await this.resolveBoundInstallation(event.installationId);
+ if (!installation) {
+ return { detail: `installation ${event.installationId} is not bound`, status: 'skipped' };
+ }
+
+ const row = await ScmChangeRequestModel.findByIdentity(
+ this.db,
+ 'github',
+ event.repoFullName,
+ event.number,
+ );
+ if (!row) {
+ return {
+ detail: `no tracked change request for ${event.repoFullName}#${event.number}`,
+ status: 'skipped',
+ };
+ }
+
+ // A plain comment carries no verdict and leaves the rollup alone; a
+ // dismissal drops that reviewer's verdict from it.
+ const decision =
+ event.kind === 'review_approved'
+ ? ('approved' as const)
+ : event.kind === 'review_changes_requested'
+ ? ('changes_requested' as const)
+ : null;
+ if (decision || event.kind === 'review_dismissed') {
+ const { applied } = await ScmChangeRequestModel.applyReviewerDecision(this.db, row.id, {
+ at: event.occurredAt,
+ decision,
+ reviewerId: event.actor?.externalId,
+ });
+ // The reviewer has since said something newer. Recording this event
+ // would rewind `lastEventAt`, and handing it to the control half
+ // would wake the agent over a verdict that no longer stands.
+ if (!applied) {
+ return { detail: `${row.id} ${event.kind} superseded`, status: 'skipped' };
+ }
+ }
+ await ScmChangeRequestModel.recordEvent(this.db, row.id, event.kind, event.occurredAt);
+
+ const fresh = (await ScmChangeRequestModel.findById(this.db, row.id)) ?? row;
+ await this.onChangeRequestEvent({ event, kind: event.kind, row: fresh });
+ return { detail: `${row.id} ${event.kind}`, status: 'processed' };
+ };
+}
diff --git a/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts b/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts
new file mode 100644
index 00000000000..fc03c344498
--- /dev/null
+++ b/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts
@@ -0,0 +1,242 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ScmChangeRequestModel, ScmInstallationModel } from '@/database/models/scm';
+import { acceptances, scmWebhookDeliveries, users } from '@/database/schemas';
+
+import * as fx from '../github/__tests__/fixtures';
+import { normalizeGitHubEvent } from '../github/normalize';
+import { ScmIngestService } from '../ScmIngestService';
+
+const serverDB = await getTestDB();
+const userId = 'scm-ingest-user';
+const acceptanceId = '0f1e2d3c-4b5a-4c6d-8e9f-0a1b2c3d4e5f';
+
+const bindInstallation = () =>
+ ScmInstallationModel.bind(serverDB, {
+ accountExternalId: '1',
+ accountLogin: 'lobehub',
+ accountType: 'organization',
+ installationId: String(fx.installation.id),
+ provider: 'github',
+ repositorySelection: 'all',
+ userId,
+ });
+
+const ingest = (
+ event: string,
+ payload: Record<string, unknown>,
+ service = new ScmIngestService(serverDB),
+) => service.apply(normalizeGitHubEvent(event, payload));
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(scmWebhookDeliveries);
+ await serverDB.delete(users);
+});
+
+describe('ScmIngestService', () => {
+ it('skips events from an installation nobody has connected', async () => {
+ expect(await ingest('pull_request', fx.pullRequestEvent('opened'))).toMatchObject({
+ status: 'skipped',
+ });
+ expect(await ingest('installation', fx.installationEvent('created'))).toMatchObject({
+ status: 'skipped',
+ });
+ expect(
+ await ScmChangeRequestModel.findByIdentity(serverDB, 'github', 'lobehub/lobehub', 19_719),
+ ).toBeNull();
+ });
+
+ it('tracks a pull request through open, CI failure, review, and merge', async () => {
+ const installation = await bindInstallation();
+ await serverDB
+ .insert(acceptances)
+ .values({ id: acceptanceId, subjectId: 's', subjectType: 'standalone', userId });
+
+ const hook = vi.fn(async () => {});
+ const service = new ScmIngestService(serverDB);
+ service.onChangeRequestEvent = hook;
+
+ // opened β†’ row scoped to the installation, linked to the acceptance from the body
+ expect(await ingest('pull_request', fx.pullRequestEvent('opened'), service)).toMatchObject({
+ status: 'processed',
+ });
+ let row = await ScmChangeRequestModel.findByIdentity(
+ serverDB,
+ 'github',
+ 'lobehub/lobehub',
+ 19_719,
+ );
+ expect(row).toMatchObject({
+ acceptanceId,
+ installationId: installation.id,
+ lastEventKind: 'opened',
+ state: 'open',
+ userId,
+ });
+ expect(hook).toHaveBeenLastCalledWith(expect.objectContaining({ kind: 'opened' }));
+
+ // failing check_run β†’ rollup failure + ci_failed
+ expect(await ingest('check_run', fx.checkRunEvent(), service)).toMatchObject({
+ status: 'processed',
+ });
+ row = await ScmChangeRequestModel.findById(serverDB, row!.id);
+ expect(row).toMatchObject({ ciStatus: 'failure', lastEventKind: 'ci_failed' });
+ expect(row?.checks?.[0]).toMatchObject({ name: 'Test Packages' });
+ expect(hook).toHaveBeenLastCalledWith(expect.objectContaining({ kind: 'ci_failed' }));
+
+ // a second, green check_run does not flip the rollup while the failure stands
+ hook.mockClear();
+ await ingest(
+ 'check_run',
+ fx.checkRunEvent({ conclusion: 'success', id: 3, name: 'Lint' }),
+ service,
+ );
+ row = await ScmChangeRequestModel.findById(serverDB, row!.id);
+ expect(row?.ciStatus).toBe('failure');
+ expect(row?.checks).toHaveLength(2);
+ expect(hook).not.toHaveBeenCalled();
+
+ // review changes requested
+ await ingest('pull_request_review', fx.reviewEvent('changes_requested'), service);
+ row = await ScmChangeRequestModel.findById(serverDB, row!.id);
+ expect(row).toMatchObject({
+ lastEventKind: 'review_changes_requested',
+ reviewDecision: 'changes_requested',
+ });
+
+ // the same review dismissed: GitHub invalidated the verdict
+ await ingest(
+ 'pull_request_review',
+ { ...fx.reviewEvent('dismissed'), action: 'dismissed' },
+ service,
+ );
+ row = await ScmChangeRequestModel.findById(serverDB, row!.id);
+ expect(row).toMatchObject({ lastEventKind: 'review_dismissed', reviewDecision: null });
+
+ // merged
+ await ingest(
+ 'pull_request',
+ fx.pullRequestEvent('closed', {
+ merged: true,
+ merged_at: '2026-09-20T07:00:00Z',
+ merged_by: { id: 42, login: 'arvinxx' },
+ state: 'closed',
+ }),
+ service,
+ );
+ row = await ScmChangeRequestModel.findById(serverDB, row!.id);
+ expect(row).toMatchObject({
+ lastEventKind: 'merged',
+ mergedByExternalId: '42',
+ state: 'merged',
+ });
+ expect(hook).toHaveBeenLastCalledWith(expect.objectContaining({ kind: 'merged' }));
+ });
+
+ it('drops a review the same reviewer has already superseded', async () => {
+ const hook = vi.fn();
+ const service = new ScmIngestService(serverDB);
+ service.onChangeRequestEvent = hook;
+
+ await bindInstallation();
+ await ingest('pull_request', fx.pullRequestEvent('opened'), service);
+
+ // The approval lands first; the older changes-request arrives after.
+ await ingest(
+ 'pull_request_review',
+ {
+ ...fx.reviewEvent('approved'),
+ review: { ...fx.reviewEvent('approved').review, submitted_at: '2026-09-20T12:00:00Z' },
+ },
+ service,
+ );
+ hook.mockClear();
+
+ expect(
+ await ingest(
+ 'pull_request_review',
+ {
+ ...fx.reviewEvent('changes_requested'),
+ review: {
+ ...fx.reviewEvent('changes_requested').review,
+ submitted_at: '2026-09-20T09:00:00Z',
+ },
+ },
+ service,
+ ),
+ ).toMatchObject({ status: 'skipped' });
+
+ const row = await ScmChangeRequestModel.findByIdentity(
+ serverDB,
+ 'github',
+ 'lobehub/lobehub',
+ 19_719,
+ );
+ // Neither the verdict, nor the event marker, nor the control half moved.
+ expect(row).toMatchObject({ lastEventKind: 'review_approved', reviewDecision: 'approved' });
+ expect(hook).not.toHaveBeenCalled();
+ });
+
+ it('resets CI on a new push and ignores late results for the old commit', async () => {
+ await bindInstallation();
+ await ingest('pull_request', fx.pullRequestEvent('opened'));
+ await ingest('check_run', fx.checkRunEvent());
+
+ const sha2 = 'b'.repeat(40);
+ await ingest(
+ 'pull_request',
+ fx.pullRequestEvent('synchronize', { head: { ref: 'x', sha: sha2 } }),
+ );
+ let row = await ScmChangeRequestModel.findByIdentity(
+ serverDB,
+ 'github',
+ 'lobehub/lobehub',
+ 19_719,
+ );
+ expect(row).toMatchObject({ checks: null, ciStatus: null, headSha: sha2 });
+
+ // late result for the old sha, no PR numbers attached (fork-style)
+ expect(await ingest('check_run', fx.checkRunEvent({ pull_requests: [] }))).toMatchObject({
+ status: 'skipped',
+ });
+
+ // result for the new sha, resolved by sha
+ expect(
+ await ingest(
+ 'check_run',
+ fx.checkRunEvent({ conclusion: 'success', head_sha: sha2, pull_requests: [] }),
+ ),
+ ).toMatchObject({ status: 'processed' });
+ row = await ScmChangeRequestModel.findById(serverDB, row!.id);
+ expect(row).toMatchObject({ ciStatus: 'success', lastEventKind: 'ci_passed' });
+ });
+
+ it('maintains the installation from lifecycle events', async () => {
+ const installation = await bindInstallation();
+
+ await ingest('installation_repositories', fx.installationRepositoriesEvent());
+ let fresh = await ScmInstallationModel.findById(serverDB, installation.id);
+ expect(fresh?.repositories).toEqual([
+ { externalId: '601000002', fullName: 'lobehub/lobehub-cloud', private: true },
+ ]);
+
+ await ingest('installation', fx.installationEvent('suspend'));
+ fresh = await ScmInstallationModel.findById(serverDB, installation.id);
+ expect(fresh?.suspendedAt).not.toBeNull();
+
+ await ingest('installation', fx.installationEvent('deleted'));
+ fresh = await ScmInstallationModel.findById(serverDB, installation.id);
+ expect(fresh?.revokedAt).not.toBeNull();
+
+ // revoked β†’ events for it are skipped
+ expect(await ingest('pull_request', fx.pullRequestEvent('opened'))).toMatchObject({
+ status: 'skipped',
+ });
+ });
+});
diff --git a/apps/server/src/services/scm/__tests__/links.test.ts b/apps/server/src/services/scm/__tests__/links.test.ts
new file mode 100644
index 00000000000..cba282915df
--- /dev/null
+++ b/apps/server/src/services/scm/__tests__/links.test.ts
@@ -0,0 +1,168 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { acceptances, topics, users, verifyRuns, works, workspaces } from '@/database/schemas';
+
+import { parseAcceptanceIds, resolveChangeRequestLinks } from '../links';
+
+const serverDB = await getTestDB();
+const userId = 'scm-links-user';
+const otherUserId = 'scm-links-user-2';
+const acceptanceId = '0f1e2d3c-4b5a-4c6d-8e9f-0a1b2c3d4e5f';
+
+describe('parseAcceptanceIds', () => {
+ it('finds acceptance ids in any host and de-duplicates them', () => {
+ const text = [
+ `- Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`,
+ `see http://localhost:3010/acceptance/${acceptanceId.toUpperCase()}?r=2`,
+ 'and https://app.lobehub.com/acceptance/11111111-2222-4333-8444-555555555555',
+ 'not https://app.lobehub.com/acceptance/not-a-uuid',
+ ].join('\n');
+
+ expect(parseAcceptanceIds(text)).toEqual([
+ acceptanceId,
+ '11111111-2222-4333-8444-555555555555',
+ ]);
+ expect(parseAcceptanceIds(null)).toEqual([]);
+ });
+});
+
+describe('resolveChangeRequestLinks', () => {
+ beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(workspaces);
+ await serverDB.delete(users);
+ });
+
+ const base = {
+ number: 19_719,
+ repoFullName: 'lobehub/lobehub',
+ scope: { userId },
+ url: 'https://github.com/lobehub/lobehub/pull/19719',
+ };
+
+ it('links the acceptance named in the body and its topic subject', async () => {
+ const [topic] = await serverDB.insert(topics).values({ title: 't', userId }).returning();
+ await serverDB
+ .insert(acceptances)
+ .values({ id: acceptanceId, subjectId: topic.id, subjectType: 'topic', userId });
+
+ const links = await resolveChangeRequestLinks(serverDB, {
+ ...base,
+ body: `Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`,
+ });
+
+ expect(links).toEqual({ acceptanceId, topicId: topic.id });
+ });
+
+ it('skips body ids that do not exist and falls through to the Work', async () => {
+ const [topic] = await serverDB.insert(topics).values({ title: 't', userId }).returning();
+ const [work] = await serverDB
+ .insert(works)
+ .values({
+ originTopicId: topic.id,
+ resourceId: 'lobehub/lobehub#19719',
+ resourceType: 'github_pull_request',
+ toolIdentifier: 'lobe-local-system',
+ toolName: 'runCommand',
+ type: 'external',
+ userId,
+ visibility: 'private',
+ })
+ .returning();
+
+ const links = await resolveChangeRequestLinks(serverDB, {
+ ...base,
+ body: 'Acceptance: https://app.lobehub.com/acceptance/11111111-2222-4333-8444-555555555555',
+ });
+
+ expect(links).toEqual({ topicId: topic.id, workId: work.id });
+ });
+
+ it("never crosses tenants: another user's acceptance, Work and round are invisible", async () => {
+ const insertWork = (owner: string) =>
+ serverDB
+ .insert(works)
+ .values({
+ resourceId: 'lobehub/lobehub#19719',
+ resourceType: 'github_pull_request',
+ toolIdentifier: 'lobe-local-system',
+ toolName: 'runCommand',
+ type: 'external',
+ userId: owner,
+ visibility: 'private',
+ })
+ .returning();
+ const [theirs] = await insertWork(otherUserId);
+ await serverDB
+ .insert(acceptances)
+ .values({ id: acceptanceId, subjectId: 's', subjectType: 'standalone', userId: otherUserId });
+ await serverDB.insert(verifyRuns).values({
+ acceptanceId,
+ context: { pullRequest: { number: 19_719, url: base.url } },
+ roundIndex: 1,
+ scenario: 'coding',
+ userId: otherUserId,
+ });
+
+ // A body naming their acceptance, a Work they registered, a round they
+ // ingested: none of it links from my installation.
+ expect(
+ await resolveChangeRequestLinks(serverDB, {
+ ...base,
+ body: `Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`,
+ }),
+ ).toEqual({});
+
+ // Once I register my own Work it wins, and theirs still does not leak in.
+ const [mine] = await insertWork(userId);
+ expect(mine.id).not.toBe(theirs.id);
+ expect((await resolveChangeRequestLinks(serverDB, base)).workId).toBe(mine.id);
+ });
+
+ it('separates a workspace installation from personal records of the same user', async () => {
+ const [workspace] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'ws', primaryOwnerId: userId, slug: 'scm-links-ws' })
+ .returning();
+ await serverDB
+ .insert(acceptances)
+ .values({ id: acceptanceId, subjectId: 's', subjectType: 'standalone', userId });
+ const body = `Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`;
+
+ expect(
+ await resolveChangeRequestLinks(serverDB, {
+ ...base,
+ body,
+ scope: { userId, workspaceId: workspace.id },
+ }),
+ ).toEqual({});
+ expect(await resolveChangeRequestLinks(serverDB, { ...base, body })).toEqual({
+ acceptanceId,
+ });
+ });
+
+ it('falls back to the acceptance round that ingested the PR url', async () => {
+ await serverDB
+ .insert(acceptances)
+ .values({ id: acceptanceId, subjectId: 'standalone-1', subjectType: 'standalone', userId });
+ await serverDB.insert(verifyRuns).values({
+ acceptanceId,
+ context: { pullRequest: { number: 19_719, url: base.url } },
+ roundIndex: 1,
+ scenario: 'coding',
+ userId,
+ });
+
+ const links = await resolveChangeRequestLinks(serverDB, base);
+ expect(links).toEqual({ acceptanceId });
+ });
+
+ it('returns nothing when no source matches', async () => {
+ expect(await resolveChangeRequestLinks(serverDB, base)).toEqual({});
+ });
+});
diff --git a/apps/server/src/services/scm/__tests__/scope.test.ts b/apps/server/src/services/scm/__tests__/scope.test.ts
new file mode 100644
index 00000000000..56783237fd6
--- /dev/null
+++ b/apps/server/src/services/scm/__tests__/scope.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { canManageWorkspaceScm, sanitizeReturnTo } from '../scope';
+
+describe('scm scope helpers', () => {
+ it('lets members and above install, never viewers or non-members', () => {
+ expect(canManageWorkspaceScm('owner')).toBe(true);
+ expect(canManageWorkspaceScm('admin')).toBe(true);
+ expect(canManageWorkspaceScm('member')).toBe(true);
+ expect(canManageWorkspaceScm('viewer')).toBe(false);
+ expect(canManageWorkspaceScm(undefined)).toBe(false);
+ });
+
+ it('keeps only same-origin paths as return destinations', () => {
+ expect(sanitizeReturnTo('/settings/integrations/github')).toBe('/settings/integrations/github');
+ expect(sanitizeReturnTo('https://evil.example/phish')).toBeUndefined();
+ expect(sanitizeReturnTo('//evil.example/phish')).toBeUndefined();
+ expect(sanitizeReturnTo('/\\evil.example')).toBeUndefined();
+ expect(sanitizeReturnTo('settings')).toBeUndefined();
+ expect(sanitizeReturnTo(null)).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/scm/github/__tests__/fixtures.ts b/apps/server/src/services/scm/github/__tests__/fixtures.ts
new file mode 100644
index 00000000000..cee148e74ed
--- /dev/null
+++ b/apps/server/src/services/scm/github/__tests__/fixtures.ts
@@ -0,0 +1,130 @@
+/**
+ * Trimmed GitHub webhook payloads: only the fields the normalizer reads, with
+ * the same nesting GitHub uses. Values are stable so tests can assert on them.
+ */
+
+export const repository = {
+ full_name: 'lobehub/lobehub',
+ id: 601_000_001,
+ private: false,
+};
+
+export const installation = { id: 90_001 };
+
+export const sender = { id: 42, login: 'arvinxx' };
+
+export const pullRequest = (overrides: Record<string, unknown> = {}) => ({
+ base: { ref: 'canary' },
+ body: 'Closes the loop.\n\n- Acceptance: https://app.lobehub.com/acceptance/0f1e2d3c-4b5a-4c6d-8e9f-0a1b2c3d4e5f',
+ closed_at: null,
+ draft: false,
+ head: { ref: 'feat/scm-github-app', sha: 'a'.repeat(40) },
+ html_url: 'https://github.com/lobehub/lobehub/pull/19719',
+ merged: false,
+ merged_at: null,
+ merged_by: null,
+ mergeable: true,
+ mergeable_state: 'clean',
+ node_id: 'PR_kwDO1',
+ number: 19_719,
+ state: 'open',
+ title: 'feat(scm): GitHub App core',
+ updated_at: '2026-09-20T06:00:00Z',
+ user: { id: 42, login: 'arvinxx' },
+ ...overrides,
+});
+
+export const pullRequestEvent = (action: string, overrides: Record<string, unknown> = {}) => ({
+ action,
+ installation,
+ pull_request: pullRequest(overrides),
+ repository,
+ sender,
+});
+
+export const checkRunEvent = (overrides: Record<string, unknown> = {}) => ({
+ action: 'completed',
+ check_run: {
+ completed_at: '2026-09-20T06:05:00Z',
+ conclusion: 'failure',
+ details_url: 'https://github.com/lobehub/lobehub/actions/runs/1/job/2',
+ head_sha: 'a'.repeat(40),
+ html_url: 'https://github.com/lobehub/lobehub/runs/2',
+ id: 2,
+ name: 'Test Packages',
+ pull_requests: [{ number: 19_719 }],
+ started_at: '2026-09-20T06:01:00Z',
+ status: 'completed',
+ ...overrides,
+ },
+ installation,
+ repository,
+});
+
+export const reviewEvent = (state: string) => ({
+ action: 'submitted',
+ installation,
+ pull_request: { number: 19_719 },
+ repository,
+ review: {
+ body: 'Please split the handler.',
+ html_url: 'https://github.com/lobehub/lobehub/pull/19719#pullrequestreview-7',
+ id: 7,
+ state,
+ submitted_at: '2026-09-20T06:10:00Z',
+ user: { id: 77, login: 'chatgpt-codex-connector[bot]' },
+ },
+});
+
+export const reviewCommentEvent = () => ({
+ action: 'created',
+ comment: {
+ body: 'This guard is inverted.',
+ created_at: '2026-09-20T06:11:00Z',
+ html_url: 'https://github.com/lobehub/lobehub/pull/19719#discussion_r9',
+ id: 9,
+ line: 42,
+ path: 'apps/server/src/services/scm/ScmIngestService.ts',
+ user: { id: 77, login: 'chatgpt-codex-connector[bot]' },
+ },
+ installation,
+ pull_request: { number: 19_719 },
+ repository,
+});
+
+export const installationEvent = (action: string) => ({
+ action,
+ installation: {
+ account: {
+ avatar_url: 'https://avatars.githubusercontent.com/u/1',
+ id: 1,
+ login: 'lobehub',
+ type: 'Organization',
+ },
+ events: ['pull_request', 'check_run'],
+ id: installation.id,
+ permissions: { checks: 'write', pull_requests: 'write' },
+ repository_selection: 'selected',
+ suspended_at: null,
+ },
+ repositories: [repository],
+ sender,
+});
+
+export const installationRepositoriesEvent = () => ({
+ action: 'added',
+ installation,
+ repositories_added: [{ full_name: 'lobehub/lobehub-cloud', id: 601_000_002, private: true }],
+ repositories_removed: [repository],
+ sender,
+});
+
+export const statusEvent = (state: string) => ({
+ context: 'ci/circleci',
+ installation,
+ repository,
+ sha: 'a'.repeat(40),
+ state,
+ target_url: 'https://circleci.com/gh/lobehub/lobehub/1',
+ updated_at: '2026-09-20T06:06:00Z',
+});
diff --git a/apps/server/src/services/scm/github/__tests__/normalize.test.ts b/apps/server/src/services/scm/github/__tests__/normalize.test.ts
new file mode 100644
index 00000000000..b26e364efde
--- /dev/null
+++ b/apps/server/src/services/scm/github/__tests__/normalize.test.ts
@@ -0,0 +1,248 @@
+import { describe, expect, it } from 'vitest';
+
+import { describeGitHubDelivery, normalizeGitHubEvent } from '../normalize';
+import * as fx from './fixtures';
+
+describe('normalizeGitHubEvent', () => {
+ describe('pull_request', () => {
+ it('maps opened to a change_request event with the body and snapshot', () => {
+ const event = normalizeGitHubEvent('pull_request', fx.pullRequestEvent('opened'));
+
+ expect(event).toMatchObject({
+ actor: { externalId: '42', login: 'arvinxx' },
+ installationId: '90001',
+ kind: 'opened',
+ type: 'change_request',
+ });
+ if (event.type !== 'change_request') throw new Error('unreachable');
+ expect(event.body).toContain('/acceptance/0f1e2d3c');
+ expect(event.changeRequest).toMatchObject({
+ baseRef: 'canary',
+ headRef: 'feat/scm-github-app',
+ headSha: 'a'.repeat(40),
+ isDraft: false,
+ mergeStateStatus: 'CLEAN',
+ metadata: { mergeable: 'true' },
+ number: 19_719,
+ provider: 'github',
+ repoFullName: 'lobehub/lobehub',
+ state: 'open',
+ url: 'https://github.com/lobehub/lobehub/pull/19719',
+ });
+ expect(event.occurredAt).toEqual(new Date('2026-09-20T06:00:00Z'));
+ });
+
+ it('distinguishes merged from closed-without-merge', () => {
+ const merged = normalizeGitHubEvent(
+ 'pull_request',
+ fx.pullRequestEvent('closed', {
+ merged: true,
+ merged_at: '2026-09-20T07:00:00Z',
+ merged_by: { id: 42, login: 'arvinxx' },
+ state: 'closed',
+ }),
+ );
+ expect(merged).toMatchObject({
+ changeRequest: {
+ mergedAt: new Date('2026-09-20T07:00:00Z'),
+ mergedByExternalId: '42',
+ state: 'merged',
+ },
+ kind: 'merged',
+ });
+
+ const closed = normalizeGitHubEvent(
+ 'pull_request',
+ fx.pullRequestEvent('closed', { closed_at: '2026-09-20T07:00:00Z', state: 'closed' }),
+ );
+ expect(closed).toMatchObject({ changeRequest: { state: 'closed' }, kind: 'closed' });
+ });
+
+ it('maps synchronize / ready_for_review / edited and ignores unknown actions', () => {
+ expect(
+ normalizeGitHubEvent('pull_request', fx.pullRequestEvent('synchronize')),
+ ).toMatchObject({
+ kind: 'synchronized',
+ });
+ expect(
+ normalizeGitHubEvent('pull_request', fx.pullRequestEvent('ready_for_review')),
+ ).toMatchObject({ kind: 'ready_for_review' });
+ expect(normalizeGitHubEvent('pull_request', fx.pullRequestEvent('edited'))).toMatchObject({
+ kind: 'synchronized',
+ });
+ expect(normalizeGitHubEvent('pull_request', fx.pullRequestEvent('labeled'))).toMatchObject({
+ type: 'ignored',
+ });
+ });
+ });
+
+ describe('reviews', () => {
+ it('maps a submitted review by state', () => {
+ expect(
+ normalizeGitHubEvent('pull_request_review', fx.reviewEvent('changes_requested')),
+ ).toMatchObject({
+ actor: { externalId: '77' },
+ kind: 'review_changes_requested',
+ number: 19_719,
+ review: { body: 'Please split the handler.', externalId: '7' },
+ type: 'review',
+ });
+ expect(normalizeGitHubEvent('pull_request_review', fx.reviewEvent('APPROVED'))).toMatchObject(
+ {
+ kind: 'review_approved',
+ },
+ );
+ expect(
+ normalizeGitHubEvent('pull_request_review', fx.reviewEvent('commented')),
+ ).toMatchObject({
+ kind: 'review_commented',
+ });
+ // `dismissed` arrives as an action, not a review state: GitHub has
+ // invalidated the verdict, so it has to reach the ingest path.
+ expect(
+ normalizeGitHubEvent('pull_request_review', {
+ ...fx.reviewEvent('dismissed'),
+ action: 'dismissed',
+ }),
+ ).toMatchObject({ kind: 'review_dismissed', occurredAt: undefined, type: 'review' });
+ expect(
+ normalizeGitHubEvent('pull_request_review', {
+ ...fx.reviewEvent('approved'),
+ action: 'edited',
+ }),
+ ).toMatchObject({ type: 'ignored' });
+ });
+
+ it('maps an inline review comment with its file location', () => {
+ expect(
+ normalizeGitHubEvent('pull_request_review_comment', fx.reviewCommentEvent()),
+ ).toMatchObject({
+ kind: 'review_commented',
+ review: {
+ externalId: 'comment:9',
+ line: 42,
+ path: 'apps/server/src/services/scm/ScmIngestService.ts',
+ },
+ type: 'review',
+ });
+ });
+ });
+
+ describe('checks', () => {
+ it('maps a check_run to one check keyed by run id, with the PR numbers attached', () => {
+ const event = normalizeGitHubEvent('check_run', fx.checkRunEvent());
+ expect(event).toEqual({
+ checks: [
+ {
+ completedAt: '2026-09-20T06:05:00Z',
+ conclusion: 'failure',
+ externalId: 'check_run:2',
+ name: 'Test Packages',
+ reportedAt: '2026-09-20T06:05:00Z',
+ startedAt: '2026-09-20T06:01:00Z',
+ status: 'completed',
+ url: 'https://github.com/lobehub/lobehub/runs/2',
+ },
+ ],
+ headSha: 'a'.repeat(40),
+ installationId: '90001',
+ numbers: [19_719],
+ repoFullName: 'lobehub/lobehub',
+ type: 'checks',
+ });
+ });
+
+ it('keeps an in-progress check_run pending with no conclusion', () => {
+ const event = normalizeGitHubEvent(
+ 'check_run',
+ fx.checkRunEvent({
+ completed_at: null,
+ conclusion: null,
+ pull_requests: [],
+ status: 'in_progress',
+ }),
+ );
+ expect(event).toMatchObject({
+ checks: [{ conclusion: undefined, status: 'in_progress' }],
+ numbers: [],
+ });
+ });
+
+ it('folds a commit status into the check set by context', () => {
+ expect(normalizeGitHubEvent('status', fx.statusEvent('failure'))).toMatchObject({
+ checks: [{ conclusion: 'failure', externalId: 'status:ci/circleci', status: 'completed' }],
+ type: 'checks',
+ });
+ expect(normalizeGitHubEvent('status', fx.statusEvent('pending'))).toMatchObject({
+ checks: [{ conclusion: undefined, status: 'in_progress' }],
+ });
+ });
+
+ it('ignores the aggregate events that duplicate check_run', () => {
+ expect(normalizeGitHubEvent('check_suite', { action: 'completed' })).toMatchObject({
+ type: 'ignored',
+ });
+ expect(normalizeGitHubEvent('workflow_run', { action: 'completed' })).toMatchObject({
+ type: 'ignored',
+ });
+ });
+ });
+
+ describe('installations', () => {
+ it('maps installation lifecycle with the account snapshot and repositories', () => {
+ const event = normalizeGitHubEvent('installation', fx.installationEvent('created'));
+ expect(event).toMatchObject({
+ action: 'created',
+ installation: {
+ accountExternalId: '1',
+ accountLogin: 'lobehub',
+ accountType: 'organization',
+ installationId: '90001',
+ metadata: { events: ['pull_request', 'check_run'], permissions: { checks: 'write' } },
+ provider: 'github',
+ repositories: [{ externalId: '601000001', fullName: 'lobehub/lobehub', private: false }],
+ repositorySelection: 'selected',
+ },
+ type: 'installation',
+ });
+ });
+
+ it('maps repository adds and removes', () => {
+ expect(
+ normalizeGitHubEvent('installation_repositories', fx.installationRepositoriesEvent()),
+ ).toEqual({
+ added: [{ externalId: '601000002', fullName: 'lobehub/lobehub-cloud', private: true }],
+ installationId: '90001',
+ removed: [{ externalId: '601000001', fullName: 'lobehub/lobehub', private: false }],
+ type: 'installation_repositories',
+ });
+ });
+ });
+
+ it('ignores events it does not know and incomplete payloads', () => {
+ expect(normalizeGitHubEvent('ping', { zen: 'x' })).toMatchObject({ type: 'ignored' });
+ expect(normalizeGitHubEvent('pull_request', { action: 'opened' })).toMatchObject({
+ type: 'ignored',
+ });
+ });
+});
+
+describe('describeGitHubDelivery', () => {
+ it('extracts the ledger fields from a pull_request payload', () => {
+ expect(describeGitHubDelivery(fx.pullRequestEvent('opened'))).toEqual({
+ action: 'opened',
+ installationId: '90001',
+ number: 19_719,
+ repoFullName: 'lobehub/lobehub',
+ });
+ });
+
+ it('tolerates payloads without a pull request', () => {
+ expect(describeGitHubDelivery({ zen: 'x' })).toEqual({
+ action: null,
+ installationId: null,
+ number: null,
+ repoFullName: null,
+ });
+ });
+});
diff --git a/apps/server/src/services/scm/github/__tests__/signature.test.ts b/apps/server/src/services/scm/github/__tests__/signature.test.ts
new file mode 100644
index 00000000000..07560facfb7
--- /dev/null
+++ b/apps/server/src/services/scm/github/__tests__/signature.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import { signGitHubPayload, verifyGitHubSignature } from '../signature';
+
+const secret = "It's a Secret to Everybody";
+const body = 'Hello, World!';
+
+describe('verifyGitHubSignature', () => {
+ it('accepts the signature GitHub documents for the reference secret and body', () => {
+ // From https://docs.github.com/webhooks/using-webhooks/validating-webhook-deliveries
+ const documented = 'sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17';
+ expect(signGitHubPayload(body, secret)).toBe(documented);
+ expect(verifyGitHubSignature({ rawBody: body, secret, signature: documented })).toBe(true);
+ });
+
+ it('rejects a missing, malformed, or wrong signature', () => {
+ expect(verifyGitHubSignature({ rawBody: body, secret, signature: undefined })).toBe(false);
+ expect(verifyGitHubSignature({ rawBody: body, secret, signature: 'sha1=abc' })).toBe(false);
+ expect(verifyGitHubSignature({ rawBody: body, secret, signature: 'sha256=00' })).toBe(false);
+ expect(
+ verifyGitHubSignature({
+ rawBody: `${body} `,
+ secret,
+ signature: signGitHubPayload(body, secret),
+ }),
+ ).toBe(false);
+ expect(
+ verifyGitHubSignature({
+ rawBody: body,
+ secret: 'other',
+ signature: signGitHubPayload(body, secret),
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/scm/github/app.ts b/apps/server/src/services/scm/github/app.ts
new file mode 100644
index 00000000000..c396f0968ed
--- /dev/null
+++ b/apps/server/src/services/scm/github/app.ts
@@ -0,0 +1,168 @@
+import type { ScmInstallationRepository, ScmInstallationSnapshot } from '@lobechat/types';
+import debug from 'debug';
+import { App, Octokit } from 'octokit';
+
+import { scmEnv } from '@/envs/scm';
+
+const log = debug('lobe-server:scm:github-app');
+
+let cachedApp: App | undefined;
+
+/**
+ * The process-wide GitHub App client. `octokit`'s `App` mints the app JWT and
+ * caches installation tokens (1h TTL) in memory, so there is no token store
+ * to manage here; a fresh process simply mints again.
+ */
+export const getGitHubApp = (): App | null => {
+ if (cachedApp) return cachedApp;
+ if (!scmEnv.ENABLED_GITHUB_APP || !scmEnv.GITHUB_APP_ID || !scmEnv.GITHUB_APP_PRIVATE_KEY) {
+ return null;
+ }
+
+ cachedApp = new App({
+ appId: scmEnv.GITHUB_APP_ID,
+ oauth:
+ scmEnv.GITHUB_APP_CLIENT_ID && scmEnv.GITHUB_APP_CLIENT_SECRET
+ ? { clientId: scmEnv.GITHUB_APP_CLIENT_ID, clientSecret: scmEnv.GITHUB_APP_CLIENT_SECRET }
+ : undefined,
+ privateKey: scmEnv.GITHUB_APP_PRIVATE_KEY,
+ });
+ return cachedApp;
+};
+
+/** Test seam: drop the cached client so a test can rebuild with stubbed env. */
+export const resetGitHubApp = () => {
+ cachedApp = undefined;
+};
+
+/** Where to send a user to install the app. GitHub echoes `state` back on the callback. */
+export const buildGitHubInstallUrl = (state: string): string | null => {
+ if (!scmEnv.GITHUB_APP_SLUG) return null;
+ const url = new URL(`https://github.com/apps/${scmEnv.GITHUB_APP_SLUG}/installations/new`);
+ url.searchParams.set('state', state);
+ return url.toString();
+};
+
+export interface GitHubUserAuthorization {
+ accessToken: string;
+ expiresAt?: string;
+ refreshToken?: string;
+ refreshTokenExpiresAt?: string;
+ user: { avatarUrl?: string; email?: string | null; externalId: string; login: string };
+}
+
+/**
+ * Exchange the `code` GitHub appends to the install callback for a
+ * user-to-server token, and read who the user is. Requires the App to have
+ * "Request user authorization (OAuth) during installation" enabled.
+ */
+export const exchangeGitHubUserCode = async (code: string): Promise<GitHubUserAuthorization> => {
+ const app = getGitHubApp();
+ if (!app) throw new Error('GitHub App is not configured');
+
+ const { authentication } = await app.oauth.createToken({ code });
+ const octokit = new Octokit({ auth: authentication.token });
+ const { data: user } = await octokit.request('GET /user');
+
+ return {
+ accessToken: authentication.token,
+ expiresAt: 'expiresAt' in authentication ? authentication.expiresAt : undefined,
+ refreshToken: 'refreshToken' in authentication ? authentication.refreshToken : undefined,
+ refreshTokenExpiresAt:
+ 'refreshTokenExpiresAt' in authentication ? authentication.refreshTokenExpiresAt : undefined,
+ user: {
+ avatarUrl: user.avatar_url,
+ email: user.email,
+ externalId: String(user.id),
+ login: user.login,
+ },
+ };
+};
+
+/** Read an installation from the API and shape it like a webhook would. */
+export const fetchGitHubInstallation = async (
+ installationId: string,
+): Promise<ScmInstallationSnapshot> => {
+ const app = getGitHubApp();
+ if (!app) throw new Error('GitHub App is not configured');
+
+ const { data } = await app.octokit.request('GET /app/installations/{installation_id}', {
+ installation_id: Number(installationId),
+ });
+
+ const account = data.account as {
+ avatar_url?: string;
+ id?: number;
+ login?: string;
+ type?: string;
+ } | null;
+ const snapshot: ScmInstallationSnapshot = {
+ accountExternalId: String(account?.id ?? ''),
+ accountLogin: String(account?.login ?? ''),
+ accountType: account?.type === 'User' ? 'user' : 'organization',
+ installationId: String(data.id),
+ metadata: {
+ accountAvatarUrl: account?.avatar_url,
+ events: data.events,
+ permissions: data.permissions as Record<string, string>,
+ },
+ provider: 'github',
+ repositorySelection: data.repository_selection === 'selected' ? 'selected' : 'all',
+ suspendedAt: data.suspended_at ? new Date(data.suspended_at) : null,
+ };
+
+ if (snapshot.repositorySelection === 'selected') {
+ snapshot.repositories = await listGitHubInstallationRepositories(installationId);
+ }
+
+ return snapshot;
+};
+
+export const listGitHubInstallationRepositories = async (
+ installationId: string,
+): Promise<ScmInstallationRepository[]> => {
+ const app = getGitHubApp();
+ if (!app) throw new Error('GitHub App is not configured');
+
+ const octokit = await app.getInstallationOctokit(Number(installationId));
+ const repositories: ScmInstallationRepository[] = [];
+ for await (const { data } of octokit.paginate.iterator('GET /installation/repositories', {
+ per_page: 100,
+ })) {
+ for (const repo of data) {
+ repositories.push({
+ externalId: String(repo.id),
+ fullName: repo.full_name,
+ private: repo.private,
+ });
+ }
+ }
+
+ log('installation %s has %d repositories', installationId, repositories.length);
+ return repositories;
+};
+
+/**
+ * The installations the *user* can see, read with their own token. This is
+ * the only signal that ties a person to an installation: the app-level
+ * credential can fetch any installation of this App, so it cannot tell
+ * whether the caller is the one who installed it.
+ */
+export const userCanAccessInstallation = async (
+ accessToken: string,
+ installationId: string,
+): Promise<boolean> => {
+ try {
+ const octokit = new Octokit({ auth: accessToken });
+ for await (const response of octokit.paginate.iterator('GET /user/installations', {
+ per_page: 100,
+ })) {
+ const installations = (response.data ?? []) as { id: number }[];
+ if (installations.some((item) => String(item.id) === installationId)) return true;
+ }
+ return false;
+ } catch (error) {
+ log('cannot list installations for the authorizing user: %O', error);
+ return false;
+ }
+};
diff --git a/apps/server/src/services/scm/github/normalize.ts b/apps/server/src/services/scm/github/normalize.ts
new file mode 100644
index 00000000000..806f9f7681c
--- /dev/null
+++ b/apps/server/src/services/scm/github/normalize.ts
@@ -0,0 +1,358 @@
+import type {
+ ScmChangeRequestEventKind,
+ ScmChangeRequestSnapshot,
+ ScmChangeRequestState,
+ ScmCheck,
+ ScmInstallationRepository,
+ ScmInstallationSnapshot,
+} from '@lobechat/types';
+
+import type { ScmActor, ScmInboundEvent } from '../types';
+
+/**
+ * Translate raw GitHub webhook payloads into provider-neutral
+ * {@link ScmInboundEvent}s. Pure: no I/O, no database. Everything the ingest
+ * service needs must be derivable from the payload alone; the few reads that
+ * need the API (installation repositories on install) happen in the install
+ * callback, not here.
+ *
+ * Payload shapes follow the GitHub webhook reference. Fields are read
+ * defensively β€” GitHub adds fields freely and drops none, so missing means
+ * "not applicable", never "malformed".
+ */
+
+type Json = Record<string, any>;
+
+const str = (value: unknown): string | null =>
+ value === undefined || value === null ? null : String(value);
+
+const date = (value: unknown): Date | null => {
+ if (typeof value !== 'string' || !value) return null;
+ const parsed = new Date(value);
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
+};
+
+const actor = (user: Json | null | undefined): ScmActor | undefined =>
+ user && user.id !== undefined && user.login
+ ? { externalId: String(user.id), login: String(user.login) }
+ : undefined;
+
+const repository = (repo: Json | null | undefined): ScmInstallationRepository | null =>
+ repo && repo.full_name
+ ? {
+ externalId: String(repo.id),
+ fullName: String(repo.full_name),
+ private: repo.private === true,
+ }
+ : null;
+
+const installationSnapshot = (installation: Json): ScmInstallationSnapshot => ({
+ accountExternalId: String(installation.account?.id ?? ''),
+ accountLogin: String(installation.account?.login ?? ''),
+ accountType: installation.account?.type === 'User' ? 'user' : 'organization',
+ installationId: String(installation.id),
+ metadata: {
+ accountAvatarUrl: installation.account?.avatar_url,
+ events: Array.isArray(installation.events) ? installation.events : undefined,
+ permissions: installation.permissions,
+ },
+ provider: 'github',
+ repositorySelection: installation.repository_selection === 'selected' ? 'selected' : 'all',
+ suspendedAt: date(installation.suspended_at),
+});
+
+const pullRequestState = (pr: Json): ScmChangeRequestState => {
+ if (pr.merged === true || pr.merged_at) return 'merged';
+ return pr.state === 'closed' ? 'closed' : 'open';
+};
+
+const pullRequestSnapshot = (repo: Json, pr: Json): ScmChangeRequestSnapshot => ({
+ authorExternalId: str(pr.user?.id),
+ authorExternalLogin: str(pr.user?.login),
+ baseRef: str(pr.base?.ref),
+ closedAt: date(pr.closed_at),
+ externalId: str(pr.node_id),
+ headRef: str(pr.head?.ref),
+ headSha: str(pr.head?.sha),
+ isDraft: pr.draft === true,
+ mergeStateStatus: str(pr.mergeable_state)?.toUpperCase() ?? null,
+ mergedAt: date(pr.merged_at),
+ mergedByExternalId: str(pr.merged_by?.id),
+ metadata:
+ pr.mergeable === null || pr.mergeable === undefined ? {} : { mergeable: String(pr.mergeable) },
+ number: Number(pr.number),
+ provider: 'github',
+ repoExternalId: str(repo.id),
+ repoFullName: String(repo.full_name),
+ state: pullRequestState(pr),
+ title: str(pr.title),
+ url: String(pr.html_url),
+});
+
+const PULL_REQUEST_ACTION_KINDS: Record<string, ScmChangeRequestEventKind> = {
+ converted_to_draft: 'synchronized',
+ edited: 'synchronized',
+ opened: 'opened',
+ ready_for_review: 'ready_for_review',
+ reopened: 'reopened',
+ synchronize: 'synchronized',
+};
+
+const normalizePullRequest = (payload: Json): ScmInboundEvent => {
+ const pr = payload.pull_request;
+ const repo = payload.repository;
+ const installationId = str(payload.installation?.id);
+ if (!pr || !repo || !installationId)
+ return { reason: 'pull_request payload incomplete', type: 'ignored' };
+
+ const action = String(payload.action);
+ let kind: ScmChangeRequestEventKind | undefined;
+ if (action === 'closed') kind = pr.merged === true ? 'merged' : 'closed';
+ else kind = PULL_REQUEST_ACTION_KINDS[action];
+
+ if (!kind) return { reason: `pull_request action ${action} not tracked`, type: 'ignored' };
+
+ return {
+ actor: actor(payload.sender),
+ body: typeof pr.body === 'string' ? pr.body : null,
+ changeRequest: pullRequestSnapshot(repo, pr),
+ installationId,
+ kind,
+ occurredAt: date(pr.updated_at) ?? undefined,
+ type: 'change_request',
+ };
+};
+
+const REVIEW_STATE_KINDS: Record<
+ string,
+ 'review_approved' | 'review_changes_requested' | 'review_commented'
+> = {
+ approved: 'review_approved',
+ changes_requested: 'review_changes_requested',
+ commented: 'review_commented',
+};
+
+const normalizePullRequestReview = (payload: Json): ScmInboundEvent => {
+ const action = String(payload.action);
+ // `dismissed` is tracked too: GitHub has invalidated the review, so the
+ // stored decision has to be cleared rather than left standing.
+ if (action !== 'submitted' && action !== 'dismissed') {
+ return { reason: `pull_request_review action ${action} not tracked`, type: 'ignored' };
+ }
+ const review = payload.review;
+ const pr = payload.pull_request;
+ const repo = payload.repository;
+ const installationId = str(payload.installation?.id);
+ if (!review || !pr || !repo || !installationId) {
+ return { reason: 'pull_request_review payload incomplete', type: 'ignored' };
+ }
+
+ const kind =
+ action === 'dismissed'
+ ? ('review_dismissed' as const)
+ : REVIEW_STATE_KINDS[String(review.state).toLowerCase()];
+ if (!kind) return { reason: `review state ${review.state} not tracked`, type: 'ignored' };
+
+ return {
+ actor: actor(review.user),
+ installationId,
+ kind,
+ number: Number(pr.number),
+ // A dismissal happens now; `submitted_at` still names the original review.
+ occurredAt: action === 'dismissed' ? undefined : (date(review.submitted_at) ?? undefined),
+ repoFullName: String(repo.full_name),
+ review: {
+ body: typeof review.body === 'string' ? review.body : null,
+ externalId: String(review.id),
+ url: str(review.html_url),
+ },
+ type: 'review',
+ };
+};
+
+const normalizePullRequestReviewComment = (payload: Json): ScmInboundEvent => {
+ if (payload.action !== 'created') {
+ return {
+ reason: `pull_request_review_comment action ${payload.action} not tracked`,
+ type: 'ignored',
+ };
+ }
+ const comment = payload.comment;
+ const pr = payload.pull_request;
+ const repo = payload.repository;
+ const installationId = str(payload.installation?.id);
+ if (!comment || !pr || !repo || !installationId) {
+ return { reason: 'pull_request_review_comment payload incomplete', type: 'ignored' };
+ }
+
+ return {
+ actor: actor(comment.user),
+ installationId,
+ kind: 'review_commented',
+ number: Number(pr.number),
+ occurredAt: date(comment.created_at) ?? undefined,
+ repoFullName: String(repo.full_name),
+ review: {
+ body: typeof comment.body === 'string' ? comment.body : null,
+ externalId: `comment:${comment.id}`,
+ line: typeof comment.line === 'number' ? comment.line : (comment.original_line ?? null),
+ path: str(comment.path),
+ url: str(comment.html_url),
+ },
+ type: 'review',
+ };
+};
+
+const checkFromRun = (run: Json): ScmCheck => ({
+ appId: str(run.app?.id) ?? undefined,
+ completedAt: str(run.completed_at) ?? undefined,
+ conclusion: str(run.conclusion) ?? undefined,
+ externalId: `check_run:${run.id}`,
+ name: String(run.name ?? run.id),
+ reportedAt: str(run.completed_at ?? run.started_at) ?? undefined,
+ startedAt: str(run.started_at) ?? undefined,
+ status: String(run.status ?? 'queued'),
+ url: str(run.html_url ?? run.details_url) ?? undefined,
+});
+
+const pullRequestNumbers = (list: unknown): number[] =>
+ Array.isArray(list)
+ ? list.map((item) => Number(item?.number)).filter((n) => Number.isFinite(n))
+ : [];
+
+const normalizeCheckRun = (payload: Json): ScmInboundEvent => {
+ const run = payload.check_run;
+ const repo = payload.repository;
+ const installationId = str(payload.installation?.id);
+ if (!run || !repo || !installationId || !run.head_sha) {
+ return { reason: 'check_run payload incomplete', type: 'ignored' };
+ }
+
+ return {
+ checks: [checkFromRun(run)],
+ headSha: String(run.head_sha),
+ installationId,
+ numbers: pullRequestNumbers(run.pull_requests),
+ repoFullName: String(repo.full_name),
+ type: 'checks',
+ };
+};
+
+/** Legacy commit statuses (external CI posting to the Status API) fold into the same check set. */
+const normalizeStatus = (payload: Json): ScmInboundEvent => {
+ const repo = payload.repository;
+ const installationId = str(payload.installation?.id);
+ if (!payload.sha || !repo || !installationId || !payload.context) {
+ return { reason: 'status payload incomplete', type: 'ignored' };
+ }
+
+ const state = String(payload.state);
+ const completed = state !== 'pending';
+ return {
+ checks: [
+ {
+ completedAt: completed ? (str(payload.updated_at) ?? undefined) : undefined,
+ conclusion: completed ? (state === 'success' ? 'success' : 'failure') : undefined,
+ externalId: `status:${payload.context}`,
+ name: String(payload.context),
+ reportedAt: str(payload.updated_at ?? payload.created_at) ?? undefined,
+ status: completed ? 'completed' : 'in_progress',
+ url: str(payload.target_url) ?? undefined,
+ },
+ ],
+ headSha: String(payload.sha),
+ installationId,
+ numbers: [],
+ repoFullName: String(repo.full_name),
+ type: 'checks',
+ };
+};
+
+const normalizeInstallation = (payload: Json): ScmInboundEvent => {
+ const installation = payload.installation;
+ if (!installation?.id) return { reason: 'installation payload incomplete', type: 'ignored' };
+
+ const action = String(payload.action);
+ if (
+ !['created', 'deleted', 'new_permissions_accepted', 'suspend', 'unsuspend'].includes(action)
+ ) {
+ return { reason: `installation action ${action} not tracked`, type: 'ignored' };
+ }
+
+ const repositories = Array.isArray(payload.repositories)
+ ? payload.repositories.map(repository).filter((r: ScmInstallationRepository | null) => !!r)
+ : [];
+
+ return {
+ action: action as 'created' | 'deleted' | 'new_permissions_accepted' | 'suspend' | 'unsuspend',
+ installation: { ...installationSnapshot(installation), repositories },
+ type: 'installation',
+ };
+};
+
+const normalizeInstallationRepositories = (payload: Json): ScmInboundEvent => {
+ const installationId = str(payload.installation?.id);
+ if (!installationId)
+ return { reason: 'installation_repositories payload incomplete', type: 'ignored' };
+
+ const list = (items: unknown) =>
+ Array.isArray(items)
+ ? items.map(repository).filter((r): r is ScmInstallationRepository => !!r)
+ : [];
+
+ return {
+ added: list(payload.repositories_added),
+ installationId,
+ removed: list(payload.repositories_removed),
+ type: 'installation_repositories',
+ };
+};
+
+/**
+ * Entry point: `event` is the `X-GitHub-Event` header. Unknown events are
+ * ignored (not errors) so subscribing to more events on the App never
+ * produces failed deliveries.
+ */
+export const normalizeGitHubEvent = (event: string, payload: Json): ScmInboundEvent => {
+ switch (event) {
+ case 'pull_request': {
+ return normalizePullRequest(payload);
+ }
+ case 'pull_request_review': {
+ return normalizePullRequestReview(payload);
+ }
+ case 'pull_request_review_comment': {
+ return normalizePullRequestReviewComment(payload);
+ }
+ case 'check_run': {
+ return normalizeCheckRun(payload);
+ }
+ case 'status': {
+ return normalizeStatus(payload);
+ }
+ case 'installation': {
+ return normalizeInstallation(payload);
+ }
+ case 'installation_repositories': {
+ return normalizeInstallationRepositories(payload);
+ }
+ // `check_suite` and `workflow_run` are aggregates of `check_run`; the run-level
+ // events already carry every check with its name and conclusion.
+ default: {
+ return { reason: `event ${event} not tracked`, type: 'ignored' };
+ }
+ }
+};
+
+/** Pull the request-level facts a delivery ledger row records, without normalizing. */
+export const describeGitHubDelivery = (payload: Json) => ({
+ action: str(payload.action),
+ installationId: str(payload.installation?.id),
+ number:
+ typeof payload.pull_request?.number === 'number'
+ ? payload.pull_request.number
+ : typeof payload.number === 'number'
+ ? payload.number
+ : null,
+ repoFullName: str(payload.repository?.full_name),
+});
diff --git a/apps/server/src/services/scm/github/signature.ts b/apps/server/src/services/scm/github/signature.ts
new file mode 100644
index 00000000000..308336142d2
--- /dev/null
+++ b/apps/server/src/services/scm/github/signature.ts
@@ -0,0 +1,30 @@
+import { createHmac, timingSafeEqual } from 'node:crypto';
+
+const SIGNATURE_PREFIX = 'sha256=';
+
+/**
+ * Verify a GitHub webhook signature: `X-Hub-Signature-256` is
+ * `sha256=` + hex(HMAC-SHA256(secret, raw body)). The body must be the exact
+ * bytes GitHub sent, before any JSON parsing.
+ */
+export const verifyGitHubSignature = (params: {
+ rawBody: string;
+ secret: string;
+ signature: string | null | undefined;
+}): boolean => {
+ const { rawBody, secret, signature } = params;
+ if (!signature || !signature.startsWith(SIGNATURE_PREFIX)) return false;
+
+ const expected = createHmac('sha256', secret).update(rawBody, 'utf8').digest('hex');
+ const actual = signature.slice(SIGNATURE_PREFIX.length);
+
+ const expectedBuf = Buffer.from(expected, 'utf8');
+ const actualBuf = Buffer.from(actual, 'utf8');
+ if (expectedBuf.length !== actualBuf.length) return false;
+
+ return timingSafeEqual(expectedBuf, actualBuf);
+};
+
+/** Produce the header value GitHub would send for a body; used by tests and local replay. */
+export const signGitHubPayload = (rawBody: string, secret: string): string =>
+ `${SIGNATURE_PREFIX}${createHmac('sha256', secret).update(rawBody, 'utf8').digest('hex')}`;
diff --git a/apps/server/src/services/scm/links.ts b/apps/server/src/services/scm/links.ts
new file mode 100644
index 00000000000..5eedfa6d630
--- /dev/null
+++ b/apps/server/src/services/scm/links.ts
@@ -0,0 +1,131 @@
+import type { ScmChangeRequestLinks } from '@lobechat/types';
+import { and, desc, eq, inArray, isNotNull, isNull, type SQL, sql } from 'drizzle-orm';
+
+import { acceptances, verifyRuns, works } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+/**
+ * Resolve which LobeHub records a provider change request belongs to. Three
+ * sources, in order of trust:
+ *
+ * 1. The acceptance link the `pr` skill puts in the PR body
+ * (`…/acceptance/<uuid>`).
+ * 2. The `external` Work the agent's `gh pr create` registered
+ * (`works.resourceId = owner/repo#number`). Gives topic + agent.
+ * 3. The acceptance round that recorded this PR url in its coding context
+ * (`verify_runs.context.pullRequest.url`), written by `lh acceptance run ingest`.
+ *
+ * Every source is confined to the tenant the installation is bound to: a
+ * personal installation only sees that user's personal records, a workspace
+ * installation only that workspace's. A PR body can name any acceptance id,
+ * and without this fence a merge on an attacker's repository would accept
+ * someone else's delivery.
+ *
+ * Every source is optional; the result only ever fills links, and the model
+ * never clears one, so a later event with less context cannot undo a match.
+ */
+
+/** Ceiling on how many body ids one delivery may resolve; the body is user-controlled. */
+const MAX_BODY_ACCEPTANCE_IDS = 20;
+
+const ACCEPTANCE_LINK_RE =
+ /\/acceptance\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/gi;
+
+/** Acceptance ids mentioned in free text, de-duplicated in order of appearance. */
+export const parseAcceptanceIds = (text: string | null | undefined): string[] => {
+ if (!text) return [];
+ const ids: string[] = [];
+ for (const match of text.matchAll(ACCEPTANCE_LINK_RE)) {
+ const id = match[1].toLowerCase();
+ if (!ids.includes(id)) ids.push(id);
+ }
+ return ids;
+};
+
+export interface ResolveLinksParams {
+ body?: string | null;
+ number: number;
+ repoFullName: string;
+ /** Scope of the installation the event came through; every source must match it exactly. */
+ scope: { userId: string; workspaceId?: string | null };
+ url: string;
+}
+
+/** Exact tenant match: the workspace, or the user's personal (workspace-less) records. */
+const inScope = (
+ table: { userId: SQL.Aliased | any; workspaceId: any },
+ scope: ResolveLinksParams['scope'],
+): SQL =>
+ scope.workspaceId
+ ? eq(table.workspaceId, scope.workspaceId)
+ : and(eq(table.userId, scope.userId), isNull(table.workspaceId))!;
+
+export const resolveChangeRequestLinks = async (
+ db: LobeChatDatabase,
+ params: ResolveLinksParams,
+): Promise<ScmChangeRequestLinks> => {
+ const links: ScmChangeRequestLinks = {};
+
+ // 1. Acceptance link in the body β€” first id that exists in this scope
+ // wins. The body is user-controlled and may name a hundred ids, so they
+ // are resolved in one query rather than one round trip each.
+ const candidates = parseAcceptanceIds(params.body).slice(0, MAX_BODY_ACCEPTANCE_IDS);
+ if (candidates.length > 0) {
+ const rows = await db
+ .select({
+ id: acceptances.id,
+ subjectId: acceptances.subjectId,
+ subjectType: acceptances.subjectType,
+ })
+ .from(acceptances)
+ .where(and(inArray(acceptances.id, candidates), inScope(acceptances, params.scope)));
+
+ const byId = new Map(rows.map((row) => [row.id, row]));
+ for (const id of candidates) {
+ const row = byId.get(id);
+ if (!row) continue;
+ links.acceptanceId = row.id;
+ if (row.subjectType === 'topic') links.topicId = row.subjectId;
+ if (row.subjectType === 'task') links.taskId = row.subjectId;
+ break;
+ }
+ }
+
+ // 2. The registered Work in this scope, newest first.
+ const resourceId = `${params.repoFullName}#${params.number}`;
+ const [work] = await db
+ .select({ id: works.id, originTopicId: works.originTopicId })
+ .from(works)
+ .where(
+ and(
+ eq(works.resourceType, 'github_pull_request'),
+ eq(works.resourceId, resourceId),
+ inScope(works, params.scope),
+ ),
+ )
+ .orderBy(desc(works.updatedAt))
+ .limit(1);
+ if (work) {
+ links.workId = work.id;
+ if (!links.topicId && work.originTopicId) links.topicId = work.originTopicId;
+ }
+
+ // 3. The acceptance round in this scope that ingested this PR url.
+ if (!links.acceptanceId) {
+ const [run] = await db
+ .select({ acceptanceId: verifyRuns.acceptanceId })
+ .from(verifyRuns)
+ .where(
+ and(
+ isNotNull(verifyRuns.acceptanceId),
+ inScope(verifyRuns, params.scope),
+ sql`${verifyRuns.context} -> 'pullRequest' ->> 'url' = ${params.url}`,
+ ),
+ )
+ .orderBy(desc(verifyRuns.createdAt))
+ .limit(1);
+ if (run?.acceptanceId) links.acceptanceId = run.acceptanceId;
+ }
+
+ return links;
+};
diff --git a/apps/server/src/services/scm/oauth/stateStore.ts b/apps/server/src/services/scm/oauth/stateStore.ts
new file mode 100644
index 00000000000..f031c1336ba
--- /dev/null
+++ b/apps/server/src/services/scm/oauth/stateStore.ts
@@ -0,0 +1,112 @@
+import { randomUUID } from 'node:crypto';
+
+import type { ScmProvider } from '@lobechat/types';
+import debug from 'debug';
+
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+
+const log = debug('lobe-server:scm:oauth-state');
+
+const STATE_TTL_SECONDS = 600;
+const KEY_PREFIX = 'scm:install-state:';
+const CLAIM_TTL_SECONDS = 600;
+const CLAIM_PREFIX = 'scm:install-claim:';
+
+const stateKey = (state: string): string => `${KEY_PREFIX}${state}`;
+const claimKey = (claim: string): string => `${CLAIM_PREFIX}${claim}`;
+
+export interface ScmInstallStatePayload {
+ /** LobeHub user who clicked "Connect"; the installation binds to them. */
+ lobeUserId: string;
+ /** Where to send the user after the callback (relative path). */
+ returnTo?: string;
+ ts: number;
+ /** Workspace to bind the installation to; null for a personal connection. */
+ workspaceId?: string | null;
+}
+
+/**
+ * Single-use state for the install redirect, same Redis pattern as the
+ * messenger OAuth flow: TTL-bound, deleted on first consume, so the callback
+ * cannot be replayed to bind a second installation to the same click.
+ */
+export const issueScmInstallState = async (
+ payload: Omit<ScmInstallStatePayload, 'ts'>,
+): Promise<string> => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) throw new Error('Redis is required for SCM install state storage');
+
+ const state = randomUUID().replaceAll('-', '');
+ const value: ScmInstallStatePayload = { ...payload, ts: Date.now() };
+
+ await redis.set(stateKey(state), JSON.stringify(value), 'EX', STATE_TTL_SECONDS);
+ log('issued state for user=%s workspace=%s', payload.lobeUserId, payload.workspaceId ?? '-');
+ return state;
+};
+
+export const consumeScmInstallState = async (
+ state: string,
+): Promise<ScmInstallStatePayload | null> => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return null;
+
+ const raw = await redis.get(stateKey(state));
+ if (!raw) return null;
+ await redis.del(stateKey(state));
+
+ try {
+ return JSON.parse(raw) as ScmInstallStatePayload;
+ } catch {
+ return null;
+ }
+};
+
+export interface ScmInstallClaimPayload {
+ installationId: string;
+ /** LobeHub user the callback resolved from the session; only they may redeem it. */
+ lobeUserId: string;
+ provider: ScmProvider;
+ ts: number;
+}
+
+/**
+ * Proof that *this* user just came back from GitHub holding *this*
+ * installation. An installation id is a small integer an attacker can guess,
+ * so the confirmation mutation must not accept one on its own: the callback
+ * mints a single-use claim bound to the session it resolved, and redeeming
+ * it is what authorizes the bind.
+ */
+export const issueScmInstallClaim = async (
+ payload: Omit<ScmInstallClaimPayload, 'ts'>,
+): Promise<string | null> => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return null;
+
+ const claim = randomUUID().replaceAll('-', '');
+ const value: ScmInstallClaimPayload = { ...payload, ts: Date.now() };
+
+ await redis.set(claimKey(claim), JSON.stringify(value), 'EX', CLAIM_TTL_SECONDS);
+ log(
+ 'issued install claim for user=%s installation=%s',
+ payload.lobeUserId,
+ payload.installationId,
+ );
+ return claim;
+};
+
+export const consumeScmInstallClaim = async (
+ claim: string,
+): Promise<ScmInstallClaimPayload | null> => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return null;
+
+ const raw = await redis.get(claimKey(claim));
+ if (!raw) return null;
+ await redis.del(claimKey(claim));
+
+ try {
+ return JSON.parse(raw) as ScmInstallClaimPayload;
+ } catch {
+ return null;
+ }
+};
diff --git a/apps/server/src/services/scm/scope.ts b/apps/server/src/services/scm/scope.ts
new file mode 100644
index 00000000000..7b5286d7696
--- /dev/null
+++ b/apps/server/src/services/scm/scope.ts
@@ -0,0 +1,34 @@
+import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
+import type { LobeChatDatabase } from '@/database/type';
+
+/**
+ * Who may bind a provider installation to a workspace: every active member
+ * except read-only viewers. Binding pulls the installation's repositories
+ * and pull-request traffic into the whole workspace, which is a write.
+ */
+const INSTALLER_ROLES: ReadonlySet<string> = new Set(['owner', 'admin', 'member']);
+
+export const canManageWorkspaceScm = (role: string | null | undefined): boolean =>
+ !!role && INSTALLER_ROLES.has(role);
+
+/** `true` for a personal scope, or a workspace the user may install into. */
+export const canWriteScmScope = async (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | null | undefined,
+): Promise<boolean> => {
+ if (!workspaceId) return true;
+ const member = await new WorkspaceMemberModel(db, userId).getMember(workspaceId, userId);
+ return canManageWorkspaceScm(member?.role);
+};
+
+/**
+ * Only same-origin destinations survive: a path with a single leading slash.
+ * `new URL(value, origin)` would keep an absolute or protocol-relative URL
+ * intact, which would turn the install callback into an open redirect.
+ */
+export const sanitizeReturnTo = (value: string | null | undefined): string | undefined => {
+ if (!value) return undefined;
+ if (!value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\')) return undefined;
+ return value;
+};
diff --git a/apps/server/src/services/scm/types.ts b/apps/server/src/services/scm/types.ts
new file mode 100644
index 00000000000..59aa6f64869
--- /dev/null
+++ b/apps/server/src/services/scm/types.ts
@@ -0,0 +1,84 @@
+import type {
+ ScmChangeRequestEventKind,
+ ScmChangeRequestSnapshot,
+ ScmCheck,
+ ScmInstallationRepository,
+ ScmInstallationSnapshot,
+ ScmProvider,
+} from '@lobechat/types';
+
+/** A provider user as it appears on an event. */
+export interface ScmActor {
+ externalId: string;
+ login: string;
+}
+
+/**
+ * One inbound webhook delivery, normalized to provider-neutral shape. Every
+ * provider adapter produces this union; the ingest service consumes it and
+ * never sees a raw payload.
+ */
+export type ScmInboundEvent =
+ | {
+ action: 'created' | 'deleted' | 'new_permissions_accepted' | 'suspend' | 'unsuspend';
+ installation: ScmInstallationSnapshot;
+ type: 'installation';
+ }
+ | {
+ added: ScmInstallationRepository[];
+ installationId: string;
+ removed: ScmInstallationRepository[];
+ type: 'installation_repositories';
+ }
+ | {
+ actor?: ScmActor;
+ /** Change request description; acceptance links are parsed out of it. */
+ body?: string | null;
+ changeRequest: ScmChangeRequestSnapshot;
+ installationId: string;
+ kind: ScmChangeRequestEventKind;
+ occurredAt?: Date;
+ type: 'change_request';
+ }
+ | {
+ checks: ScmCheck[];
+ headSha: string;
+ installationId: string;
+ /** Change request numbers the provider attached; empty for fork PRs, resolved by sha then. */
+ numbers: number[];
+ repoFullName: string;
+ type: 'checks';
+ }
+ | {
+ actor?: ScmActor;
+ installationId: string;
+ kind:
+ 'review_approved' | 'review_changes_requested' | 'review_commented' | 'review_dismissed';
+ number: number;
+ occurredAt?: Date;
+ repoFullName: string;
+ review: {
+ body?: string | null;
+ externalId: string;
+ /** Inline comment location, when the review event is a single comment. */
+ line?: number | null;
+ path?: string | null;
+ url?: string | null;
+ };
+ type: 'review';
+ }
+ | { reason: string; type: 'ignored' };
+
+/** What the handler recorded on the delivery ledger and what it should tell the provider. */
+export interface ScmIngestOutcome {
+ /** Human-readable note for the delivery row (`skipped` reason, affected row id). */
+ detail?: string;
+ status: 'processed' | 'skipped';
+}
+
+export interface ScmDeliveryEnvelope {
+ action?: string | null;
+ deliveryId: string;
+ event: string;
+ provider: ScmProvider;
+}
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index 08dc600cff9..f3d8a9a03ef 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -261,6 +261,9 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
// human decision, not something a restricted key should automate.
resourceTransferRequest: 'blocked',
search: rw('chat:read', null),
+ // source-control integration wiring (installations, linked identities,
+ // tracked pull requests) is configured from Settings, not from keys
+ scm: 'blocked',
session: rw('chat:read', 'chat:write'),
sessionGroup: rw('chat:read', 'chat:write'),
share: rw('chat:read', 'chat:write'),
diff --git a/packages/database/src/models/scm/__tests__/changeRequest.test.ts b/packages/database/src/models/scm/__tests__/changeRequest.test.ts
new file mode 100644
index 00000000000..ea8416d3761
--- /dev/null
+++ b/packages/database/src/models/scm/__tests__/changeRequest.test.ts
@@ -0,0 +1,657 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { acceptances, scmWebhookDeliveries, users } from '../../../schemas';
+import { mergeChecks, rollupCiStatus, ScmChangeRequestModel } from '../changeRequest';
+import { ScmWebhookDeliveryModel } from '../delivery';
+import { ScmInstallationModel } from '../installation';
+
+const serverDB = await getTestDB();
+const userId = 'scm-model-user';
+
+const sha1 = '1'.repeat(40);
+const sha2 = '2'.repeat(40);
+
+const snapshot = {
+ headSha: sha1,
+ number: 7,
+ provider: 'github' as const,
+ repoFullName: 'lobehub/lobehub',
+ state: 'open' as const,
+ url: 'https://github.com/lobehub/lobehub/pull/7',
+ userId,
+};
+
+const check = (name: string, conclusion?: string, status = 'completed') => ({
+ conclusion,
+ externalId: `check_run:${name}`,
+ name,
+ status,
+});
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(scmWebhookDeliveries);
+ await serverDB.delete(users);
+});
+
+describe('rollupCiStatus', () => {
+ it('never calls a cancelled or unrecognized conclusion green', () => {
+ // A cancelled workflow has not passed. Saying `success` here would hand
+ // merge automation a green light it never earned; `failure` would be a
+ // lie in the other direction, since nothing broke.
+ expect(rollupCiStatus([check('Test', 'cancelled')])).toBe('unknown');
+ expect(rollupCiStatus([check('Test', 'stale')])).toBe('unknown');
+ expect(rollupCiStatus([check('Test', undefined)])).toBe('unknown');
+ expect(rollupCiStatus([check('Lint', 'success'), check('Test', 'cancelled')])).toBe('unknown');
+
+ // The green set is exactly success / neutral / skipped.
+ expect(
+ rollupCiStatus([check('a', 'success'), check('b', 'neutral'), check('c', 'skipped')]),
+ ).toBe('success');
+ // Something actually broken still outranks the inconclusive ones.
+ expect(rollupCiStatus([check('Test', 'cancelled'), check('Build', 'failure')])).toBe('failure');
+ });
+
+ it('keeps two apps reporting the same check name apart', () => {
+ // GitHub dedupes "latest per name" *within an app*; collapsing across
+ // apps would let one app's pass erase another app's failure.
+ const failing = {
+ appId: '1',
+ conclusion: 'failure',
+ externalId: 'check_run:10',
+ name: 'Test',
+ reportedAt: '2026-09-20T06:00:00Z',
+ status: 'completed',
+ };
+ const passing = {
+ appId: '2',
+ conclusion: 'success',
+ externalId: 'check_run:11',
+ name: 'Test',
+ reportedAt: '2026-09-20T06:10:00Z',
+ status: 'completed',
+ };
+
+ const merged = mergeChecks([failing], [passing]);
+ expect(merged).toHaveLength(2);
+ expect(rollupCiStatus(merged)).toBe('failure');
+ });
+
+ it('replaces a failed attempt when the job is rerun under a new id', () => {
+ // A rerun mints a new `check_run:<id>`; keeping both would pin the
+ // rollup to failure forever.
+ const failed = {
+ appId: '1',
+ conclusion: 'failure',
+ externalId: 'check_run:1',
+ name: 'Test',
+ reportedAt: '2026-09-20T06:00:00Z',
+ status: 'completed',
+ };
+ const rerun = {
+ appId: '1',
+ conclusion: 'success',
+ externalId: 'check_run:2',
+ name: 'Test',
+ reportedAt: '2026-09-20T06:30:00Z',
+ status: 'completed',
+ };
+
+ const merged = mergeChecks([failed], [rerun]);
+ expect(merged).toEqual([rerun]);
+ expect(rollupCiStatus(merged)).toBe('success');
+
+ // Two providers reporting the same name stay apart.
+ const legacy = {
+ conclusion: 'failure',
+ externalId: 'status:Test',
+ name: 'Test',
+ status: 'completed',
+ };
+ expect(mergeChecks([rerun], [legacy])).toHaveLength(2);
+ });
+
+ it('is unknown with no checks, pending while any runs, failure over success', () => {
+ expect(rollupCiStatus([])).toBe('unknown');
+ expect(rollupCiStatus([check('a', 'success'), check('b', undefined, 'in_progress')])).toBe(
+ 'pending',
+ );
+ expect(rollupCiStatus([check('a', 'success'), check('b', 'failure')])).toBe('failure');
+ expect(rollupCiStatus([check('a', 'success'), check('b', 'skipped')])).toBe('success');
+ });
+
+ it('keeps the newer report when deliveries for one check arrive out of order', () => {
+ const at = (
+ name: string,
+ conclusion: string | undefined,
+ reportedAt: string,
+ status = 'completed',
+ ) => ({
+ conclusion,
+ externalId: 'check_run:9',
+ name,
+ reportedAt,
+ status,
+ });
+
+ // A delayed `queued` must not un-finish a completed run.
+ const completed = at('Test', 'failure', '2026-09-20T06:05:00Z');
+ const stalePending = at('Test', undefined, '2026-09-20T06:01:00Z', 'queued');
+ expect(mergeChecks([completed], [stalePending])).toEqual([completed]);
+
+ // A delayed success must not hide a newer failure.
+ const staleSuccess = at('Test', 'success', '2026-09-20T06:02:00Z');
+ expect(mergeChecks([completed], [staleSuccess])).toEqual([completed]);
+
+ // The genuinely newer result still wins.
+ const newer = at('Test', 'success', '2026-09-20T06:09:00Z');
+ expect(mergeChecks([completed], [newer])).toEqual([newer]);
+
+ // With no timestamps at all, completed still beats pending.
+ const bare = { externalId: 'check_run:8', name: 'Lint', status: 'queued' };
+ const bareDone = {
+ conclusion: 'success',
+ externalId: 'check_run:8',
+ name: 'Lint',
+ status: 'completed',
+ };
+ expect(mergeChecks([bareDone], [bare])).toEqual([bareDone]);
+ });
+
+ it('merges by external id with the incoming check winning', () => {
+ const merged = mergeChecks(
+ [check('a', undefined, 'queued'), check('b', 'success')],
+ [check('a', 'failure')],
+ );
+ expect(merged).toEqual([check('a', 'failure'), check('b', 'success')]);
+ });
+});
+
+describe('ScmChangeRequestModel', () => {
+ it('upserts by identity, keeps links once set, and resets CI on a new head', async () => {
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ subjectId: 's', subjectType: 'standalone', userId })
+ .returning();
+
+ const created = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ eventKind: 'opened',
+ links: { acceptanceId: acceptance.id },
+ title: 'first',
+ });
+ expect(created.acceptanceId).toBe(acceptance.id);
+ expect(created.lastEventKind).toBe('opened');
+
+ await ScmChangeRequestModel.applyChecks(serverDB, created.id, {
+ checks: [check('unit', 'failure')],
+ headSha: sha1,
+ });
+
+ // A later event without links and with a new head commit.
+ const updated = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ eventKind: 'synchronized',
+ headSha: sha2,
+ title: null,
+ });
+ expect(updated.id).toBe(created.id);
+ expect(updated.acceptanceId).toBe(acceptance.id);
+ expect(updated.title).toBe('first');
+ expect(updated.headSha).toBe(sha2);
+ expect(updated.ciStatus).toBeNull();
+ expect(updated.checks).toBeNull();
+ expect(updated.lastEventKind).toBe('synchronized');
+ });
+
+ it('holds checks reported before the push that makes their commit the head', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
+
+ // GitHub reported the job for sha2 before the `synchronize` landed.
+ const early = await ScmChangeRequestModel.applyChecks(serverDB, row.id, {
+ checks: [check('Test', 'success')],
+ headSha: sha2,
+ });
+ expect(early?.applied).toBe(false);
+ expect(early?.row.ciStatus).toBeNull();
+ expect(early?.row.metadata.pendingChecks?.sha).toBe(sha2);
+
+ // The push arrives: the held results are this commit's CI, not leftovers.
+ const pushed = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ eventKind: 'synchronized',
+ headSha: sha2,
+ });
+ expect(pushed.ciHeadSha).toBe(sha2);
+ expect(pushed.ciStatus).toBe('success');
+ expect(pushed.checks).toHaveLength(1);
+ expect(pushed.metadata.pendingChecks).toBeUndefined();
+ });
+
+ it('drops check results for a commit that is no longer the head', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, { ...snapshot, headSha: sha2 });
+
+ const stale = await ScmChangeRequestModel.applyChecks(serverDB, row.id, {
+ checks: [check('unit', 'failure')],
+ headSha: sha1,
+ });
+ expect(stale).toMatchObject({ applied: false, ciStatus: null });
+
+ const fresh = await ScmChangeRequestModel.applyChecks(serverDB, row.id, {
+ checks: [check('unit', undefined, 'in_progress'), check('lint', 'success')],
+ headSha: sha2,
+ });
+ expect(fresh).toMatchObject({ applied: true, ciStatus: 'pending', previousCiStatus: null });
+
+ const done = await ScmChangeRequestModel.applyChecks(serverDB, row.id, {
+ checks: [check('unit', 'success')],
+ headSha: sha2,
+ });
+ expect(done).toMatchObject({ applied: true, ciStatus: 'success', previousCiStatus: 'pending' });
+ expect(done?.row.checks).toHaveLength(2);
+ });
+
+ it('follows a repository rename instead of splitting the change request', async () => {
+ const created = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ externalId: 'PR_node_1',
+ eventKind: 'opened',
+ });
+
+ // The repository is renamed; every later delivery carries the new name.
+ const renamed = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ eventKind: 'synchronized',
+ externalId: 'PR_node_1',
+ repoFullName: 'lobehub/lobehub-renamed',
+ url: 'https://github.com/lobehub/lobehub-renamed/pull/7',
+ });
+
+ expect(renamed.id).toBe(created.id);
+ expect(renamed.repoFullName).toBe('lobehub/lobehub-renamed');
+ expect(
+ await ScmChangeRequestModel.findByIdentity(
+ serverDB,
+ 'github',
+ 'lobehub/lobehub-renamed',
+ snapshot.number,
+ ),
+ ).toMatchObject({ id: created.id });
+ });
+
+ it('finds rows by head sha and fills only missing links', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
+ const [installation] = [
+ await ScmInstallationModel.bind(serverDB, {
+ accountExternalId: '1',
+ accountLogin: 'lobehub',
+ accountType: 'organization',
+ installationId: '90001',
+ provider: 'github',
+ repositorySelection: 'all',
+ userId,
+ }),
+ ];
+
+ await ScmChangeRequestModel.attachLinks(serverDB, row.id, { installationId: installation.id });
+ const other = await ScmInstallationModel.bind(serverDB, {
+ accountExternalId: '2',
+ accountLogin: 'other',
+ accountType: 'user',
+ installationId: '90002',
+ provider: 'github',
+ repositorySelection: 'all',
+ userId,
+ });
+ const after = await ScmChangeRequestModel.attachLinks(serverDB, row.id, {
+ installationId: other.id,
+ });
+ expect(after?.installationId).toBe(installation.id);
+
+ expect(
+ await ScmChangeRequestModel.findByHeadSha(serverDB, 'github', 'lobehub/lobehub', sha1),
+ ).toHaveLength(1);
+ expect(
+ await ScmChangeRequestModel.findByHeadSha(serverDB, 'github', 'lobehub/lobehub', sha2),
+ ).toHaveLength(0);
+ });
+
+ it('ignores a delivery older than the last one applied, and never reopens a merge', async () => {
+ const merged = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ eventAt: new Date('2026-09-20T12:00:00Z'),
+ eventKind: 'merged',
+ mergedAt: new Date('2026-09-20T12:00:00Z'),
+ state: 'merged',
+ });
+ expect(merged.state).toBe('merged');
+
+ // A redelivered `opened` from before the merge: links still fill, the
+ // lifecycle does not move.
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ subjectId: 's', subjectType: 'standalone', userId })
+ .returning();
+ const replayed = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ eventAt: new Date('2026-09-20T09:00:00Z'),
+ eventKind: 'opened',
+ headSha: sha2,
+ links: { acceptanceId: acceptance.id },
+ state: 'open',
+ });
+ expect(replayed.state).toBe('merged');
+ expect(replayed.headSha).toBe(sha1);
+ expect(replayed.lastEventKind).toBe('merged');
+ expect(replayed.acceptanceId).toBe(acceptance.id);
+
+ // Even a *newer* event cannot walk a merge back to open.
+ const later = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ eventAt: new Date('2026-09-20T18:00:00Z'),
+ eventKind: 'reopened',
+ state: 'open',
+ });
+ expect(later.state).toBe('merged');
+ });
+
+ it('keeps every check when deliveries for one commit land concurrently', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
+ const names = ['Lint', 'Test', 'Build', 'Typecheck', 'E2E', 'Docs'];
+
+ await Promise.all(
+ names.map((name) =>
+ ScmChangeRequestModel.applyChecks(serverDB, row.id, {
+ checks: [check(name, name === 'Test' ? 'failure' : 'success')],
+ headSha: sha1,
+ }),
+ ),
+ );
+
+ const after = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect((after?.checks ?? []).map((c) => c.name).sort()).toEqual([...names].sort());
+ expect(after?.ciStatus).toBe('failure');
+ });
+
+ it('follows the installation to a new tenant and drops the old tenant links', async () => {
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ subjectId: 's', subjectType: 'standalone', userId })
+ .returning();
+ const first = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ links: { acceptanceId: acceptance.id },
+ });
+ expect(first.acceptanceId).toBe(acceptance.id);
+
+ await serverDB.insert(users).values({ id: 'scm-model-user-2' });
+ const moved = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ userId: 'scm-model-user-2',
+ });
+ expect(moved.id).toBe(first.id);
+ expect(moved.userId).toBe('scm-model-user-2');
+ expect(moved.acceptanceId).toBeNull();
+ expect(moved.topicId).toBeNull();
+ });
+
+ it('rolls up review verdicts per reviewer, in any delivery order', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
+
+ // Reviewer A requests changes, reviewer B approves afterwards: the
+ // outstanding request still governs.
+ await ScmChangeRequestModel.applyReviewerDecision(serverDB, row.id, {
+ at: new Date('2026-09-20T08:00:00Z'),
+ decision: 'changes_requested',
+ reviewerId: 'rev-a',
+ });
+ await ScmChangeRequestModel.applyReviewerDecision(serverDB, row.id, {
+ at: new Date('2026-09-20T08:30:00Z'),
+ decision: 'approved',
+ reviewerId: 'rev-b',
+ });
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.reviewDecision).toBe(
+ 'changes_requested',
+ );
+
+ // A stale delivery of A's earlier verdict does not undo a newer one,
+ // and says so, so the caller can skip the downstream side effects.
+ expect(
+ await ScmChangeRequestModel.applyReviewerDecision(serverDB, row.id, {
+ at: new Date('2026-09-20T12:00:00Z'),
+ decision: 'approved',
+ reviewerId: 'rev-a',
+ }),
+ ).toMatchObject({ applied: true });
+ expect(
+ await ScmChangeRequestModel.applyReviewerDecision(serverDB, row.id, {
+ at: new Date('2026-09-20T09:00:00Z'),
+ decision: 'changes_requested',
+ reviewerId: 'rev-a',
+ }),
+ ).toMatchObject({ applied: false, reviewDecision: 'approved' });
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.reviewDecision).toBe(
+ 'approved',
+ );
+
+ // A dismisses their own review: only B's approval is left.
+ await ScmChangeRequestModel.applyReviewerDecision(serverDB, row.id, {
+ at: new Date('2026-09-20T13:00:00Z'),
+ decision: null,
+ reviewerId: 'rev-a',
+ });
+ const after = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect(after?.reviewDecision).toBe('approved');
+ expect(Object.keys(after?.metadata.reviewers ?? {})).toEqual(['rev-b']);
+ });
+
+ it('serializes a merge against an older synchronize that overlaps it', async () => {
+ await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ eventAt: new Date('2026-09-20T08:00:00Z'),
+ eventKind: 'opened',
+ state: 'open',
+ });
+
+ // Both deliveries start from the same open row; the row lock decides
+ // the order, and the merge must survive whichever writes last.
+ await Promise.all([
+ ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ eventAt: new Date('2026-09-20T12:00:00Z'),
+ eventKind: 'merged',
+ mergedAt: new Date('2026-09-20T12:00:00Z'),
+ state: 'merged',
+ }),
+ ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ eventAt: new Date('2026-09-20T11:00:00Z'),
+ eventKind: 'synchronized',
+ headSha: sha2,
+ state: 'open',
+ }),
+ ]);
+
+ const after = await ScmChangeRequestModel.findById(
+ serverDB,
+ (await ScmChangeRequestModel.findByIdentity(
+ serverDB,
+ snapshot.provider,
+ snapshot.repoFullName,
+ snapshot.number,
+ ))!.id,
+ );
+ expect(after?.state).toBe('merged');
+ expect(after?.headSha).toBe(sha1);
+ });
+
+ it('clears the closure stamp when a pull request reopens', async () => {
+ const closedAt = new Date('2026-09-20T10:00:00Z');
+ const closed = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ closedAt,
+ eventKind: 'closed',
+ state: 'closed',
+ });
+ expect(closed.closedAt).toEqual(closedAt);
+
+ // GitHub reports `closed_at: null` on a reopen; keeping the old stamp
+ // would leave the row open and closed at once.
+ const reopened = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ closedAt: null,
+ eventKind: 'reopened',
+ state: 'open',
+ });
+ expect(reopened.state).toBe('open');
+ expect(reopened.closedAt).toBeNull();
+ // A descriptive field the event did not carry is still kept.
+ expect(reopened.title).toBe(closed.title);
+ });
+
+ it('keeps concurrent repository grants from overwriting each other', async () => {
+ const repo = (id: string) => ({ externalId: id, fullName: `arvinxx/r${id}` });
+ const installation = await ScmInstallationModel.bind(serverDB, {
+ accountExternalId: 'acct-repos',
+ accountLogin: 'arvinxx',
+ accountType: 'user',
+ installationId: '500',
+ provider: 'github',
+ repositories: [repo('1'), repo('2')],
+ repositorySelection: 'selected',
+ userId,
+ });
+
+ await Promise.all([
+ ScmInstallationModel.applyRepositoryChange(serverDB, installation.id, {
+ added: [repo('3')],
+ removed: [],
+ }),
+ ScmInstallationModel.applyRepositoryChange(serverDB, installation.id, {
+ added: [],
+ removed: [repo('1')],
+ }),
+ ScmInstallationModel.applyRepositoryChange(serverDB, installation.id, {
+ added: [repo('4')],
+ removed: [],
+ }),
+ ]);
+
+ const after = await ScmInstallationModel.findById(serverDB, installation.id);
+ expect((after?.repositories ?? []).map((r) => r.externalId).sort()).toEqual(['2', '3', '4']);
+ });
+
+ it('counts wakes', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
+ expect(await ScmChangeRequestModel.recordWake(serverDB, row.id)).toBe(1);
+ expect(await ScmChangeRequestModel.recordWake(serverDB, row.id)).toBe(2);
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.lastWakeAt).not.toBeNull();
+ });
+});
+
+describe('ScmWebhookDeliveryModel', () => {
+ it('claims a delivery once and settles it', async () => {
+ const key = { deliveryId: 'd-1', provider: 'github' as const };
+ const first = await ScmWebhookDeliveryModel.claim(serverDB, { ...key, event: 'pull_request' });
+ expect(first?.status).toBe('received');
+ expect(
+ await ScmWebhookDeliveryModel.claim(serverDB, { ...key, event: 'pull_request' }),
+ ).toBeNull();
+
+ await ScmWebhookDeliveryModel.settle(serverDB, key, {
+ status: 'processed',
+ error: 'scr_x opened',
+ });
+ const [row] = await serverDB.select().from(scmWebhookDeliveries);
+ expect(row).toMatchObject({ error: 'scr_x opened', status: 'processed' });
+ expect(row.processedAt).not.toBeNull();
+
+ expect(await ScmWebhookDeliveryModel.pruneBefore(serverDB, new Date(Date.now() + 1000))).toBe(
+ 1,
+ );
+ });
+
+ it('lets a failed or abandoned delivery be replayed, but never a settled one', async () => {
+ const key = { deliveryId: 'd-2', provider: 'github' as const };
+ const claim = () => ScmWebhookDeliveryModel.claim(serverDB, { ...key, event: 'pull_request' });
+
+ expect((await claim())?.status).toBe('received');
+ // In flight: a redelivery must not run the handler a second time.
+ expect(await claim()).toBeNull();
+
+ // Failed: redelivery is how GitHub recovers the event, so it is claimable.
+ await ScmWebhookDeliveryModel.settle(serverDB, key, { error: 'boom', status: 'failed' });
+ const retried = await claim();
+ expect(retried).toMatchObject({ error: null, status: 'received' });
+ expect(retried?.processedAt).toBeNull();
+
+ // Settled: nothing to redo.
+ await ScmWebhookDeliveryModel.settle(serverDB, key, { status: 'processed' });
+ expect(await claim()).toBeNull();
+ await ScmWebhookDeliveryModel.settle(serverDB, key, { status: 'skipped' });
+ expect(await claim()).toBeNull();
+
+ // Stuck in `received` past the window β€” the process died mid-flight.
+ await serverDB
+ .update(scmWebhookDeliveries)
+ .set({
+ processedAt: null,
+ receivedAt: new Date(Date.now() - 10 * 60_000),
+ status: 'received',
+ })
+ .where(eq(scmWebhookDeliveries.deliveryId, 'd-2'));
+ expect((await claim())?.status).toBe('received');
+ });
+});
+
+describe('ScmInstallationModel', () => {
+ it('retires the stale row when the same account comes back under a new installation id', async () => {
+ const base = {
+ accountExternalId: 'acct-1',
+ accountLogin: 'arvinxx',
+ accountType: 'user' as const,
+ provider: 'github' as const,
+ repositorySelection: 'all' as const,
+ userId,
+ };
+ const old = await ScmInstallationModel.bind(serverDB, { ...base, installationId: '100' });
+ const fresh = await ScmInstallationModel.bind(serverDB, { ...base, installationId: '200' });
+ expect(fresh.id).not.toBe(old.id);
+
+ const listed = await ScmInstallationModel.listByScope(serverDB, { userId });
+ expect(listed.map((i) => i.installationId)).toEqual(['200']);
+ expect((await ScmInstallationModel.findById(serverDB, old.id))?.revokedAt).not.toBeNull();
+ });
+
+ it('re-binding the same installation keeps its id, moves scope, and clears revocation', async () => {
+ const params = {
+ accountExternalId: '1',
+ accountLogin: 'lobehub',
+ accountType: 'organization' as const,
+ installationId: '90001',
+ provider: 'github' as const,
+ repositorySelection: 'all' as const,
+ userId,
+ };
+ const first = await ScmInstallationModel.bind(serverDB, params);
+ await ScmInstallationModel.markRevoked(serverDB, first.id);
+
+ const second = await ScmInstallationModel.bind(serverDB, {
+ ...params,
+ repositorySelection: 'selected',
+ repositories: [{ externalId: '9', fullName: 'lobehub/x' }],
+ });
+ expect(second.id).toBe(first.id);
+ expect(second.revokedAt).toBeNull();
+ expect(second.repositorySelection).toBe('selected');
+
+ expect(await ScmInstallationModel.listByScope(serverDB, { userId })).toHaveLength(1);
+ expect(await ScmInstallationModel.listByScope(serverDB, { userId: 'nobody' })).toHaveLength(0);
+ });
+});
diff --git a/packages/database/src/models/scm/changeRequest.ts b/packages/database/src/models/scm/changeRequest.ts
new file mode 100644
index 00000000000..07c5efd36e2
--- /dev/null
+++ b/packages/database/src/models/scm/changeRequest.ts
@@ -0,0 +1,590 @@
+import type {
+ ScmApplyChecksParams,
+ ScmApplyChecksResult,
+ ScmChangeRequestEventKind,
+ ScmChangeRequestLinks,
+ ScmCheck,
+ ScmCiStatus,
+ ScmProvider,
+ ScmReviewDecision,
+ ScmUpsertChangeRequestParams,
+} from '@lobechat/types';
+import { and, desc, eq, isNull } from 'drizzle-orm';
+
+import type { ScmChangeRequestItem } from '../../schemas';
+import { scmChangeRequests } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+/**
+ * Conclusions worth waking an agent over: something broke and there is
+ * something to fix. A cancelled or stale run is not one of them β€” usually a
+ * human superseded it β€” but it is not a pass either, which is why the two
+ * sets below are separate rather than complements.
+ */
+const FAILING_CONCLUSIONS = new Set(['action_required', 'failure', 'startup_failure', 'timed_out']);
+
+/** The only conclusions that let the rollup read as green. */
+const GREEN_CONCLUSIONS = new Set(['neutral', 'skipped', 'success']);
+
+/**
+ * Fold a set of checks into one CI status. Pending wins over everything
+ * because the user cannot act on a partial result, then failure, then
+ * `unknown` β€” a commit whose workflow was cancelled has not passed, and
+ * saying `success` there would hand a green light to merge automation. An
+ * empty set is `unknown` too, so "no CI configured" never reads as green.
+ */
+export const rollupCiStatus = (checks: ScmCheck[] | null | undefined): ScmCiStatus => {
+ if (!checks || checks.length === 0) return 'unknown';
+
+ let failed = false;
+ let inconclusive = false;
+ for (const check of checks) {
+ if (check.status !== 'completed') return 'pending';
+ if (check.conclusion && FAILING_CONCLUSIONS.has(check.conclusion)) failed = true;
+ else if (!check.conclusion || !GREEN_CONCLUSIONS.has(check.conclusion)) inconclusive = true;
+ }
+
+ if (failed) return 'failure';
+ return inconclusive ? 'unknown' : 'success';
+};
+
+/** Whether one check's conclusion counts as a failure in the rollup. */
+export const isFailingCheck = (check: ScmCheck): boolean =>
+ check.status === 'completed' && !!check.conclusion && FAILING_CONCLUSIONS.has(check.conclusion);
+
+/** Merge incoming checks into the stored set by external id; incoming wins. */
+/**
+ * When this result was reported, as the provider timed it. A completed run
+ * always sorts after a pending one for the same id, so a delayed "queued"
+ * cannot un-finish a check even when neither side carries a timestamp.
+ */
+const reportedAt = (check: ScmCheck): number => {
+ const stamp = check.reportedAt ?? check.completedAt ?? check.startedAt;
+ const parsed = stamp ? Date.parse(stamp) : Number.NaN;
+ if (!Number.isNaN(parsed)) return parsed;
+ return check.status === 'completed' ? 1 : 0;
+};
+
+/**
+ * What the check *is*, as opposed to which attempt reported it. Re-running a
+ * failed Actions job mints a new `check_run:<id>`, so keying the set by the
+ * external id alone keeps the failed attempt next to its successful
+ * replacement and pins the rollup to `failure` forever.
+ *
+ * GitHub's own answer to "which result counts" is the latest run of a given
+ * name *published by a given app* (`GET /commits/{ref}/check-runs?filter=latest`),
+ * so that is the identity used here. Dropping the app would let one app's
+ * passing `Test` erase another's failing `Test`; dropping the name would
+ * stop reruns from superseding anything. The legacy status API has no app
+ * and its context is unique per commit, so its namespace carries the name
+ * alone.
+ */
+const checkIdentity = (check: ScmCheck): string => {
+ const [namespace] = check.externalId.split(':');
+ const name = check.name?.trim();
+ if (!name) return check.externalId;
+ return check.appId ? `${namespace}:app:${check.appId}:${name}` : `${namespace}:${name}`;
+};
+
+export const mergeChecks = (current: ScmCheck[] | null | undefined, incoming: ScmCheck[]) => {
+ const byIdentity = new Map<string, ScmCheck>();
+ for (const check of current ?? []) byIdentity.set(checkIdentity(check), check);
+ for (const check of incoming) {
+ const key = checkIdentity(check);
+ const stored = byIdentity.get(key);
+ // A delayed pending event must not regress a completed check, and a
+ // delayed success must not hide a newer failure.
+ if (stored && reportedAt(stored) > reportedAt(check)) continue;
+ byIdentity.set(key, check);
+ }
+ return [...byIdentity.values()];
+};
+
+/**
+ * CRUD for `scm_change_requests`, the hub row an inbound provider event
+ * resolves to. Writers are server-side ingest paths, so the model is static
+ * over the db; scope lives on the row.
+ */
+export class ScmChangeRequestModel {
+ /**
+ * The change request by the provider's own id for it (GitHub's PR node
+ * id). Stable across a repository rename or transfer, which is what the
+ * name-based key is not.
+ */
+ static findByExternalId = async (
+ db: LobeChatDatabase,
+ provider: ScmProvider,
+ externalId: string,
+ ): Promise<ScmChangeRequestItem | null> => {
+ const [row] = await db
+ .select()
+ .from(scmChangeRequests)
+ .where(
+ and(eq(scmChangeRequests.provider, provider), eq(scmChangeRequests.externalId, externalId)),
+ )
+ .limit(1);
+
+ return row ?? null;
+ };
+
+ static findByIdentity = async (
+ db: LobeChatDatabase,
+ provider: ScmProvider,
+ repoFullName: string,
+ number: number,
+ ): Promise<ScmChangeRequestItem | null> => {
+ const [row] = await db
+ .select()
+ .from(scmChangeRequests)
+ .where(
+ and(
+ eq(scmChangeRequests.provider, provider),
+ eq(scmChangeRequests.repoFullName, repoFullName),
+ eq(scmChangeRequests.number, number),
+ ),
+ )
+ .limit(1);
+
+ return row ?? null;
+ };
+
+ static findById = async (
+ db: LobeChatDatabase,
+ id: string,
+ ): Promise<ScmChangeRequestItem | null> => {
+ const [row] = await db.select().from(scmChangeRequests).where(eq(scmChangeRequests.id, id));
+ return row ?? null;
+ };
+
+ /** Open change requests whose head is the given commit; `check_run` events name a sha, not a number. */
+ static findByHeadSha = async (
+ db: LobeChatDatabase,
+ provider: ScmProvider,
+ repoFullName: string,
+ headSha: string,
+ ): Promise<ScmChangeRequestItem[]> =>
+ db
+ .select()
+ .from(scmChangeRequests)
+ .where(
+ and(
+ eq(scmChangeRequests.provider, provider),
+ eq(scmChangeRequests.repoFullName, repoFullName),
+ eq(scmChangeRequests.headSha, headSha),
+ ),
+ );
+
+ static listByAcceptance = async (
+ db: LobeChatDatabase,
+ acceptanceId: string,
+ ): Promise<ScmChangeRequestItem[]> =>
+ db
+ .select()
+ .from(scmChangeRequests)
+ .where(eq(scmChangeRequests.acceptanceId, acceptanceId))
+ .orderBy(desc(scmChangeRequests.updatedAt));
+
+ /** Change requests visible to a scope, newest activity first. */
+ static listByScope = async (
+ db: LobeChatDatabase,
+ scope: { userId: string; workspaceId?: string | null },
+ options: { limit?: number } = {},
+ ): Promise<ScmChangeRequestItem[]> => {
+ const scopeCondition = scope.workspaceId
+ ? eq(scmChangeRequests.workspaceId, scope.workspaceId)
+ : and(eq(scmChangeRequests.userId, scope.userId), isNull(scmChangeRequests.workspaceId));
+
+ return db
+ .select()
+ .from(scmChangeRequests)
+ .where(scopeCondition)
+ .orderBy(desc(scmChangeRequests.updatedAt))
+ .limit(options.limit ?? 50);
+ };
+
+ static listByTopic = async (
+ db: LobeChatDatabase,
+ topicId: string,
+ ): Promise<ScmChangeRequestItem[]> =>
+ db
+ .select()
+ .from(scmChangeRequests)
+ .where(eq(scmChangeRequests.topicId, topicId))
+ .orderBy(desc(scmChangeRequests.updatedAt));
+
+ /**
+ * Create or refresh the hub row from a provider snapshot. A new head commit
+ * resets the CI rollup: the stored checks described the old commit.
+ * Links are only ever filled in, never cleared, so a later event that could
+ * not resolve the acceptance does not drop a link an earlier one found β€”
+ * unless the installation moved to another tenant since the row was
+ * created, in which case the row follows it and the tenant-owned links
+ * (acceptance, topic, task, Work) start over from what this event resolved.
+ */
+ static upsert = async (
+ db: LobeChatDatabase,
+ params: ScmUpsertChangeRequestParams,
+ ): Promise<ScmChangeRequestItem> =>
+ // The whole read-modify-write runs under a row lock. Reading the row
+ // outside one lets a `merged` and an older `synchronize` delivery both
+ // see the pre-merge state, and whichever writes last wins β€” the stale
+ // guards below can only judge what they were shown.
+ db.transaction(async (tx) => {
+ // Renaming or transferring a repository changes `repoFullName` on
+ // every later delivery, so the name-based key would miss the row and
+ // insert a second one β€” splitting the checks, the review state and
+ // the acceptance links off the copy still on screen. The provider's
+ // own id for the pull request survives both, so it leads.
+ const [existing] = await tx
+ .select()
+ .from(scmChangeRequests)
+ .where(
+ and(
+ eq(scmChangeRequests.provider, params.provider),
+ params.externalId
+ ? eq(scmChangeRequests.externalId, params.externalId)
+ : and(
+ eq(scmChangeRequests.repoFullName, params.repoFullName),
+ eq(scmChangeRequests.number, params.number),
+ )!,
+ ),
+ )
+ .for('update');
+
+ // Deliveries are not ordered: GitHub retries, and a redelivery of an old
+ // `opened` after a `merged` would otherwise reopen the row, rewind the
+ // head and drop the CI rollup for the commit that actually landed. Two
+ // independent guards, because neither covers the other:
+ //
+ // - an event whose provider timestamp predates the newest one applied is
+ // a replay (compared provider-clock to provider-clock; the
+ // `lastEventAt` column also carries events we stamp ourselves, so it
+ // cannot serve as the reference);
+ // - a merge is terminal and a close only reopens through `reopened`,
+ // whatever the timestamps say.
+ const previousEventAt = existing?.metadata?.lastProviderEventAt;
+ const outOfOrder =
+ !!previousEventAt && !!params.eventAt && params.eventAt < new Date(previousEventAt);
+ const regressesLifecycle =
+ (existing?.state === 'merged' && params.state !== 'merged') ||
+ (existing?.state === 'closed' &&
+ params.state === 'open' &&
+ params.eventKind !== 'reopened');
+ const stale = !!existing && (outOfOrder || regressesLifecycle);
+
+ const headChanged =
+ !stale && !!params.headSha && !!existing && existing.headSha !== params.headSha;
+ const links = params.links ?? {};
+ const now = new Date();
+
+ // Lifecycle stamps are state the provider can legitimately reset β€” a
+ // reopened pull request reports `closed_at: null` β€” so for those an
+ // explicit `null` clears the column and only `undefined` (the caller
+ // said nothing) keeps it. Descriptive fields keep the lenient rule: a
+ // payload that omits the title should not erase the stored one.
+ const resettable = <T>(
+ next: T | null | undefined,
+ previous: T | null | undefined,
+ ): T | null => (next === undefined ? (previous ?? null) : next);
+
+ const snapshot = {
+ authorExternalId: params.authorExternalId ?? existing?.authorExternalId ?? null,
+ authorExternalLogin: params.authorExternalLogin ?? existing?.authorExternalLogin ?? null,
+ baseRef: params.baseRef ?? existing?.baseRef ?? null,
+ closedAt: resettable(params.closedAt, existing?.closedAt),
+ externalId: params.externalId ?? existing?.externalId ?? null,
+ headRef: params.headRef ?? existing?.headRef ?? null,
+ headSha: params.headSha ?? existing?.headSha ?? null,
+ isDraft: params.isDraft ?? existing?.isDraft ?? false,
+ mergeStateStatus: params.mergeStateStatus ?? existing?.mergeStateStatus ?? null,
+ mergedAt: resettable(params.mergedAt, existing?.mergedAt),
+ mergedByExternalId: resettable(params.mergedByExternalId, existing?.mergedByExternalId),
+ metadata: {
+ ...existing?.metadata,
+ ...params.metadata,
+ ...(params.eventAt ? { lastProviderEventAt: params.eventAt.toISOString() } : {}),
+ // Once adopted (or superseded by a newer head) the bucket is spent.
+ ...(headChanged ? { pendingChecks: undefined } : {}),
+ },
+ repoExternalId: params.repoExternalId ?? existing?.repoExternalId ?? null,
+ // Follow a rename rather than leaving the row under the old name.
+ repoFullName: params.repoFullName,
+ state: params.state,
+ title: params.title ?? existing?.title ?? null,
+ url: params.url,
+ };
+
+ const scopeMoved =
+ !!existing &&
+ (existing.userId !== params.userId ||
+ (existing.workspaceId ?? null) !== (params.workspaceId ?? null));
+ const inherited = scopeMoved ? undefined : existing;
+ const linkValues = {
+ acceptanceId: links.acceptanceId ?? inherited?.acceptanceId ?? null,
+ installationId: links.installationId ?? existing?.installationId ?? null,
+ taskId: links.taskId ?? inherited?.taskId ?? null,
+ topicId: links.topicId ?? inherited?.topicId ?? null,
+ workId: links.workId ?? inherited?.workId ?? null,
+ };
+ const ownerValues = scopeMoved
+ ? { userId: params.userId, workspaceId: params.workspaceId ?? null }
+ : {};
+
+ const ciValues = headChanged
+ ? (() => {
+ // Results reported before this push became the head belong to
+ // the new commit, not to the one being replaced.
+ const held = existing?.metadata?.pendingChecks;
+ const adopted = held && held.sha === params.headSha ? held.checks : null;
+ return {
+ checks: adopted,
+ ciHeadSha: params.headSha ?? null,
+ ciStatus: adopted ? rollupCiStatus(adopted) : null,
+ };
+ })()
+ : {};
+
+ const eventValues =
+ params.eventKind && !stale
+ ? { lastEventAt: params.eventAt ?? now, lastEventKind: params.eventKind }
+ : {};
+
+ if (existing) {
+ // A stale delivery still carries link context worth keeping (an
+ // acceptance id parsed from the body), so fills apply; the lifecycle
+ // columns do not.
+ const stateValues = stale
+ ? { metadata: { ...snapshot.metadata, ...existing.metadata, ...params.metadata } }
+ : snapshot;
+ const [row] = await tx
+ .update(scmChangeRequests)
+ .set({
+ ...stateValues,
+ ...linkValues,
+ ...ownerValues,
+ ...ciValues,
+ ...eventValues,
+ updatedAt: now,
+ })
+ .where(eq(scmChangeRequests.id, existing.id))
+ .returning();
+ return row;
+ }
+
+ // No row to lock yet, so two first deliveries can race here; the
+ // unique index settles it and both end up applied.
+ const [row] = await tx
+ .insert(scmChangeRequests)
+ .values({
+ ...snapshot,
+ ...linkValues,
+ ...eventValues,
+ ciHeadSha: params.headSha ?? null,
+ number: params.number,
+ provider: params.provider,
+ repoFullName: params.repoFullName,
+ userId: params.userId,
+ workspaceId: params.workspaceId ?? null,
+ })
+ .onConflictDoUpdate({
+ set: { ...snapshot, ...linkValues, ...eventValues, updatedAt: now },
+ target: [
+ scmChangeRequests.provider,
+ scmChangeRequests.repoFullName,
+ scmChangeRequests.number,
+ ],
+ })
+ .returning();
+
+ return row;
+ });
+
+ /** Fill in links that are still null. Never overwrites a link already set. */
+ static attachLinks = async (
+ db: LobeChatDatabase,
+ id: string,
+ links: ScmChangeRequestLinks,
+ ): Promise<ScmChangeRequestItem | null> => {
+ const existing = await ScmChangeRequestModel.findById(db, id);
+ if (!existing) return null;
+
+ const set: Partial<ScmChangeRequestLinks> = {};
+ for (const key of ['acceptanceId', 'installationId', 'taskId', 'topicId', 'workId'] as const) {
+ if (!existing[key] && links[key]) set[key] = links[key];
+ }
+ if (Object.keys(set).length === 0) return existing;
+
+ const [row] = await db
+ .update(scmChangeRequests)
+ .set({ ...set, updatedAt: new Date() })
+ .where(eq(scmChangeRequests.id, id))
+ .returning();
+ return row;
+ };
+
+ /**
+ * Merge check results for a commit into the row and recompute the rollup.
+ * Results for a commit other than the row's current head are stale (the
+ * agent already pushed again) and are dropped without touching the row.
+ */
+ static applyChecks = async (
+ db: LobeChatDatabase,
+ id: string,
+ params: ScmApplyChecksParams,
+ ): Promise<ScmApplyChecksResult<ScmChangeRequestItem> | null> =>
+ // Deliveries for the jobs of one commit arrive together and are handled
+ // concurrently; each merges its own check into the stored set, so the
+ // read and the write must not interleave or the last writer drops the
+ // others' checks. The row lock serialises them.
+ db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select()
+ .from(scmChangeRequests)
+ .where(eq(scmChangeRequests.id, id))
+ .for('update');
+ if (!existing) return null;
+
+ if (existing.headSha && existing.headSha !== params.headSha) {
+ // Not necessarily stale: GitHub can report a job for a commit before
+ // the `synchronize` that makes it the head. Hold the results against
+ // that commit β€” `upsert` adopts them when the head catches up, and a
+ // newer commit simply replaces the bucket.
+ const held = existing.metadata?.pendingChecks;
+ const pendingChecks = {
+ checks:
+ held?.sha === params.headSha ? mergeChecks(held.checks, params.checks) : params.checks,
+ sha: params.headSha,
+ };
+ const [row] = await tx
+ .update(scmChangeRequests)
+ .set({ metadata: { ...existing.metadata, pendingChecks }, updatedAt: new Date() })
+ .where(eq(scmChangeRequests.id, id))
+ .returning();
+
+ return {
+ applied: false,
+ ciStatus: existing.ciStatus,
+ previousCiStatus: existing.ciStatus,
+ row,
+ };
+ }
+
+ const sameCommit = existing.ciHeadSha === params.headSha;
+ const checks =
+ params.replace || !sameCommit ? params.checks : mergeChecks(existing.checks, params.checks);
+ const ciStatus = rollupCiStatus(checks);
+
+ const [row] = await tx
+ .update(scmChangeRequests)
+ .set({ checks, ciHeadSha: params.headSha, ciStatus, updatedAt: new Date() })
+ .where(eq(scmChangeRequests.id, id))
+ .returning();
+
+ return {
+ applied: true,
+ ciStatus,
+ previousCiStatus: sameCommit ? existing.ciStatus : null,
+ row,
+ };
+ });
+
+ /**
+ * Record one reviewer's verdict and recompute the change request's
+ * rollup. GitHub reports reviews per reviewer, not as an aggregate, so
+ * storing the newest event verbatim would let a later approval bury
+ * another reviewer's outstanding changes request (and the reverse, on a
+ * different delivery order). `decision: null` drops the reviewer, which
+ * is what a dismissal means.
+ */
+ static applyReviewerDecision = async (
+ db: LobeChatDatabase,
+ id: string,
+ params: {
+ at?: Date;
+ decision: 'approved' | 'changes_requested' | null;
+ /** Provider user id; without one the verdict cannot be attributed. */
+ reviewerId?: string | null;
+ },
+ ): Promise<{ applied: boolean; reviewDecision: ScmReviewDecision | null }> =>
+ db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select()
+ .from(scmChangeRequests)
+ .where(eq(scmChangeRequests.id, id))
+ .for('update');
+ if (!existing) return { applied: false, reviewDecision: null };
+
+ const reviewers = { ...existing.metadata?.reviewers };
+ let stale = false;
+ if (params.reviewerId) {
+ // Reviews are delivered per reviewer and can arrive out of order; an
+ // approval submitted after a changes-request must not be undone by
+ // the older event landing second.
+ const stored = reviewers[params.reviewerId];
+ const at = params.at ?? new Date();
+ const storedAt = stored?.at ? Date.parse(stored.at) : Number.NaN;
+ stale = !Number.isNaN(storedAt) && at.getTime() < storedAt;
+
+ if (stale) {
+ // nothing to apply: the stored verdict is the newer one
+ } else if (params.decision) {
+ reviewers[params.reviewerId] = { at: at.toISOString(), decision: params.decision };
+ } else delete reviewers[params.reviewerId];
+ }
+
+ const verdicts = Object.values(reviewers).map((entry) => entry.decision);
+ const reviewDecision: ScmReviewDecision | null = verdicts.includes('changes_requested')
+ ? 'changes_requested'
+ : verdicts.includes('approved')
+ ? 'approved'
+ : null;
+
+ if (stale) return { applied: false, reviewDecision: existing.reviewDecision };
+
+ await tx
+ .update(scmChangeRequests)
+ .set({
+ metadata: { ...existing.metadata, reviewers },
+ reviewDecision,
+ updatedAt: new Date(),
+ })
+ .where(eq(scmChangeRequests.id, id));
+ return { applied: true, reviewDecision };
+ });
+
+ static setReviewDecision = async (
+ db: LobeChatDatabase,
+ id: string,
+ reviewDecision: ScmReviewDecision | null,
+ ): Promise<void> => {
+ await db
+ .update(scmChangeRequests)
+ .set({ reviewDecision, updatedAt: new Date() })
+ .where(eq(scmChangeRequests.id, id));
+ };
+
+ static recordEvent = async (
+ db: LobeChatDatabase,
+ id: string,
+ kind: ScmChangeRequestEventKind,
+ at: Date = new Date(),
+ ): Promise<void> => {
+ await db
+ .update(scmChangeRequests)
+ .set({ lastEventAt: at, lastEventKind: kind, updatedAt: new Date() })
+ .where(eq(scmChangeRequests.id, id));
+ };
+
+ /** Bump the wake counter; returns the new count so the caller can enforce its cap. */
+ static recordWake = async (db: LobeChatDatabase, id: string): Promise<number> => {
+ const existing = await ScmChangeRequestModel.findById(db, id);
+ if (!existing) return 0;
+
+ const wakeCount = existing.wakeCount + 1;
+ await db
+ .update(scmChangeRequests)
+ .set({ lastWakeAt: new Date(), updatedAt: new Date(), wakeCount })
+ .where(eq(scmChangeRequests.id, id));
+ return wakeCount;
+ };
+}
diff --git a/packages/database/src/models/scm/delivery.ts b/packages/database/src/models/scm/delivery.ts
new file mode 100644
index 00000000000..fae09082a6e
--- /dev/null
+++ b/packages/database/src/models/scm/delivery.ts
@@ -0,0 +1,94 @@
+import type {
+ ScmClaimDeliveryParams,
+ ScmProvider,
+ ScmWebhookDeliveryStatus,
+} from '@lobechat/types';
+import { and, eq, lt, or } from 'drizzle-orm';
+
+import type { ScmWebhookDeliveryItem } from '../../schemas';
+import { scmWebhookDeliveries } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+/**
+ * The idempotency gate for inbound webhooks. `claim` inserts the delivery id
+ * before any handler runs; a delivery already applied returns `null` and the
+ * caller answers the provider with a no-op 200.
+ *
+ * "Already applied" means `processed` or `skipped` β€” those are settled. A
+ * `failed` row, or one stuck in `received` because the process died
+ * mid-flight, is *not* a duplicate: redelivering is how GitHub recovers a
+ * lost event, and refusing it would drop a merge for good.
+ */
+export class ScmWebhookDeliveryModel {
+ /** How long a `received` row may sit before a redelivery may take it over. */
+ static STALE_RECEIVED_MINUTES = 5;
+
+ static claim = async (
+ db: LobeChatDatabase,
+ params: ScmClaimDeliveryParams,
+ ): Promise<ScmWebhookDeliveryItem | null> => {
+ const values = {
+ action: params.action ?? null,
+ deliveryId: params.deliveryId,
+ event: params.event,
+ installationId: params.installationId ?? null,
+ number: params.number ?? null,
+ provider: params.provider,
+ repoFullName: params.repoFullName ?? null,
+ status: 'received' as const,
+ };
+ const staleBefore = new Date(
+ Date.now() - ScmWebhookDeliveryModel.STALE_RECEIVED_MINUTES * 60_000,
+ );
+
+ // The conflict update is the retry gate: it fires only for a row that is
+ // safe to re-run, so two concurrent redeliveries still produce one claim.
+ const [row] = await db
+ .insert(scmWebhookDeliveries)
+ .values(values)
+ .onConflictDoUpdate({
+ set: { error: null, processedAt: null, receivedAt: new Date(), status: 'received' },
+ target: [scmWebhookDeliveries.provider, scmWebhookDeliveries.deliveryId],
+ where: or(
+ eq(scmWebhookDeliveries.status, 'failed'),
+ and(
+ eq(scmWebhookDeliveries.status, 'received'),
+ lt(scmWebhookDeliveries.receivedAt, staleBefore),
+ ),
+ ),
+ })
+ .returning();
+
+ return row ?? null;
+ };
+
+ static settle = async (
+ db: LobeChatDatabase,
+ key: { deliveryId: string; provider: ScmProvider },
+ outcome: { error?: string | null; status: Exclude<ScmWebhookDeliveryStatus, 'received'> },
+ ): Promise<void> => {
+ await db
+ .update(scmWebhookDeliveries)
+ .set({ error: outcome.error ?? null, processedAt: new Date(), status: outcome.status })
+ .where(
+ and(
+ eq(scmWebhookDeliveries.provider, key.provider),
+ eq(scmWebhookDeliveries.deliveryId, key.deliveryId),
+ ),
+ );
+ };
+
+ /** How long a settled delivery stays on the ledger before the sweep drops it. */
+ static RETENTION_DAYS = 30;
+
+ /** Retention sweep: drop rows older than the given instant. Returns the count removed. */
+
+ static pruneBefore = async (db: LobeChatDatabase, before: Date): Promise<number> => {
+ const rows = await db
+ .delete(scmWebhookDeliveries)
+ .where(lt(scmWebhookDeliveries.receivedAt, before))
+ .returning({ deliveryId: scmWebhookDeliveries.deliveryId });
+
+ return rows.length;
+ };
+}
diff --git a/packages/database/src/models/scm/identity.ts b/packages/database/src/models/scm/identity.ts
new file mode 100644
index 00000000000..855a7150e30
--- /dev/null
+++ b/packages/database/src/models/scm/identity.ts
@@ -0,0 +1,133 @@
+import type {
+ ScmDecryptedIdentity,
+ ScmIdentityCredentials,
+ ScmProvider,
+ ScmUpsertIdentityParams,
+} from '@lobechat/types';
+import { and, eq } from 'drizzle-orm';
+
+import type { ScmIdentityItem } from '../../schemas';
+import { scmIdentities } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+interface GateKeeper {
+ decrypt: (ciphertext: string) => Promise<{ plaintext: string }>;
+ encrypt: (plaintext: string) => Promise<string>;
+}
+
+/**
+ * CRUD for `scm_identities`: which provider account a LobeHub user is. The
+ * identity is written by the install callback and read when a provider actor
+ * (merger, reviewer) needs to resolve to a LobeHub user.
+ */
+export class ScmIdentityModel {
+ static findByExternalUser = async (
+ db: LobeChatDatabase,
+ provider: ScmProvider,
+ externalUserId: string,
+ ): Promise<ScmIdentityItem | null> => {
+ const [row] = await db
+ .select()
+ .from(scmIdentities)
+ .where(
+ and(eq(scmIdentities.provider, provider), eq(scmIdentities.externalUserId, externalUserId)),
+ )
+ .limit(1);
+
+ return row ?? null;
+ };
+
+ static findByUser = async (
+ db: LobeChatDatabase,
+ provider: ScmProvider,
+ userId: string,
+ gateKeeper?: GateKeeper,
+ ): Promise<ScmDecryptedIdentity<ScmIdentityItem> | null> => {
+ const [row] = await db
+ .select()
+ .from(scmIdentities)
+ .where(and(eq(scmIdentities.provider, provider), eq(scmIdentities.userId, userId)))
+ .limit(1);
+
+ if (!row) return null;
+ return decryptRow(row, gateKeeper);
+ };
+
+ /**
+ * Bind a provider account to a LobeHub user. The provider account is the
+ * identity: re-authorizing from the same account updates the row in place
+ * (fresh token, possibly a new login after a rename). A provider account
+ * already bound to a *different* LobeHub user is a conflict the caller
+ * must surface, so the unique index is left to throw.
+ */
+ static upsert = async (
+ db: LobeChatDatabase,
+ params: ScmUpsertIdentityParams,
+ gateKeeper?: GateKeeper,
+ ): Promise<ScmIdentityItem> => {
+ const encrypted =
+ params.credentials === undefined
+ ? undefined
+ : params.credentials === null
+ ? null
+ : await encryptCredentials(params.credentials, gateKeeper);
+
+ const values = {
+ externalLogin: params.externalLogin,
+ externalUserId: params.externalUserId,
+ metadata: params.metadata ?? {},
+ provider: params.provider,
+ tokenExpiresAt: params.tokenExpiresAt ?? null,
+ userId: params.userId,
+ ...(encrypted === undefined ? {} : { credentials: encrypted }),
+ };
+
+ // The conflict target is the provider account, which is global: without
+ // the `where` an authorization from a second LobeHub account would
+ // rewrite `userId` and hand over the stored token. Restricting the
+ // update to the current owner turns that case into zero rows, which the
+ // callback reports as `identity_taken`.
+ const [row] = await db
+ .insert(scmIdentities)
+ .values(values)
+ .onConflictDoUpdate({
+ set: { ...values, updatedAt: new Date() },
+ target: [scmIdentities.provider, scmIdentities.externalUserId],
+ where: eq(scmIdentities.userId, params.userId),
+ })
+ .returning();
+
+ if (!row) {
+ throw new Error(
+ `scm identity ${params.provider}:${params.externalUserId} belongs to another user`,
+ );
+ }
+
+ return row;
+ };
+}
+
+const encryptCredentials = async (
+ credentials: ScmIdentityCredentials,
+ gateKeeper?: GateKeeper,
+): Promise<string> => {
+ const plaintext = JSON.stringify(credentials);
+ return gateKeeper ? gateKeeper.encrypt(plaintext) : plaintext;
+};
+
+const decryptRow = async (
+ row: ScmIdentityItem,
+ gateKeeper?: GateKeeper,
+): Promise<ScmDecryptedIdentity<ScmIdentityItem>> => {
+ if (!row.credentials) return { ...row, credentials: null };
+
+ const plaintext = gateKeeper
+ ? (await gateKeeper.decrypt(row.credentials)).plaintext
+ : row.credentials;
+
+ try {
+ return { ...row, credentials: JSON.parse(plaintext) as ScmIdentityCredentials };
+ } catch {
+ return { ...row, credentials: null };
+ }
+};
diff --git a/packages/database/src/models/scm/index.ts b/packages/database/src/models/scm/index.ts
new file mode 100644
index 00000000000..2db94f0254f
--- /dev/null
+++ b/packages/database/src/models/scm/index.ts
@@ -0,0 +1,4 @@
+export * from './changeRequest';
+export * from './delivery';
+export * from './identity';
+export * from './installation';
diff --git a/packages/database/src/models/scm/installation.ts b/packages/database/src/models/scm/installation.ts
new file mode 100644
index 00000000000..54c7fb20470
--- /dev/null
+++ b/packages/database/src/models/scm/installation.ts
@@ -0,0 +1,189 @@
+import type {
+ ScmBindInstallationParams,
+ ScmInstallationRepository,
+ ScmInstallationSnapshot,
+ ScmProvider,
+} from '@lobechat/types';
+import { and, desc, eq, isNull, ne } from 'drizzle-orm';
+
+import type { ScmInstallationItem } from '../../schemas';
+import { scmInstallations } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+/**
+ * CRUD for `scm_installations`. Callers are server-side (webhook ingest, the
+ * install callback), so the model exposes static methods taking the db; the
+ * row's `user_id` / `workspace_id` is the scope the installation binds to,
+ * not the caller's identity.
+ */
+export class ScmInstallationModel {
+ static findByProviderInstallationId = async (
+ db: LobeChatDatabase,
+ provider: ScmProvider,
+ installationId: string,
+ ): Promise<ScmInstallationItem | null> => {
+ const [row] = await db
+ .select()
+ .from(scmInstallations)
+ .where(
+ and(
+ eq(scmInstallations.provider, provider),
+ eq(scmInstallations.installationId, installationId),
+ ),
+ )
+ .limit(1);
+
+ return row ?? null;
+ };
+
+ static findById = async (
+ db: LobeChatDatabase,
+ id: string,
+ ): Promise<ScmInstallationItem | null> => {
+ const [row] = await db.select().from(scmInstallations).where(eq(scmInstallations.id, id));
+ return row ?? null;
+ };
+
+ /** Active installations visible to a scope: the workspace's, or the user's personal ones. */
+ static listByScope = async (
+ db: LobeChatDatabase,
+ scope: { userId: string; workspaceId?: string | null },
+ ): Promise<ScmInstallationItem[]> => {
+ const scopeCondition = scope.workspaceId
+ ? eq(scmInstallations.workspaceId, scope.workspaceId)
+ : and(eq(scmInstallations.userId, scope.userId), isNull(scmInstallations.workspaceId));
+
+ return db
+ .select()
+ .from(scmInstallations)
+ .where(and(scopeCondition, isNull(scmInstallations.revokedAt)))
+ .orderBy(desc(scmInstallations.createdAt));
+ };
+
+ /**
+ * Create or refresh the row for an installation the user just connected.
+ * Re-binding an existing installation keeps its id (change requests point
+ * at it) but moves it to the new scope and clears any revocation β€” a user
+ * who uninstalls and reinstalls gets the same GitHub installation id back.
+ */
+ static bind = async (
+ db: LobeChatDatabase,
+ params: ScmBindInstallationParams,
+ ): Promise<ScmInstallationItem> => {
+ const values = {
+ accountExternalId: params.accountExternalId,
+ accountLogin: params.accountLogin,
+ accountType: params.accountType,
+ installationId: params.installationId,
+ installedByExternalLogin: params.installedByExternalLogin ?? null,
+ installedByExternalUserId: params.installedByExternalUserId ?? null,
+ metadata: params.metadata ?? {},
+ provider: params.provider,
+ repositories: params.repositories ?? [],
+ repositorySelection: params.repositorySelection,
+ revokedAt: null,
+ suspendedAt: params.suspendedAt ?? null,
+ userId: params.userId,
+ workspaceId: params.workspaceId ?? null,
+ };
+
+ const [row] = await db
+ .insert(scmInstallations)
+ .values(values)
+ .onConflictDoUpdate({
+ set: { ...values, updatedAt: new Date() },
+ target: [scmInstallations.provider, scmInstallations.installationId],
+ })
+ .returning();
+
+ // A provider account holds one installation of the app at a time, so any
+ // other live row for the same account is a stale one (uninstalled and
+ // reinstalled under a new id, or a missed `installation.deleted`): retire
+ // it rather than list the account twice.
+ await db
+ .update(scmInstallations)
+ .set({ revokedAt: new Date(), updatedAt: new Date() })
+ .where(
+ and(
+ eq(scmInstallations.provider, params.provider),
+ eq(scmInstallations.accountExternalId, params.accountExternalId),
+ ne(scmInstallations.id, row.id),
+ isNull(scmInstallations.revokedAt),
+ ),
+ );
+
+ return row;
+ };
+
+ /** Refresh provider facts on an existing row without touching its scope binding. */
+ static refreshSnapshot = async (
+ db: LobeChatDatabase,
+ id: string,
+ snapshot: Partial<Omit<ScmInstallationSnapshot, 'installationId' | 'provider'>>,
+ ): Promise<void> => {
+ await db
+ .update(scmInstallations)
+ .set({ ...snapshot, updatedAt: new Date() })
+ .where(eq(scmInstallations.id, id));
+ };
+
+ static setRepositories = async (
+ db: LobeChatDatabase,
+ id: string,
+ repositories: ScmInstallationRepository[],
+ ): Promise<void> => {
+ await db
+ .update(scmInstallations)
+ .set({ repositories, updatedAt: new Date() })
+ .where(eq(scmInstallations.id, id));
+ };
+
+ /**
+ * Apply a repository grant change. Adds and removes for one installation
+ * arrive as separate deliveries and are handled concurrently, so the
+ * read/merge/write runs under a row lock β€” otherwise two handlers start
+ * from the same snapshot and the last write drops the other's change.
+ */
+ static applyRepositoryChange = async (
+ db: LobeChatDatabase,
+ id: string,
+ change: { added: ScmInstallationRepository[]; removed: ScmInstallationRepository[] },
+ ): Promise<ScmInstallationRepository[]> =>
+ db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select()
+ .from(scmInstallations)
+ .where(eq(scmInstallations.id, id))
+ .for('update');
+ if (!existing) return [];
+
+ const removed = new Set(change.removed.map((r) => r.externalId));
+ const kept = existing.repositories.filter((r) => !removed.has(r.externalId));
+ const known = new Set(kept.map((r) => r.externalId));
+ const next = [...kept, ...change.added.filter((r) => !known.has(r.externalId))];
+
+ await tx
+ .update(scmInstallations)
+ .set({ repositories: next, updatedAt: new Date() })
+ .where(eq(scmInstallations.id, id));
+ return next;
+ });
+
+ static setSuspended = async (
+ db: LobeChatDatabase,
+ id: string,
+ suspended: boolean,
+ ): Promise<void> => {
+ await db
+ .update(scmInstallations)
+ .set({ suspendedAt: suspended ? new Date() : null, updatedAt: new Date() })
+ .where(eq(scmInstallations.id, id));
+ };
+
+ static markRevoked = async (db: LobeChatDatabase, id: string): Promise<void> => {
+ await db
+ .update(scmInstallations)
+ .set({ revokedAt: new Date(), updatedAt: new Date() })
+ .where(eq(scmInstallations.id, id));
+ };
+}
diff --git a/packages/env/src/__tests__/scm.test.ts b/packages/env/src/__tests__/scm.test.ts
new file mode 100644
index 00000000000..e212d1c1b49
--- /dev/null
+++ b/packages/env/src/__tests__/scm.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { decodeGitHubAppPrivateKey, getScmConfig } from '../scm';
+
+const PEM = '-----BEGIN RSA PRIVATE KEY-----\nabc\n-----END RSA PRIVATE KEY-----';
+
+describe('decodeGitHubAppPrivateKey', () => {
+ it('passes a raw PEM through', () => {
+ expect(decodeGitHubAppPrivateKey(` ${PEM}\n`)).toBe(PEM);
+ });
+
+ it('decodes a base64-wrapped PEM', () => {
+ expect(decodeGitHubAppPrivateKey(Buffer.from(PEM).toString('base64'))).toBe(PEM);
+ });
+
+ it('rejects values that decode to something other than a PEM', () => {
+ expect(decodeGitHubAppPrivateKey(Buffer.from('not a key').toString('base64'))).toBeUndefined();
+ expect(decodeGitHubAppPrivateKey('')).toBeUndefined();
+ expect(decodeGitHubAppPrivateKey(undefined)).toBeUndefined();
+ });
+});
+
+describe('getScmConfig', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('is disabled until every install-flow value is present', () => {
+ vi.stubEnv('GITHUB_APP_ID', '1');
+ vi.stubEnv('GITHUB_APP_PRIVATE_KEY', PEM);
+ vi.stubEnv('GITHUB_APP_WEBHOOK_SECRET', 's');
+ vi.stubEnv('GITHUB_APP_SLUG', '');
+ expect(getScmConfig().ENABLED_GITHUB_APP).toBe(false);
+
+ vi.stubEnv('GITHUB_APP_SLUG', 'lobehub');
+ const env = getScmConfig();
+ expect(env.ENABLED_GITHUB_APP).toBe(true);
+ expect(env.GITHUB_APP_PRIVATE_KEY).toBe(PEM);
+ });
+
+ it('reports identity linking as its own capability', () => {
+ vi.stubEnv('GITHUB_APP_ID', '1');
+ vi.stubEnv('GITHUB_APP_PRIVATE_KEY', PEM);
+ vi.stubEnv('GITHUB_APP_WEBHOOK_SECRET', 's');
+ vi.stubEnv('GITHUB_APP_SLUG', 'lobehub');
+
+ // Webhooks and installs work without OAuth credentials; only the
+ // identity link needs them, so the two flags move independently.
+ expect(getScmConfig().ENABLED_GITHUB_APP_OAUTH).toBe(false);
+
+ vi.stubEnv('GITHUB_APP_CLIENT_ID', 'Iv23');
+ expect(getScmConfig().ENABLED_GITHUB_APP_OAUTH).toBe(false);
+
+ vi.stubEnv('GITHUB_APP_CLIENT_SECRET', 'secret');
+ const env = getScmConfig();
+ expect(env.ENABLED_GITHUB_APP).toBe(true);
+ expect(env.ENABLED_GITHUB_APP_OAUTH).toBe(true);
+ });
+});
diff --git a/packages/env/src/scm.ts b/packages/env/src/scm.ts
new file mode 100644
index 00000000000..cb5cc7cc672
--- /dev/null
+++ b/packages/env/src/scm.ts
@@ -0,0 +1,86 @@
+import { createEnv } from '@t3-oss/env-core';
+import { z } from 'zod';
+
+declare global {
+ // eslint-disable-next-line @typescript-eslint/no-namespace
+ namespace NodeJS {
+ interface ProcessEnv {
+ /** GitHub App client id (`Ov23…`), used for the user-authorization leg of the install flow. */
+ GITHUB_APP_CLIENT_ID?: string;
+ GITHUB_APP_CLIENT_SECRET?: string;
+ /** Numeric App ID from the GitHub App settings page. */
+ GITHUB_APP_ID?: string;
+ /**
+ * App private key. Either the raw PEM (newlines intact) or the PEM
+ * base64-encoded once so it survives single-line env files.
+ */
+ GITHUB_APP_PRIVATE_KEY?: string;
+ /** URL slug of the app (`github.com/apps/<slug>`); drives the install redirect. */
+ GITHUB_APP_SLUG?: string;
+ /** Shared secret GitHub signs webhook deliveries with. */
+ GITHUB_APP_WEBHOOK_SECRET?: string;
+ }
+ }
+}
+
+const PEM_HEADER = '-----BEGIN';
+
+/**
+ * Accept the private key as raw PEM or as a base64 blob of the PEM. Operators
+ * paste multi-line PEMs into single-line env stores often enough that the
+ * base64 form is the documented one; the raw form is kept so a `.env` with
+ * a quoted multi-line value keeps working.
+ */
+export const decodeGitHubAppPrivateKey = (value?: string): string | undefined => {
+ if (!value) return undefined;
+ const trimmed = value.trim();
+ if (trimmed.startsWith(PEM_HEADER)) return trimmed;
+
+ try {
+ const decoded = Buffer.from(trimmed, 'base64').toString('utf8').trim();
+ return decoded.startsWith(PEM_HEADER) ? decoded : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+export const getScmConfig = () => {
+ const privateKey = decodeGitHubAppPrivateKey(process.env.GITHUB_APP_PRIVATE_KEY);
+
+ return createEnv({
+ runtimeEnv: {
+ ENABLED_GITHUB_APP:
+ !!process.env.GITHUB_APP_ID &&
+ !!privateKey &&
+ !!process.env.GITHUB_APP_WEBHOOK_SECRET &&
+ !!process.env.GITHUB_APP_SLUG,
+ ENABLED_GITHUB_APP_OAUTH:
+ !!process.env.GITHUB_APP_CLIENT_ID && !!process.env.GITHUB_APP_CLIENT_SECRET,
+ GITHUB_APP_CLIENT_ID: process.env.GITHUB_APP_CLIENT_ID,
+ GITHUB_APP_CLIENT_SECRET: process.env.GITHUB_APP_CLIENT_SECRET,
+ GITHUB_APP_ID: process.env.GITHUB_APP_ID,
+ GITHUB_APP_PRIVATE_KEY: privateKey,
+ GITHUB_APP_SLUG: process.env.GITHUB_APP_SLUG,
+ GITHUB_APP_WEBHOOK_SECRET: process.env.GITHUB_APP_WEBHOOK_SECRET,
+ },
+ server: {
+ /** True when every value the webhook + install flow needs is present. */
+ ENABLED_GITHUB_APP: z.boolean(),
+ /**
+ * True when the App can also exchange the install `code` for a user
+ * token. Identity linking is a separate capability: an App without
+ * OAuth credentials still receives webhooks and binds installations,
+ * it just cannot say which GitHub user connected it.
+ */
+ ENABLED_GITHUB_APP_OAUTH: z.boolean(),
+ GITHUB_APP_CLIENT_ID: z.string().optional(),
+ GITHUB_APP_CLIENT_SECRET: z.string().optional(),
+ GITHUB_APP_ID: z.string().optional(),
+ GITHUB_APP_PRIVATE_KEY: z.string().optional(),
+ GITHUB_APP_SLUG: z.string().optional(),
+ GITHUB_APP_WEBHOOK_SECRET: z.string().optional(),
+ },
+ });
+};
+
+export const scmEnv = getScmConfig();
diff --git a/packages/types/src/scm.ts b/packages/types/src/scm.ts
index 34e562d43e2..a64e659aa95 100644
--- a/packages/types/src/scm.ts
+++ b/packages/types/src/scm.ts
@@ -60,11 +60,24 @@ export type ScmReviewDecision = 'approved' | 'changes_requested' | 'review_requi
/** Outcome of one CI check on the current head commit. */
export interface ScmCheck {
+ /**
+ * Provider app that published the check. Two apps may report the same
+ * name for one commit, so the source is part of a check's identity β€”
+ * without it a passing `Test` from one app would erase a failing `Test`
+ * from another and turn the rollup green.
+ */
+ appId?: string;
completedAt?: string;
/** Provider conclusion, e.g. `success` | `failure` | `cancelled` | `skipped`. */
conclusion?: string;
externalId: string;
name: string;
+ /**
+ * Provider-clock time this result was reported. Check runs and legacy
+ * statuses reuse their external id as they transition, so deliveries that
+ * arrive out of order are ordered by this rather than by arrival.
+ */
+ reportedAt?: string;
startedAt?: string;
/** Provider status, e.g. `queued` | `in_progress` | `completed`. */
status: string;
@@ -88,6 +101,7 @@ export type ScmChangeRequestEventKind =
| 'review_approved'
| 'review_changes_requested'
| 'review_commented'
+ | 'review_dismissed'
| 'synchronized';
/** Open bag for change-request facts the columns do not model. */
@@ -95,9 +109,145 @@ export interface ScmChangeRequestMetadata {
[key: string]: unknown;
/** Acceptance links parsed out of the change request body. */
acceptanceIdsFromBody?: string[];
+ /**
+ * Provider-clock timestamp of the newest change-request event applied.
+ * Kept apart from the `lastEventAt` column, which also records events we
+ * time with our own clock (check results), so ordering only ever compares
+ * two provider timestamps.
+ */
+ lastProviderEventAt?: string;
/** Provider's mergeability verdict, when it exposes one (`MERGEABLE`, `CONFLICTING`, …). */
mergeable?: string;
+ /**
+ * Check results for a commit that is not the head yet. GitHub can report
+ * a job before the `synchronize` that moves the pull request onto its
+ * commit; holding them here keeps the push from landing with an empty CI
+ * rollup when that job never reports again.
+ */
+ pendingChecks?: { checks: ScmCheck[]; sha: string };
+ /**
+ * Latest effective verdict per reviewer, keyed by provider user id. The
+ * change request's `reviewDecision` is the rollup of these: one
+ * outstanding "changes requested" outweighs any number of approvals,
+ * whatever order the deliveries arrive in.
+ */
+ reviewers?: Record<string, { at?: string; decision: 'approved' | 'changes_requested' }>;
}
/** Processing state of one inbound webhook delivery. */
export type ScmWebhookDeliveryStatus = 'failed' | 'processed' | 'received' | 'skipped';
+
+// ---------------------------------------------------------------------------
+// Model contracts: the write shapes the SCM models accept and the read shapes
+// they return. Row types (`ScmChangeRequestItem`, …) come from the database
+// schema, so the results that carry a row are generic over it.
+// ---------------------------------------------------------------------------
+
+/** Provider facts about a change request, as a normalizer produces them from one event. */
+export interface ScmChangeRequestSnapshot {
+ authorExternalId?: string | null;
+ authorExternalLogin?: string | null;
+ baseRef?: string | null;
+ closedAt?: Date | null;
+ externalId?: string | null;
+ headRef?: string | null;
+ headSha?: string | null;
+ isDraft?: boolean;
+ mergedAt?: Date | null;
+ mergedByExternalId?: string | null;
+ mergeStateStatus?: string | null;
+ metadata?: ScmChangeRequestMetadata;
+ number: number;
+ provider: ScmProvider;
+ repoExternalId?: string | null;
+ repoFullName: string;
+ state: ScmChangeRequestState;
+ title?: string | null;
+ url: string;
+}
+
+/** The LobeHub records a change request is tied to. Only ever filled in, never cleared. */
+export interface ScmChangeRequestLinks {
+ acceptanceId?: string | null;
+ installationId?: string | null;
+ taskId?: string | null;
+ topicId?: string | null;
+ workId?: string | null;
+}
+
+export interface ScmUpsertChangeRequestParams extends ScmChangeRequestSnapshot {
+ eventAt?: Date;
+ eventKind?: ScmChangeRequestEventKind;
+ links?: ScmChangeRequestLinks;
+ userId: string;
+ workspaceId?: string | null;
+}
+
+export interface ScmApplyChecksParams {
+ checks: ScmCheck[];
+ /** Commit the checks describe; a mismatch with the row's head is dropped as stale. */
+ headSha: string;
+ /** When true, `checks` replaces the stored set instead of merging by id. */
+ replace?: boolean;
+}
+
+export interface ScmApplyChecksResult<TRow> {
+ applied: boolean;
+ ciStatus: ScmCiStatus | null;
+ previousCiStatus: ScmCiStatus | null;
+ row: TRow;
+}
+
+/** Provider facts about an installation, from a webhook or the installations API. */
+export interface ScmInstallationSnapshot {
+ accountExternalId: string;
+ accountLogin: string;
+ accountType: ScmInstallationAccountType;
+ installationId: string;
+ metadata?: ScmInstallationMetadata;
+ provider: ScmProvider;
+ repositories?: ScmInstallationRepository[];
+ repositorySelection: ScmRepositorySelection;
+ suspendedAt?: Date | null;
+}
+
+export interface ScmBindInstallationParams extends ScmInstallationSnapshot {
+ installedByExternalLogin?: string | null;
+ installedByExternalUserId?: string | null;
+ userId: string;
+ workspaceId?: string | null;
+}
+
+/** Plaintext user-to-server credentials; stored encrypted, never returned to a client. */
+export interface ScmIdentityCredentials {
+ accessToken: string;
+ refreshToken?: string;
+ refreshTokenExpiresAt?: string;
+}
+
+export interface ScmUpsertIdentityParams {
+ /** Plaintext credentials; encrypted before writing. Omit to keep the stored ones. */
+ credentials?: ScmIdentityCredentials | null;
+ externalLogin: string;
+ externalUserId: string;
+ metadata?: ScmIdentityMetadata;
+ provider: ScmProvider;
+ tokenExpiresAt?: Date | null;
+ userId: string;
+}
+
+/** An identity row with its credential column decrypted. */
+export type ScmDecryptedIdentity<TItem extends { credentials: unknown }> = Omit<
+ TItem,
+ 'credentials'
+> & { credentials: ScmIdentityCredentials | null };
+
+export interface ScmClaimDeliveryParams {
+ action?: string | null;
+ deliveryId: string;
+ event: string;
+ installationId?: string | null;
+ number?: number | null;
+ provider: ScmProvider;
+ repoFullName?: string | null;
+}
diff --git a/src/app/(backend)/api/webhooks/[[...route]]/route.ts b/src/app/(backend)/api/webhooks/[[...route]]/route.ts
index 738e7607348..151d6ba668e 100644
--- a/src/app/(backend)/api/webhooks/[[...route]]/route.ts
+++ b/src/app/(backend)/api/webhooks/[[...route]]/route.ts
@@ -1,3 +1,4 @@
import app from '@/server/router-hono/webhooks';
+export const GET = (request: Request) => app.fetch(request);
export const POST = (request: Request) => app.fetch(request);