Skip to content

TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.

fix: integration nonce

Nikolai Gimanb75a68d8082a
diff --git a/api/src/tv-modules/auth/AuthModel.ts b/api/src/tv-modules/auth/AuthModel.ts
index bbb3832..eec20fa 100644
--- a/api/src/tv-modules/auth/AuthModel.ts
+++ b/api/src/tv-modules/auth/AuthModel.ts
@@ -63,8 +63,8 @@ export default class AuthModel {
}
$logger.debug('User registration error');
return false;
- } catch (_error: any) {
- $logger.error('Can not inser user into DB');
+ } catch (error: any) {
+ $logger.error({ err: error, login, email }, 'Can not insert user into DB');
return false;
}
}
diff --git a/api/src/tv-modules/auth/__tests__/AuthModel.spec.ts b/api/src/tv-modules/auth/__tests__/AuthModel.spec.ts
index ddc4ccd..ff803b1 100644
--- a/api/src/tv-modules/auth/__tests__/AuthModel.spec.ts
+++ b/api/src/tv-modules/auth/__tests__/AuthModel.spec.ts
@@ -5,14 +5,18 @@ import AuthModel from '../AuthModel';
describe('AuthModel Integration Tests', () => {
let authModel: AuthModel;
- let emailNum: number;
+ let emailNum: string;
const prefixes: string[] = [];
+ let testIndex = 0;
beforeEach(async () => {
authModel = new AuthModel();
- emailNum = Date.now();
- prefixes.push(String(emailNum));
+ // Date.now() alone is not unique: on a local database a whole test fits
+ // into one millisecond, and two consecutive tests then insert the same
+ // email and trip the unique constraint. The counter keeps them apart.
+ emailNum = `${Date.now()}${String(testIndex++).padStart(2, '0')}`;
+ prefixes.push(emailNum);
});
afterAll(async () => {
diff --git a/api/src/tv-modules/integrations/IntegrationsController.ts b/api/src/tv-modules/integrations/IntegrationsController.ts
index df2eb39..33324b3 100644
--- a/api/src/tv-modules/integrations/IntegrationsController.ts
+++ b/api/src/tv-modules/integrations/IntegrationsController.ts
@@ -5,11 +5,35 @@ import { $logger } from '../../modules/logget';
import { integrationsDebugLog } from './debugLog';
import { decrypt } from '../../utils/crypto';
import AuthController from '../auth/AuthController';
+import { AppUser } from '../../core/AppUser';
+import { GoalPermissions } from '../../types/auth.types';
+import { randomToken } from '../oauth/oauth.utils';
import { IntegrationsRepository } from './IntegrationsRepository';
import { verifyGitHubWebhookSignature, GITHUB_BASE_URL } from './providers/github.provider';
import { verifyGitLabWebhookToken, GITLAB_BASE_URL } from './providers/gitlab.provider';
import { verifyGiteaWebhookSignature, GITEA_BASE_URL } from './providers/gitea.provider';
-import { IntegrationsArkTypeAdd, IntegrationsArkTypeDelete, IntegrationsArkTypeFetch, IntegrationsArkTypeSelectRepo, IntegrationsArkTypeToggle } from './types';
+import {
+ INTEGRATIONS_OAUTH_NONCE_COOKIE,
+ INTEGRATIONS_OAUTH_NONCE_PATH,
+ INTEGRATIONS_OAUTH_STATE_TTL_SECONDS,
+ IntegrationProviderArkType,
+ type AppUserFromIdArgs,
+ type CanManageIntegrationsArgs,
+ IntegrationsArkTypeAdd,
+ IntegrationsArkTypeDelete,
+ IntegrationsArkTypeFetch,
+ IntegrationsArkTypeSelectRepo,
+ IntegrationsArkTypeToggle,
+} from './types';
+
+// The cookie must survive the top-level redirect back from the provider, hence
+// SameSite=Lax rather than Strict; it is never needed outside the two OAuth routes.
+const NONCE_COOKIE_OPTIONS = {
+ httpOnly: true,
+ secure: true,
+ sameSite: 'lax' as const,
+ path: INTEGRATIONS_OAUTH_NONCE_PATH,
+};
export default class IntegrationsController {
createIntegration = async (req: Request, res: Response) => {
@@ -62,13 +86,33 @@ export default class IntegrationsController {
return res.status(401).send('Invalid token');
}
- const provider = req.params.provider;
+ const provider = IntegrationProviderArkType(req.params.provider);
+ if (provider instanceof type.errors) {
+ return res.status(400).send(provider.summary);
+ }
const projectId = Number(req.query.projectId);
if (!projectId || isNaN(projectId)) {
integrationsDebugLog({ step: 'initiate:reject', data: 'projectId is required' });
return res.status(400).send('projectId is required');
}
- const url = req.appUser.integrationsManager.getOAuthUrl(provider, projectId, userPayload.userData.id);
+
+ const initiator = new AppUser(userPayload);
+ if (!(await this.canManageIntegrations({ user: initiator, projectId }))) {
+ integrationsDebugLog({ step: 'initiate:reject', data: 'no permission for project' });
+ return res.status(403).end();
+ }
+
+ const nonce = randomToken();
+ res.cookie(INTEGRATIONS_OAUTH_NONCE_COOKIE, nonce, {
+ ...NONCE_COOKIE_OPTIONS,
+ maxAge: INTEGRATIONS_OAUTH_STATE_TTL_SECONDS * 1000,
+ });
+ const url = req.appUser.integrationsManager.getOAuthUrl({
+ provider,
+ projectId,
+ userId: userPayload.userData.id,
+ nonce,
+ });
integrationsDebugLog({ step: 'initiate:redirect', data: { userId: userPayload.userData.id, url } });
return res.redirect(url);
} catch (err: any) {
@@ -80,17 +124,31 @@ export default class IntegrationsController {
handleOAuthCallback = async (req: Request, res: Response) => {
try {
- const provider = req.params.provider;
+ const provider = IntegrationProviderArkType(req.params.provider);
+ if (provider instanceof type.errors) {
+ return res.redirect(`${process.env.APP_URL}?oauth=error`);
+ }
const code = req.query.code as string;
const state = req.query.state as string;
integrationsDebugLog({ step: 'callback:start', data: { provider, hasCode: !!code, hasState: !!state, queryKeys: Object.keys(req.query) } });
+ const nonce = req.cookies?.[INTEGRATIONS_OAUTH_NONCE_COOKIE] as string | undefined;
+ res.clearCookie(INTEGRATIONS_OAUTH_NONCE_COOKIE, NONCE_COOKIE_OPTIONS);
+
if (!code || !state) {
integrationsDebugLog({ step: 'callback:reject', data: 'missing code or state' });
return res.redirect(`${process.env.APP_URL}?oauth=error`);
}
- const { projectId, orgSlug } = await req.appUser.integrationsManager.handleOAuthCallback(provider, code, state);
+ const payload = req.appUser.integrationsManager.verifyOAuthState({ provider, state, nonce });
+
+ const initiator = await this.appUserFromId({ req, userId: payload.userId });
+ if (!initiator || !(await this.canManageIntegrations({ user: initiator, projectId: payload.projectId }))) {
+ integrationsDebugLog({ step: 'callback:reject', data: 'initiator may not manage the project' });
+ return res.redirect(`${process.env.APP_URL}?oauth=error`);
+ }
+
+ const { projectId, orgSlug } = await req.appUser.integrationsManager.completeOAuthCallback({ provider, code, payload });
integrationsDebugLog({ step: 'callback:success', data: { projectId, orgSlug } });
return res.redirect(`${process.env.APP_URL}/${orgSlug}/${projectId}/integrations?oauth=success`);
} catch (err: any) {
@@ -117,6 +175,19 @@ export default class IntegrationsController {
}
};
+ private async canManageIntegrations(args: CanManageIntegrationsArgs): Promise<boolean> {
+ const checker = await args.user.permissionsFetcher.getCheckerForGoal(args.projectId);
+ return checker.hasPermissions(GoalPermissions.INTEGRATIONS_CAN_MANAGE);
+ }
+
+ private async appUserFromId(args: AppUserFromIdArgs): Promise<AppUser | null> {
+ const userData = await args.req.appUser.authManager.repository.fetchUserById(args.userId);
+ if (!userData || userData.block !== 0) return null;
+ const user = new AppUser({ id: 0, userData: { id: userData.id, login: userData.login, email: userData.email } });
+ user.setUserDataFromDb(userData);
+ return user;
+ }
+
fetchRepos = async (req: Request, res: Response) => {
try {
const integrationId = Number(req.query.integrationId);
diff --git a/api/src/tv-modules/integrations/IntegrationsManager.ts b/api/src/tv-modules/integrations/IntegrationsManager.ts
index cee070b..b4075df 100644
--- a/api/src/tv-modules/integrations/IntegrationsManager.ts
+++ b/api/src/tv-modules/integrations/IntegrationsManager.ts
@@ -8,8 +8,22 @@ import { $logger } from '../../modules/logget';
import { IntegrationsRepository } from './IntegrationsRepository';
import { TasksRepository } from '../tasks/TasksRepository';
import type { IntegrationsSchemaTypeForSelect } from 'taskview-db-schemas';
-import type { IntegrationProvider, IntegrationsArgAdd, IntegrationsArgDelete, IntegrationsArgFetch, IntegrationsArgSelectRepo, IntegrationsArgToggle, OAuthStatePayload, RepoItemForClient } from './types';
+import {
+ INTEGRATIONS_OAUTH_STATE_TTL_SECONDS,
+ type CompleteOAuthCallbackArgs,
+ type GetOAuthUrlArgs,
+ type IntegrationProvider,
+ type IntegrationsArgAdd,
+ type IntegrationsArgDelete,
+ type IntegrationsArgFetch,
+ type IntegrationsArgSelectRepo,
+ type IntegrationsArgToggle,
+ type OAuthStatePayload,
+ type RepoItemForClient,
+ type VerifyOAuthStateArgs,
+} from './types';
import { randomBytes } from 'crypto';
+import { safeCompareHex, sha256Hex } from '../oauth/oauth.utils';
import { getGitHubOAuthUrl, exchangeGitHubCode, fetchGitHubRepos, fetchGitHubIssues, createGitHubWebhook, updateGitHubIssueState, GITHUB_BASE_URL } from './providers/github.provider';
import { getGitLabOAuthUrl, exchangeGitLabCode, fetchGitLabRepos, fetchGitLabIssues, createGitLabWebhook, updateGitLabIssueState, refreshGitLabToken, GITLAB_BASE_URL } from './providers/gitlab.provider';
import { getGiteaOAuthUrl, exchangeGiteaCode, fetchGiteaRepos, fetchGiteaIssues, createGiteaWebhook, updateGiteaIssueState, refreshGiteaToken, verifyGiteaToken, GITEA_BASE_URL } from './providers/gitea.provider';
@@ -46,32 +60,43 @@ export class IntegrationsManager {
return this.repository.fetchByProjectId(projectId);
}
- getOAuthUrl(provider: string, projectId: number, userId: number): string {
- const state = jwt.sign(
- { userId, projectId, provider } as OAuthStatePayload,
- process.env.JWT_SIGN as string,
- { expiresIn: '10m' }
- );
-
- if (provider === 'github') {
+ getOAuthUrl(args: GetOAuthUrlArgs): string {
+ const payload: OAuthStatePayload = {
+ userId: args.userId,
+ projectId: args.projectId,
+ provider: args.provider,
+ nonceHash: sha256Hex(args.nonce),
+ };
+ const state = jwt.sign(payload, process.env.JWT_SIGN as string, {
+ expiresIn: INTEGRATIONS_OAUTH_STATE_TTL_SECONDS,
+ });
+
+ if (args.provider === 'github') {
return getGitHubOAuthUrl(state);
- } else if (provider === 'gitlab') {
+ } else if (args.provider === 'gitlab') {
return getGitLabOAuthUrl(state);
- } else if (provider === 'gitea') {
- return getGiteaOAuthUrl(state);
}
- throw new Error(`Unknown provider: ${provider}`);
+ return getGiteaOAuthUrl(state);
}
- async handleOAuthCallback(provider: string, code: string, state: string): Promise<{ projectId: number; orgSlug: string }> {
- $logger.debug({ provider }, '[integrations] handleOAuthCallback start');
- const payload = jwt.verify(state, process.env.JWT_SIGN as string) as OAuthStatePayload;
+ verifyOAuthState(args: VerifyOAuthStateArgs): OAuthStatePayload {
+ const payload = jwt.verify(args.state, process.env.JWT_SIGN as string) as OAuthStatePayload;
integrationsDebugLog({ step: 'callback:state-verified', data: { userId: payload.userId, projectId: payload.projectId, provider: payload.provider } });
- if (payload.provider !== provider) {
- $logger.error({ provider, payloadProvider: payload.provider }, '[integrations] provider mismatch in state');
+ if (payload.provider !== args.provider) {
+ $logger.error({ provider: args.provider, payloadProvider: payload.provider }, '[integrations] provider mismatch in state');
throw new Error('Provider mismatch in state');
}
+ if (!args.nonce || typeof payload.nonceHash !== 'string' || !safeCompareHex(payload.nonceHash, sha256Hex(args.nonce))) {
+ $logger.error({ provider: args.provider, userId: payload.userId }, '[integrations] OAuth callback nonce does not match the state');
+ throw new Error('OAuth callback was not started by this browser');
+ }
+ return payload;
+ }
+
+ async completeOAuthCallback(args: CompleteOAuthCallbackArgs): Promise<{ projectId: number; orgSlug: string }> {
+ const { provider, code, payload } = args;
+ $logger.debug({ provider }, '[integrations] completeOAuthCallback start');
const userLogin = await this.repository.fetchUserLogin(payload.userId);
integrationsDebugLog({ step: 'callback:user-fetched', data: { userLogin } });
diff --git a/api/src/tv-modules/integrations/__tests__/IntegrationsManager.test.ts b/api/src/tv-modules/integrations/__tests__/IntegrationsManager.test.ts
new file mode 100644
index 0000000..0e6c5f2
--- /dev/null
+++ b/api/src/tv-modules/integrations/__tests__/IntegrationsManager.test.ts
@@ -0,0 +1,423 @@
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import jwt from 'jsonwebtoken'
+import nock from 'nock'
+import { createHash } from 'crypto'
+import type { IntegrationsSchemaTypeForSelect } from 'taskview-db-schemas'
+
+const repositoryMock = {
+ fetchById: vi.fn(),
+ fetchMappingsByIntegrationId: vi.fn(),
+ fetchMappingByTaskId: vi.fn(),
+ backfillSourceUrls: vi.fn(),
+ updateTaskComplete: vi.fn(),
+ updateMappingState: vi.fn(),
+ updateTaskTitleAndNote: vi.fn(),
+ updateTaskSourceUrl: vi.fn(),
+ createTasksAndMappingsBatch: vi.fn(),
+ updateLastSyncedAt: vi.fn(),
+ updateTokens: vi.fn(),
+ updateWebhook: vi.fn(),
+ existsRepoInProject: vi.fn(),
+ updateRepo: vi.fn(),
+}
+
+vi.mock('../IntegrationsRepository', () => ({
+ IntegrationsRepository: vi.fn(() => repositoryMock),
+}))
+
+const { IntegrationsManager } = await import('../IntegrationsManager')
+const { encrypt, decrypt } = await import('../../../utils/crypto')
+const { TasksRepository } = await import('../../tasks/TasksRepository')
+type AppUserStub = ConstructorParameters<typeof IntegrationsManager>[0]
+
+const GITHUB_API = 'https://api.github.com'
+const GITLAB = 'https://gitlab.com'
+const GITLAB_API = 'https://gitlab.com/api/v4'
+const GITEA = 'https://gitea.com'
+const GITEA_API = 'https://gitea.com/api/v1'
+
+const NONCE = 'a'.repeat(64)
+const nonceHash = (nonce: string) => createHash('sha256').update(nonce).digest('hex')
+
+const fetchMinKanban = vi.fn()
+const userStub = { tasksManager: { repository: { fetchTaskWithMinKanbanOrder: fetchMinKanban } } } as unknown as AppUserStub
+
+const integration = (overrides: Partial<IntegrationsSchemaTypeForSelect> = {}): IntegrationsSchemaTypeForSelect => ({
+ id: 11,
+ provider: 'github',
+ accessTokenEncrypted: encrypt('gh-token'),
+ refreshTokenEncrypted: null,
+ repoExternalId: null,
+ repoFullName: 'o/r',
+ projectId: 42,
+ webhookId: null,
+ webhookSecretEncrypted: null,
+ isActive: true,
+ lastSyncedAt: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ ...overrides,
+})
+
+let manager: InstanceType<typeof IntegrationsManager>
+
+beforeAll(() => {
+ nock.disableNetConnect()
+ Object.assign(process.env, {
+ JWT_SIGN: 'unit-test-secret',
+ ENCRYPTION_KEY: 'ab'.repeat(32),
+ API_URL: 'https://api.test',
+ GITHUB_INTEGRATION_CLIENT_ID: 'gh-client',
+ GITHUB_INTEGRATION_CALLBACK_URL: 'https://api.test/module/integrations/oauth/github/callback',
+ GITLAB_INTEGRATION_CLIENT_ID: 'gl-client',
+ GITLAB_INTEGRATION_CLIENT_SECRET: 'gl-secret',
+ GITLAB_INTEGRATION_CALLBACK_URL: 'https://api.test/module/integrations/oauth/gitlab/callback',
+ GITEA_INTEGRATION_CLIENT_ID: 'gt-client',
+ GITEA_INTEGRATION_CLIENT_SECRET: 'gt-secret',
+ })
+ manager = new IntegrationsManager(userStub)
+})
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ for (const fn of Object.values(repositoryMock)) fn.mockResolvedValue(true)
+ repositoryMock.fetchMappingsByIntegrationId.mockResolvedValue([])
+ repositoryMock.createTasksAndMappingsBatch.mockImplementation(async (items: unknown[]) => items.length)
+ fetchMinKanban.mockResolvedValue(null)
+})
+
+afterEach(() => {
+ expect(nock.pendingMocks()).toEqual([])
+ nock.cleanAll()
+})
+
+describe('OAuth state', () => {
+ const stateFor = (nonce: string, overrides: Record<string, unknown> = {}) =>
+ jwt.sign({ userId: 7, projectId: 42, provider: 'github', nonceHash: nonceHash(nonce), ...overrides }, process.env.JWT_SIGN as string)
+
+ it('puts only the hash of the nonce into the state', () => {
+ const url = manager.getOAuthUrl({ provider: 'github', projectId: 42, userId: 7, nonce: NONCE })
+ const state = new URL(url).searchParams.get('state') as string
+ const payload = jwt.verify(state, process.env.JWT_SIGN as string) as Record<string, unknown>
+
+ expect(payload.nonceHash).toBe(nonceHash(NONCE))
+ expect(JSON.stringify(payload)).not.toContain(NONCE)
+ expect(payload).toMatchObject({ userId: 7, projectId: 42, provider: 'github' })
+ })
+
+ it('accepts the nonce that produced the state', () => {
+ const payload = manager.verifyOAuthState({ provider: 'github', state: stateFor(NONCE), nonce: NONCE })
+ expect(payload).toMatchObject({ userId: 7, projectId: 42, provider: 'github' })
+ })
+
+ it('refuses a callback without the nonce cookie', () => {
+ expect(() => manager.verifyOAuthState({ provider: 'github', state: stateFor(NONCE), nonce: undefined }))
+ .toThrow('not started by this browser')
+ })
+
+ it('refuses a nonce from another browser', () => {
+ expect(() => manager.verifyOAuthState({ provider: 'github', state: stateFor(NONCE), nonce: 'b'.repeat(64) }))
+ .toThrow('not started by this browser')
+ })
+
+ it('refuses a state issued before nonces existed', () => {
+ const legacy = jwt.sign({ userId: 7, projectId: 42, provider: 'github' }, process.env.JWT_SIGN as string)
+ expect(() => manager.verifyOAuthState({ provider: 'github', state: legacy, nonce: NONCE }))
+ .toThrow('not started by this browser')
+ })
+
+ it('refuses a state minted for another provider', () => {
+ expect(() => manager.verifyOAuthState({ provider: 'gitlab', state: stateFor(NONCE), nonce: NONCE }))
+ .toThrow('Provider mismatch')
+ })
+
+ it('refuses a state signed with another key', () => {
+ const forged = jwt.sign({ userId: 7, projectId: 42, provider: 'github', nonceHash: nonceHash(NONCE) }, 'other-key')
+ expect(() => manager.verifyOAuthState({ provider: 'github', state: forged, nonce: NONCE })).toThrow()
+ })
+})
+
+describe('access tokens (via fetchRepos)', () => {
+ it('GitHub tokens never expire, so no probe is made', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration())
+ nock(GITHUB_API).get('/user/repos').query(true).matchHeader('authorization', 'Bearer gh-token').reply(200, [])
+
+ expect(await manager.fetchRepos(11)).toEqual([])
+ expect(repositoryMock.updateTokens).not.toHaveBeenCalled()
+ })
+
+ it('GitLab keeps the current token when the probe succeeds', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration({
+ provider: 'gitlab', accessTokenEncrypted: encrypt('gl-a'), refreshTokenEncrypted: encrypt('gl-r'),
+ }))
+ nock(GITLAB_API)
+ .get('/user').matchHeader('authorization', 'Bearer gl-a').reply(200, { id: 1 })
+ .get('/projects').query(true).matchHeader('authorization', 'Bearer gl-a')
+ .reply(200, [{ id: 3, path_with_namespace: 'g/p', name: 'p', visibility: 'private', description: 'd', web_url: 'u' }])
+
+ expect(await manager.fetchRepos(11)).toEqual([{ id: 3, fullName: 'g/p', name: 'p', isPrivate: true, description: 'd', url: 'u' }])
+ expect(repositoryMock.updateTokens).not.toHaveBeenCalled()
+ })
+
+ it('GitLab refreshes on 401, stores the new pair encrypted and retries with the new token', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration({
+ provider: 'gitlab', accessTokenEncrypted: encrypt('gl-old'), refreshTokenEncrypted: encrypt('gl-r'),
+ }))
+ nock(GITLAB_API).get('/user').matchHeader('authorization', 'Bearer gl-old').reply(401, {})
+ nock(GITLAB).post('/oauth/token', (b) => b.grant_type === 'refresh_token' && b.refresh_token === 'gl-r')
+ .reply(200, { access_token: 'gl-new', refresh_token: 'gl-new-r' })
+ nock(GITLAB_API).get('/projects').query(true).matchHeader('authorization', 'Bearer gl-new').reply(200, [])
+
+ await manager.fetchRepos(11)
+
+ const [id, access, refresh] = repositoryMock.updateTokens.mock.calls[0]
+ expect(id).toBe(11)
+ expect(decrypt(access)).toBe('gl-new')
+ expect(decrypt(refresh)).toBe('gl-new-r')
+ })
+
+ it('a probe failure other than 401 keeps the token instead of refreshing', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration({
+ provider: 'gitea', accessTokenEncrypted: encrypt('gt-a'), refreshTokenEncrypted: encrypt('gt-r'),
+ }))
+ nock(GITEA_API)
+ .get('/user').reply(503, {})
+ .get('/user/repos').query(true).matchHeader('authorization', 'Bearer gt-a').reply(200, [])
+
+ expect(await manager.fetchRepos(11)).toEqual([])
+ expect(repositoryMock.updateTokens).not.toHaveBeenCalled()
+ })
+
+ it('gives up when the refresh itself fails', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration({
+ provider: 'gitea', accessTokenEncrypted: encrypt('gt-a'), refreshTokenEncrypted: encrypt('gt-r'),
+ }))
+ nock(GITEA_API).get('/user').reply(401, {})
+ nock(GITEA).post('/login/oauth/access_token').reply(400, { error: 'invalid_grant' })
+
+ expect(await manager.fetchRepos(11)).toEqual([])
+ expect(repositoryMock.updateTokens).not.toHaveBeenCalled()
+ })
+
+ it('an integration that never finished OAuth has no repos', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration({ accessTokenEncrypted: null }))
+ expect(await manager.fetchRepos(11)).toEqual([])
+ })
+})
+
+describe('syncIssues', () => {
+ const ghIssue = (n: number, state: 'open' | 'closed' = 'open') => ({ number: n, title: `t${n}`, body: `b${n}`, state, html_url: '' })
+
+ it('inserts new issues oldest-first with descending kanban order below the current minimum', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration())
+ fetchMinKanban.mockResolvedValue(-100)
+ nock(GITHUB_API).get('/repos/o/r/issues').query((q) => q.since === undefined)
+ .reply(200, [ghIssue(3, 'closed'), ghIssue(2), ghIssue(1)])
+
+ expect(await manager.syncIssues(11)).toBe(3)
+
+ const items = repositoryMock.createTasksAndMappingsBatch.mock.calls[0][0]
+ expect(items.map((i: { issueNumber: number }) => i.issueNumber)).toEqual([1, 2, 3])
+ const gap = TasksRepository.KANBAN_ORDER_GAP
+ expect(items.map((i: { kanbanOrder: number }) => i.kanbanOrder)).toEqual([-100 - gap, -100 - gap * 2, -100 - gap * 3])
+ expect(items[2]).toMatchObject({
+ goalId: 42, description: 't3', note: 'b3', complete: true, issueState: 'closed',
+ sourceUrl: 'https://github.com/o/r/issues/3',
+ })
+ expect(repositoryMock.updateLastSyncedAt).toHaveBeenCalledWith(11)
+ expect(repositoryMock.backfillSourceUrls).not.toHaveBeenCalled()
+ })
+
+ it('updates already-mapped issues in place and asks the provider only for changes since the last sync', async () => {
+ const since = new Date('2026-01-01T00:00:00.000Z')
+ repositoryMock.fetchById.mockResolvedValue(integration({ lastSyncedAt: since }))
+ repositoryMock.fetchMappingsByIntegrationId.mockResolvedValue([
+ { id: 900, integrationId: 11, taskId: 500, issueNumber: 1, issueState: 'open', syncedAt: null },
+ ])
+ nock(GITHUB_API).get('/repos/o/r/issues').query((q) => q.since === since.toISOString() && q.sort === 'updated')
+ .reply(200, [{ ...ghIssue(1, 'closed'), title: 'renamed', body: null }])
+
+ expect(await manager.syncIssues(11)).toBe(0)
+
+ expect(repositoryMock.updateTaskComplete).toHaveBeenCalledWith(500, true)
+ expect(repositoryMock.updateMappingState).toHaveBeenCalledWith(900, 'closed')
+ expect(repositoryMock.updateTaskTitleAndNote).toHaveBeenCalledWith(500, 'renamed', null)
+ expect(repositoryMock.updateTaskSourceUrl).toHaveBeenCalledWith(500, 'https://github.com/o/r/issues/1')
+ expect(repositoryMock.backfillSourceUrls).toHaveBeenCalledWith(11, 'https://github.com/o/r/issues/')
+ expect(repositoryMock.createTasksAndMappingsBatch).toHaveBeenCalledWith([])
+ })
+
+ it('does not touch the mapping state when it already matches', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration())
+ repositoryMock.fetchMappingsByIntegrationId.mockResolvedValue([
+ { id: 900, integrationId: 11, taskId: 500, issueNumber: 1, issueState: 'open', syncedAt: null },
+ ])
+ nock(GITHUB_API).get('/repos/o/r/issues').query(true).reply(200, [ghIssue(1)])
+
+ await manager.syncIssues(11)
+ expect(repositoryMock.updateMappingState).not.toHaveBeenCalled()
+ })
+
+ it('GitLab maps issues by iid, uses the numeric project id and the /-/issues/ URL shape', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration({
+ provider: 'gitlab', repoExternalId: '77', repoFullName: 'g/p',
+ accessTokenEncrypted: encrypt('gl-a'), refreshTokenEncrypted: encrypt('gl-r'),
+ }))
+ nock(GITLAB_API)
+ .get('/user').reply(200, {})
+ .get('/projects/77/issues').query(true)
+ .reply(200, [{ iid: 9, title: 'gl', description: 'd', state: 'closed', web_url: '' }])
+
+ await manager.syncIssues(11)
+ expect(repositoryMock.createTasksAndMappingsBatch.mock.calls[0][0][0]).toMatchObject({
+ issueNumber: 9, complete: true, issueState: 'closed', sourceUrl: 'https://gitlab.com/g/p/-/issues/9',
+ })
+ })
+
+ it('GitLab without a stored project id syncs nothing rather than guessing', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration({
+ provider: 'gitlab', repoExternalId: null, accessTokenEncrypted: encrypt('gl-a'), refreshTokenEncrypted: null,
+ }))
+ expect(await manager.syncIssues(11)).toBe(0)
+ expect(repositoryMock.createTasksAndMappingsBatch).toHaveBeenCalledWith([])
+ })
+
+ it('Gitea builds source URLs from its base URL', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration({ provider: 'gitea', accessTokenEncrypted: encrypt('gt-a') }))
+ nock(GITEA_API).get('/repos/o/r/issues').query(true)
+ .reply(200, [{ number: 4, title: 'g', body: null, state: 'open', html_url: '' }])
+
+ await manager.syncIssues(11)
+ expect(repositoryMock.createTasksAndMappingsBatch.mock.calls[0][0][0]).toMatchObject({
+ issueNumber: 4, complete: false, sourceUrl: 'https://gitea.com/o/r/issues/4',
+ })
+ })
+
+ it('skips an integration without a selected repository', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration({ repoFullName: null }))
+ expect(await manager.syncIssues(11)).toBe(0)
+ expect(repositoryMock.updateLastSyncedAt).not.toHaveBeenCalled()
+ })
+})
+
+describe('onTaskCompleteChanged', () => {
+ const mapping = (overrides: Partial<IntegrationsSchemaTypeForSelect> = {}, issueState = 'open') => ({
+ id: 900, integrationId: 11, taskId: 500, issueNumber: 3, issueState, syncedAt: null, integration: integration(overrides),
+ })
+
+ it('is a no-op for a task that did not come from an integration', async () => {
+ repositoryMock.fetchMappingByTaskId.mockResolvedValue(undefined)
+ expect(await manager.onTaskCompleteChanged(500, true)).toBe(true)
+ })
+
+ it('leaves the provider alone when the integration is paused', async () => {
+ repositoryMock.fetchMappingByTaskId.mockResolvedValue(mapping({ isActive: false }))
+ expect(await manager.onTaskCompleteChanged(500, true)).toBe(true)
+ expect(repositoryMock.updateMappingState).not.toHaveBeenCalled()
+ })
+
+ it('skips the round trip when the issue is already in the target state', async () => {
+ repositoryMock.fetchMappingByTaskId.mockResolvedValue(mapping({}, 'closed'))
+ expect(await manager.onTaskCompleteChanged(500, true)).toBe(true)
+ expect(repositoryMock.updateMappingState).not.toHaveBeenCalled()
+ })
+
+ it('closes the GitHub issue and records the new state', async () => {
+ repositoryMock.fetchMappingByTaskId.mockResolvedValue(mapping())
+ nock(GITHUB_API).patch('/repos/o/r/issues/3', { state: 'closed' }).reply(200, {})
+
+ expect(await manager.onTaskCompleteChanged(500, true)).toBe(true)
+ expect(repositoryMock.updateMappingState).toHaveBeenCalledWith(900, 'closed')
+ })
+
+ it('reopens a GitLab issue with state_event=reopen', async () => {
+ repositoryMock.fetchMappingByTaskId.mockResolvedValue(mapping({
+ provider: 'gitlab', repoExternalId: '77', accessTokenEncrypted: encrypt('gl-a'), refreshTokenEncrypted: null,
+ }, 'closed'))
+ nock(GITLAB_API).put('/projects/77/issues/3', { state_event: 'reopen' }).reply(200, {})
+
+ expect(await manager.onTaskCompleteChanged(500, false)).toBe(true)
+ expect(repositoryMock.updateMappingState).toHaveBeenCalledWith(900, 'open')
+ })
+
+ it('closes a Gitea issue', async () => {
+ repositoryMock.fetchMappingByTaskId.mockResolvedValue(mapping({ provider: 'gitea', accessTokenEncrypted: encrypt('gt-a') }))
+ nock(GITEA_API).patch('/repos/o/r/issues/3', { state: 'closed' }).reply(200, {})
+
+ expect(await manager.onTaskCompleteChanged(500, true)).toBe(true)
+ expect(repositoryMock.updateMappingState).toHaveBeenCalledWith(900, 'closed')
+ })
+
+ it('reports failure when no usable token exists, so the caller can tell the user', async () => {
+ repositoryMock.fetchMappingByTaskId.mockResolvedValue(mapping({
+ provider: 'gitea', accessTokenEncrypted: encrypt('gt-a'), refreshTokenEncrypted: encrypt('gt-r'),
+ }))
+ nock(GITEA_API).get('/user').reply(401, {})
+ nock(GITEA).post('/login/oauth/access_token').reply(400, {})
+
+ expect(await manager.onTaskCompleteChanged(500, true)).toBe(false)
+ expect(repositoryMock.updateMappingState).not.toHaveBeenCalled()
+ })
+})
+
+describe('selectRepo and webhook registration', () => {
+ const selection = { integrationId: 11, repoFullName: 'o/r', repoExternalId: '77' }
+
+ it('refuses to connect a repository twice to the same project', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration())
+ repositoryMock.existsRepoInProject.mockResolvedValue(true)
+
+ expect(await manager.selectRepo(selection)).toBe(false)
+ expect(repositoryMock.updateRepo).not.toHaveBeenCalled()
+ expect(repositoryMock.existsRepoInProject).toHaveBeenCalledWith(42, 'o/r', 11)
+ })
+
+ it('stores the repo, syncs it and registers a webhook whose secret is stored encrypted', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration())
+ repositoryMock.existsRepoInProject.mockResolvedValue(false)
+ repositoryMock.updateRepo.mockResolvedValue(integration())
+ nock(GITHUB_API).get('/repos/o/r/issues').query(true).reply(200, [])
+ let receivedSecret = ''
+ nock(GITHUB_API).post('/repos/o/r/hooks', (body) => {
+ receivedSecret = body.config.secret
+ return body.config.url === 'https://api.test/module/integrations/webhook/github'
+ }).reply(201, { id: 55 })
+
+ expect(await manager.selectRepo(selection)).toBeTruthy()
+ await vi.waitFor(() => expect(repositoryMock.updateWebhook).toHaveBeenCalled())
+
+ const [id, webhookId, secretEncrypted] = repositoryMock.updateWebhook.mock.calls[0]
+ expect(id).toBe(11)
+ expect(webhookId).toBe('55')
+ expect(receivedSecret).toHaveLength(64)
+ expect(decrypt(secretEncrypted)).toBe(receivedSecret)
+ expect(secretEncrypted).not.toContain(receivedSecret)
+ await vi.waitFor(() => expect(repositoryMock.updateLastSyncedAt).toHaveBeenCalledWith(11))
+ })
+
+ it('does not register a webhook when the API has no public URL to receive it', async () => {
+ const saved = process.env.API_URL
+ delete process.env.API_URL
+ repositoryMock.fetchById.mockResolvedValue(integration())
+ repositoryMock.existsRepoInProject.mockResolvedValue(false)
+ repositoryMock.updateRepo.mockResolvedValue(integration())
+ nock(GITHUB_API).get('/repos/o/r/issues').query(true).reply(200, [])
+
+ await manager.selectRepo(selection)
+ await vi.waitFor(() => expect(repositoryMock.updateLastSyncedAt).toHaveBeenCalled())
+ expect(repositoryMock.updateWebhook).not.toHaveBeenCalled()
+ process.env.API_URL = saved
+ })
+
+ it('GitLab needs the numeric project id to register a webhook', async () => {
+ repositoryMock.fetchById.mockResolvedValue(integration({
+ provider: 'gitlab', repoExternalId: null, accessTokenEncrypted: encrypt('gl-a'), refreshTokenEncrypted: null,
+ }))
+ repositoryMock.existsRepoInProject.mockResolvedValue(false)
+ repositoryMock.updateRepo.mockResolvedValue(integration({ provider: 'gitlab' }))
+
+ await manager.selectRepo(selection)
+ await vi.waitFor(() => expect(repositoryMock.updateLastSyncedAt).toHaveBeenCalled())
+ expect(repositoryMock.updateWebhook).not.toHaveBeenCalled()
+ })
+})
diff --git a/api/src/tv-modules/integrations/__tests__/IntegrationsOAuth.integration.spec.ts b/api/src/tv-modules/integrations/__tests__/IntegrationsOAuth.integration.spec.ts
new file mode 100644
index 0000000..d57275c
--- /dev/null
+++ b/api/src/tv-modules/integrations/__tests__/IntegrationsOAuth.integration.spec.ts
@@ -0,0 +1,207 @@
+import axios from 'axios';
+import http from 'http';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import App from '../../../App';
+import { decrypt } from '../../../utils/crypto';
+import { integrationsOfGoal as integrationsOfGoalRows } from './support';
+import type { IntegrationProvider } from '../types';
+
+vi.mock('emailjs', () => ({
+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
+}));
+
+// The provider side is not under test. The code is never sent anywhere; the
+// exchange just hands back a token so the callback can be driven to the end.
+vi.mock('../providers/github.provider', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../providers/github.provider')>()),
+ exchangeGitHubCode: vi.fn().mockResolvedValue('gh-access-token'),
+}));
+vi.mock('../providers/gitlab.provider', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../providers/gitlab.provider')>()),
+ exchangeGitLabCode: vi.fn().mockResolvedValue({ accessToken: 'gl-access-token', refreshToken: 'gl-refresh-token' }),
+}));
+vi.mock('../providers/gitea.provider', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../providers/gitea.provider')>()),
+ exchangeGiteaCode: vi.fn().mockResolvedValue({ accessToken: 'gt-access-token', refreshToken: null }),
+}));
+
+const port = 1815;
+const url = `http://localhost:${port}`;
+const NONCE_COOKIE = 'tv_integrations_oauth';
+
+const LOGIN = '[email protected]';
+const PASSWORD = 'user1!#Q';
+
+let server: http.Server;
+let jwt = '';
+let goalId = 0;
+
+const api = axios.create({
+ baseURL: url,
+ validateStatus: () => true,
+ maxRedirects: 0,
+ httpAgent: new http.Agent({ keepAlive: false }),
+});
+
+const initiate = (projectId: number, provider: IntegrationProvider = 'github') =>
+ api.get(`/module/integrations/oauth/${provider}?projectId=${projectId}&token=${encodeURIComponent(jwt)}`);
+
+const nonceFrom = (response: { headers: Record<string, unknown> }): string => {
+ const raw = ([] as string[]).concat((response.headers['set-cookie'] as string[]) ?? []);
+ const cookie = raw.find((entry) => entry.startsWith(`${NONCE_COOKIE}=`));
+ expect(cookie).toBeDefined();
+ return (cookie as string).split(';')[0].split('=')[1];
+};
+
+const stateFrom = (response: { headers: Record<string, unknown> }): string => {
+ const location = new URL(response.headers.location as string);
+ return location.searchParams.get('state') as string;
+};
+
+const callback = (state: string, nonce?: string, provider: IntegrationProvider = 'github') =>
+ api.get(`/module/integrations/oauth/${provider}/callback?code=whatever&state=${encodeURIComponent(state)}`, {
+ headers: nonce ? { Cookie: `${NONCE_COOKIE}=${nonce}` } : {},
+ });
+
+const integrationsOfGoal = async () => {
+ const response = await api.get(`/module/integrations?projectId=${goalId}`, {
+ headers: { Authorization: `Bearer ${jwt}` },
+ });
+ expect(response.status).toBe(200);
+ return response.data.response as { id: number }[];
+};
+
+/**
+ * A git integration is connected over OAuth where TaskView is the client. The
+ * callback must only complete for the browser that started the flow, and only
+ * into a project the initiator may manage — otherwise an attacker starts a flow
+ * for his own project and tricks a victim into finishing it with her account.
+ */
+describe('Integrations OAuth browser binding', () => {
+ beforeAll(async () => {
+ for (const provider of ['GITHUB', 'GITLAB', 'GITEA']) {
+ process.env[`${provider}_INTEGRATION_CLIENT_ID`] ??= 'test-client';
+ process.env[`${provider}_INTEGRATION_CALLBACK_URL`] ??= `${url}/module/integrations/oauth/${provider.toLowerCase()}/callback`;
+ }
+ process.env.ENCRYPTION_KEY ??= 'ab'.repeat(32);
+
+ server = new App(port).listen();
+
+ const login = await api.post('/module/auth/login', { login: LOGIN, password: PASSWORD });
+ expect(login.status).toBe(200);
+ jwt = login.data.access;
+
+ const goal = await api.post(
+ '/module/goals',
+ { name: `integrations-oauth-it-${Date.now()}` },
+ { headers: { Authorization: `Bearer ${jwt}` } },
+ );
+ expect(goal.status).toBe(200);
+ goalId = goal.data.response.id ?? goal.data.response.goal?.id;
+ });
+
+ afterAll(async () => {
+ for (const integration of await integrationsOfGoal()) {
+ await api.delete('/module/integrations', {
+ headers: { Authorization: `Bearer ${jwt}` },
+ data: { id: integration.id },
+ });
+ }
+ if (goalId) {
+ await api.delete('/module/goals', {
+ headers: { Authorization: `Bearer ${jwt}` },
+ data: { goalId },
+ });
+ }
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ it('refuses to start a flow without a token', async () => {
+ const response = await api.get(`/module/integrations/oauth/github?projectId=${goalId}`);
+ expect(response.status).toBe(401);
+ });
+
+ it('refuses to start a flow for a project the user may not manage', async () => {
+ const response = await initiate(999_999_999);
+ expect(response.status).toBe(403);
+ expect(response.headers['set-cookie']).toBeUndefined();
+ });
+
+ it('refuses an unknown provider', async () => {
+ const response = await api.get(`/module/integrations/oauth/bitbucket?projectId=${goalId}&token=${encodeURIComponent(jwt)}`);
+ expect(response.status).toBe(400);
+ });
+
+ it('starts a flow with a nonce cookie and a state carrying only its hash', async () => {
+ const response = await initiate(goalId);
+ expect(response.status).toBe(302);
+ expect(response.headers.location).toContain('github.com');
+
+ const nonce = nonceFrom(response);
+ const state = stateFrom(response);
+ expect(nonce.length).toBeGreaterThanOrEqual(32);
+ expect(state).not.toContain(nonce);
+
+ const cookie = (response.headers['set-cookie'] as string[]).find((entry) => entry.startsWith(NONCE_COOKIE)) as string;
+ expect(cookie).toMatch(/HttpOnly/i);
+ expect(cookie).toMatch(/SameSite=Lax/i);
+ expect(cookie).toContain('Path=/module/integrations/oauth');
+ });
+
+ it('rejects a callback that arrives without the nonce cookie', async () => {
+ const started = await initiate(goalId);
+ const response = await callback(stateFrom(started));
+
+ expect(response.status).toBe(302);
+ expect(response.headers.location).toContain('oauth=error');
+ expect(await integrationsOfGoal()).toHaveLength(0);
+ });
+
+ it('rejects a callback whose cookie belongs to another browser', async () => {
+ const attacker = await initiate(goalId);
+ const victim = await initiate(goalId);
+ const response = await callback(stateFrom(attacker), nonceFrom(victim));
+
+ expect(response.status).toBe(302);
+ expect(response.headers.location).toContain('oauth=error');
+ expect(await integrationsOfGoal()).toHaveLength(0);
+ });
+
+ it('completes a callback from the browser that started the flow and clears the cookie', async () => {
+ const started = await initiate(goalId);
+ const response = await callback(stateFrom(started), nonceFrom(started));
+
+ expect(response.status).toBe(302);
+ expect(response.headers.location).toContain(`/${goalId}/integrations?oauth=success`);
+
+ const cleared = (response.headers['set-cookie'] as string[]).find((entry) => entry.startsWith(NONCE_COOKIE)) as string;
+ expect(cleared).toMatch(/Expires=Thu, 01 Jan 1970/);
+
+ expect(await integrationsOfGoal()).toHaveLength(1);
+ });
+
+ describe.each([
+ { provider: 'gitlab' as const, accessToken: 'gl-access-token', refreshToken: 'gl-refresh-token' },
+ { provider: 'gitea' as const, accessToken: 'gt-access-token', refreshToken: null },
+ ])('$provider', ({ provider, accessToken, refreshToken }) => {
+ it('completes the same bound flow and stores the tokens encrypted', async () => {
+ const started = await initiate(goalId, provider);
+ expect(started.status).toBe(302);
+ const response = await callback(stateFrom(started), nonceFrom(started), provider);
+ expect(response.headers.location).toContain('oauth=success');
+
+ const row = (await integrationsOfGoalRows(goalId)).find((r) => r.provider === provider);
+ expect(row).toBeDefined();
+ expect(row?.access_token_encrypted).not.toContain(accessToken);
+ expect(decrypt(row?.access_token_encrypted as string)).toBe(accessToken);
+ if (refreshToken) expect(decrypt(row?.refresh_token_encrypted as string)).toBe(refreshToken);
+ else expect(row?.refresh_token_encrypted).toBeNull();
+ });
+
+ it('refuses a callback carrying a state minted for another provider', async () => {
+ const started = await initiate(goalId, 'github');
+ const response = await callback(stateFrom(started), nonceFrom(started), provider);
+ expect(response.headers.location).toContain('oauth=error');
+ });
+ });
+});
diff --git a/api/src/tv-modules/integrations/__tests__/IntegrationsPermissions.integration.spec.ts b/api/src/tv-modules/integrations/__tests__/IntegrationsPermissions.integration.spec.ts
new file mode 100644
index 0000000..9ff45af
--- /dev/null
+++ b/api/src/tv-modules/integrations/__tests__/IntegrationsPermissions.integration.spec.ts
@@ -0,0 +1,112 @@
+import http from 'http';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import App from '../../../App';
+import { cleanupGoal, createApi, insertIntegration, loginAndCreateGoal } from './support';
+
+vi.mock('emailjs', () => ({
+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
+}));
+
+const port = 1817;
+const api = createApi(port);
+const FOREIGN_GOAL = 999_999_999;
+const MISSING_INTEGRATION = 999_999_999;
+
+let server: http.Server;
+let jwt = '';
+let goalId = 0;
+let integrationId = 0;
+
+const auth = () => ({ headers: { Authorization: `Bearer ${jwt}` } });
+
+/**
+ * Every management route is guarded by the project's INTEGRATIONS_CAN_VIEW /
+ * INTEGRATIONS_CAN_MANAGE permission. When a route names an integration, the
+ * project is derived from it and a projectId the caller sends is ignored.
+ */
+describe('Integrations route permissions', () => {
+ beforeAll(async () => {
+ process.env.ENCRYPTION_KEY ??= 'ab'.repeat(32);
+ server = new App(port).listen();
+ ({ jwt, goalId } = await loginAndCreateGoal(api, `integrations-perm-it-${Date.now()}`));
+ integrationId = await insertIntegration({ provider: 'github', projectId: goalId });
+ });
+
+ afterAll(async () => {
+ await cleanupGoal(api, jwt, goalId);
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ describe('anonymous callers', () => {
+ it.each([
+ ['GET', '/module/integrations?projectId=1'],
+ ['POST', '/module/integrations'],
+ ['DELETE', '/module/integrations'],
+ ['PATCH', '/module/integrations/toggle'],
+ ['PATCH', '/module/integrations/select-repo'],
+ ['POST', '/module/integrations/sync'],
+ ['GET', '/module/integrations/repos?integrationId=1'],
+ ])('%s %s answers 401', async (method, url) => {
+ const response = await api.request({ method, url, data: { projectId: goalId, id: integrationId, integrationId } });
+ expect(response.status).toBe(401);
+ });
+ });
+
+ describe('project-scoped routes', () => {
+ it('lists integrations of a project the user can view', async () => {
+ const response = await api.get(`/module/integrations?projectId=${goalId}`, auth());
+ expect(response.status).toBe(200);
+ expect(response.data.response.map((i: { id: number }) => i.id)).toContain(integrationId);
+ });
+
+ it('refuses a project the user has no role in', async () => {
+ expect((await api.get(`/module/integrations?projectId=${FOREIGN_GOAL}`, auth())).status).toBe(403);
+ const create = await api.post('/module/integrations', { provider: 'github', repoFullName: 'a/b', projectId: FOREIGN_GOAL }, auth());
+ expect(create.status).toBe(403);
+ });
+
+ it('rejects a request that names no project at all', async () => {
+ expect((await api.get('/module/integrations', auth())).status).toBe(400);
+ });
+ });
+
+ describe('integration-scoped routes', () => {
+ it('derives the project from the integration and ignores a foreign projectId in the query', async () => {
+ const response = await api.get(`/module/integrations/repos?integrationId=${integrationId}&projectId=${FOREIGN_GOAL}`, auth());
+ expect(response.status).toBe(200);
+ expect(response.data.response).toEqual([]);
+ });
+
+ it('cannot be talked into a project the user owns by naming an integration that does not exist', async () => {
+ const response = await api.get(`/module/integrations/repos?integrationId=${MISSING_INTEGRATION}&projectId=${goalId}`, auth());
+ expect(response.status).toBe(400);
+ });
+
+ it.each([
+ ['toggle', 'patch', '/module/integrations/toggle', { id: MISSING_INTEGRATION, isActive: false }],
+ ['select-repo', 'patch', '/module/integrations/select-repo', { integrationId: MISSING_INTEGRATION, repoFullName: 'a/b', repoExternalId: '1' }],
+ ['sync', 'post', '/module/integrations/sync', { integrationId: MISSING_INTEGRATION }],
+ ['delete', 'delete', '/module/integrations', { id: MISSING_INTEGRATION }],
+ ])('%s of a missing integration answers 400 rather than leaking whether it exists elsewhere', async (_name, method, url, body) => {
+ const response = await api.request({ method, url, data: body, ...auth() });
+ expect(response.status).toBe(400);
+ });
+
+ it('lets a manager pause and resume an integration of their project', async () => {
+ const paused = await api.patch('/module/integrations/toggle', { id: integrationId, isActive: false }, auth());
+ expect(paused.status).toBe(200);
+ expect(paused.data.response.isActive).toBe(false);
+
+ const resumed = await api.patch('/module/integrations/toggle', { id: integrationId, isActive: true }, auth());
+ expect(resumed.data.response.isActive).toBe(true);
+ });
+ });
+
+ describe('inbound webhooks', () => {
+ it('never require a user session, only the provider signature', async () => {
+ const response = await api.post('/module/integrations/webhook/github', { action: 'opened' }, { headers: { 'X-GitHub-Event': 'issues' } });
+ expect(response.status).toBe(401);
+ expect(response.data).toBe('Missing signature');
+ });
+ });
+});
diff --git a/api/src/tv-modules/integrations/__tests__/IntegrationsSync.integration.spec.ts b/api/src/tv-modules/integrations/__tests__/IntegrationsSync.integration.spec.ts
new file mode 100644
index 0000000..b8adeae
--- /dev/null
+++ b/api/src/tv-modules/integrations/__tests__/IntegrationsSync.integration.spec.ts
@@ -0,0 +1,163 @@
+import http from 'http';
+import nock from 'nock';
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import App from '../../../App';
+import { TasksRepository } from '../../tasks/TasksRepository';
+import { cleanupGoal, createApi, insertIntegration, integrationsOfGoal, loginAndCreateGoal, mappingsOf, tasksOfGoal } from './support';
+
+vi.mock('emailjs', () => ({
+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
+}));
+
+const port = 1818;
+const api = createApi(port);
+
+let server: http.Server;
+let jwt = '';
+let goalId = 0;
+
+const sync = (integrationId: number) =>
+ api.post('/module/integrations/sync', { integrationId }, { headers: { Authorization: `Bearer ${jwt}` } });
+
+/**
+ * Manual sync pulls the repository's issues into the project as tasks. The
+ * provider is answered by nock; everything on our side — token decryption,
+ * ordering, batch insert, mapping upsert, incremental since — is real.
+ */
+describe('Integrations issue sync', () => {
+ beforeAll(async () => {
+ process.env.ENCRYPTION_KEY ??= 'ab'.repeat(32);
+ nock.disableNetConnect();
+ nock.enableNetConnect(/localhost|127\.0\.0\.1/);
+ server = new App(port).listen();
+ ({ jwt, goalId } = await loginAndCreateGoal(api, `integrations-sync-it-${Date.now()}`));
+ });
+
+ afterEach(() => {
+ expect(nock.pendingMocks()).toEqual([]);
+ nock.cleanAll();
+ });
+
+ afterAll(async () => {
+ nock.enableNetConnect();
+ await cleanupGoal(api, jwt, goalId);
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ describe('GitHub', () => {
+ const repo = 'sync-it/github';
+ let integrationId = 0;
+ const gh = (number: number, state: 'open' | 'closed', extra: Record<string, unknown> = {}) =>
+ ({ number, title: `GH ${number}`, body: `body ${number}`, state, html_url: '', ...extra });
+
+ beforeAll(async () => {
+ integrationId = await insertIntegration({ provider: 'github', projectId: goalId, repoFullName: repo, accessToken: 'gh-token' });
+ });
+
+ it('creates one task per issue, oldest first, newest on top of the kanban, and skips pull requests', async () => {
+ nock('https://api.github.com')
+ .get(`/repos/${repo}/issues`).query((q) => q.since === undefined)
+ .matchHeader('authorization', 'Bearer gh-token')
+ .reply(200, [gh(3, 'open'), gh(2, 'closed'), gh(1, 'open'), gh(4, 'open', { pull_request: {} })]);
+
+ const response = await sync(integrationId);
+ expect(response.status).toBe(200);
+ expect(response.data.response).toEqual({ synced: 3 });
+
+ const tasks = await tasksOfGoal(goalId);
+ expect(tasks.map((t) => t.description)).toEqual(['GH 1', 'GH 2', 'GH 3']);
+ expect(tasks.map((t) => t.complete)).toEqual([false, true, false]);
+ const gap = TasksRepository.KANBAN_ORDER_GAP;
+ expect(tasks.map((t) => t.kanban_order)).toEqual([-gap, -gap * 2, -gap * 3]);
+ expect(tasks[0].source_url).toBe(`https://github.com/${repo}/issues/1`);
+ expect((await mappingsOf(integrationId)).map((m) => [m.issue_number, m.issue_state])).toEqual([[1, 'open'], [2, 'closed'], [3, 'open']]);
+ expect((await integrationsOfGoal(goalId))[0].last_synced_at).not.toBeNull();
+ });
+
+ it('a second sync is incremental and updates existing tasks instead of duplicating them', async () => {
+ nock('https://api.github.com')
+ .get(`/repos/${repo}/issues`).query((q) => typeof q.since === 'string' && q.sort === 'updated')
+ .reply(200, [gh(1, 'closed', { title: 'GH 1 done' })]);
+
+ const response = await sync(integrationId);
+ expect(response.data.response).toEqual({ synced: 0 });
+
+ const tasks = await tasksOfGoal(goalId);
+ expect(tasks).toHaveLength(3);
+ expect(tasks[0]).toMatchObject({ description: 'GH 1 done', complete: true });
+ expect((await mappingsOf(integrationId))[0].issue_state).toBe('closed');
+ });
+
+ it('reports zero and stays quiet when the provider is unreachable', async () => {
+ nock('https://api.github.com').get(`/repos/${repo}/issues`).query(true).reply(502, 'bad gateway');
+
+ const response = await sync(integrationId);
+ expect(response.status).toBe(200);
+ expect(response.data.response).toEqual({ synced: 0 });
+ expect(await tasksOfGoal(goalId)).toHaveLength(3);
+ });
+ });
+
+ describe('GitLab', () => {
+ let integrationId = 0;
+
+ beforeAll(async () => {
+ integrationId = await insertIntegration({
+ provider: 'gitlab', projectId: goalId, repoFullName: 'sync-it/gitlab', repoExternalId: '4242',
+ accessToken: 'gl-token', refreshToken: 'gl-refresh',
+ });
+ });
+
+ it('probes the token, then syncs by iid into the same project', async () => {
+ nock('https://gitlab.com/api/v4')
+ .get('/user').matchHeader('authorization', 'Bearer gl-token').reply(200, {})
+ .get('/projects/4242/issues').query(true)
+ .reply(200, [{ iid: 10, title: 'GL 10', description: null, state: 'opened', web_url: '' }]);
+
+ const response = await sync(integrationId);
+ expect(response.data.response).toEqual({ synced: 1 });
+ expect(await mappingsOf(integrationId)).toMatchObject([{ issue_number: 10, issue_state: 'open' }]);
+ expect((await tasksOfGoal(goalId)).at(-1)).toMatchObject({ description: 'GL 10', source_url: 'https://gitlab.com/sync-it/gitlab/-/issues/10' });
+ });
+
+ it('refreshes an expired token and persists the new pair before syncing', async () => {
+ nock('https://gitlab.com/api/v4').get('/user').reply(401, {});
+ nock('https://gitlab.com').post('/oauth/token', (b) => b.refresh_token === 'gl-refresh')
+ .reply(200, { access_token: 'gl-token-2', refresh_token: 'gl-refresh-2' });
+ nock('https://gitlab.com/api/v4').get('/projects/4242/issues').query(true)
+ .matchHeader('authorization', 'Bearer gl-token-2').reply(200, []);
+
+ expect((await sync(integrationId)).data.response).toEqual({ synced: 0 });
+
+ // The next probe must use the rotated token straight from the database.
+ nock('https://gitlab.com/api/v4')
+ .get('/user').matchHeader('authorization', 'Bearer gl-token-2').reply(200, {})
+ .get('/projects/4242/issues').query(true).reply(200, []);
+ expect((await sync(integrationId)).status).toBe(200);
+ });
+ });
+
+ describe('Gitea', () => {
+ let integrationId = 0;
+
+ beforeAll(async () => {
+ integrationId = await insertIntegration({ provider: 'gitea', projectId: goalId, repoFullName: 'sync-it/gitea', accessToken: 'gt-token' });
+ });
+
+ it('syncs without a probe when there is no refresh token', async () => {
+ nock('https://gitea.com/api/v1')
+ .get('/repos/sync-it/gitea/issues').query((q) => q.type === 'issues')
+ .matchHeader('authorization', 'Bearer gt-token')
+ .reply(200, [{ number: 5, title: 'GT 5', body: 'b', state: 'closed', html_url: '' }]);
+
+ expect((await sync(integrationId)).data.response).toEqual({ synced: 1 });
+ expect(await mappingsOf(integrationId)).toMatchObject([{ issue_number: 5, issue_state: 'closed' }]);
+ expect((await tasksOfGoal(goalId)).at(-1)).toMatchObject({ description: 'GT 5', complete: true, source_url: 'https://gitea.com/sync-it/gitea/issues/5' });
+ });
+ });
+
+ it('syncs nothing for an integration that has no repository selected yet', async () => {
+ const bare = await insertIntegration({ provider: 'github', projectId: goalId, accessToken: 'gh-token' });
+ expect((await sync(bare)).data.response).toEqual({ synced: 0 });
+ });
+});
diff --git a/api/src/tv-modules/integrations/__tests__/IntegrationsWebhooks.integration.spec.ts b/api/src/tv-modules/integrations/__tests__/IntegrationsWebhooks.integration.spec.ts
new file mode 100644
index 0000000..3a78417
--- /dev/null
+++ b/api/src/tv-modules/integrations/__tests__/IntegrationsWebhooks.integration.spec.ts
@@ -0,0 +1,245 @@
+import http from 'http';
+import { createHmac } from 'crypto';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import App from '../../../App';
+import { cleanupGoal, createApi, insertIntegration, loginAndCreateGoal, mappingsOf, tasksOfGoal } from './support';
+
+vi.mock('emailjs', () => ({
+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
+}));
+
+const port = 1816;
+const api = createApi(port);
+const SECRET = 'webhook-secret-under-test';
+
+let server: http.Server;
+let jwt = '';
+let goalId = 0;
+
+const post = (path: string, body: unknown, headers: Record<string, string>) =>
+ api.post(path, JSON.stringify(body), { headers: { 'Content-Type': 'application/json', ...headers } });
+
+const githubHeaders = (body: unknown, secret = SECRET, event = 'issues') => ({
+ 'X-GitHub-Event': event,
+ 'X-Hub-Signature-256': 'sha256=' + createHmac('sha256', secret).update(JSON.stringify(body)).digest('hex'),
+});
+const giteaHeaders = (body: unknown, secret = SECRET, event = 'issues') => ({
+ 'X-Gitea-Event': event,
+ 'X-Gitea-Signature': createHmac('sha256', secret).update(JSON.stringify(body)).digest('hex'),
+});
+
+/**
+ * Inbound webhooks are unauthenticated HTTP from the provider. The only thing
+ * standing between the internet and a project's task list is the signature
+ * over the raw body (GitHub, Gitea) or the shared token (GitLab), looked up by
+ * the repository named in the payload.
+ */
+describe('Integrations inbound webhooks', () => {
+ beforeAll(async () => {
+ process.env.ENCRYPTION_KEY ??= 'ab'.repeat(32);
+ server = new App(port).listen();
+ ({ jwt, goalId } = await loginAndCreateGoal(api, `integrations-webhooks-it-${Date.now()}`));
+ });
+
+ afterAll(async () => {
+ await cleanupGoal(api, jwt, goalId);
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ describe('GitHub', () => {
+ const repo = `wh-it/github-${Date.now()}`;
+ let integrationId = 0;
+ const issue = (number: number, extra: Record<string, unknown> = {}) => ({
+ action: 'opened',
+ repository: { full_name: repo },
+ issue: { number, title: `Issue ${number}`, body: `Body ${number}`, ...extra },
+ });
+
+ beforeAll(async () => {
+ integrationId = await insertIntegration({ provider: 'github', projectId: goalId, repoFullName: repo, webhookSecret: SECRET });
+ });
+
+ it('refuses a delivery without a signature', async () => {
+ const body = issue(1);
+ const response = await post('/module/integrations/webhook/github', body, { 'X-GitHub-Event': 'issues' });
+ expect(response.status).toBe(401);
+ expect(await tasksOfGoal(goalId)).toHaveLength(0);
+ });
+
+ it('acknowledges events it does not handle without touching anything', async () => {
+ const body = issue(1);
+ const response = await post('/module/integrations/webhook/github', body, githubHeaders(body, SECRET, 'push'));
+ expect(response.status).toBe(200);
+ expect(await tasksOfGoal(goalId)).toHaveLength(0);
+ });
+
+ it('answers 404 for a repository nobody connected', async () => {
+ const body = { ...issue(1), repository: { full_name: 'nobody/connected-this' } };
+ const response = await post('/module/integrations/webhook/github', body, githubHeaders(body));
+ expect(response.status).toBe(404);
+ });
+
+ it('refuses a signature made with another secret', async () => {
+ const body = issue(1);
+ const response = await post('/module/integrations/webhook/github', body, githubHeaders(body, 'wrong-secret'));
+ expect(response.status).toBe(401);
+ expect(await tasksOfGoal(goalId)).toHaveLength(0);
+ });
+
+ it('refuses a valid signature whose body was tampered with in transit', async () => {
+ const signed = issue(1);
+ const tampered = issue(1, { title: 'Tampered' });
+ const response = await post('/module/integrations/webhook/github', tampered, githubHeaders(signed));
+ expect(response.status).toBe(401);
+ });
+
+ it('creates a task with its mapping when an issue is opened', async () => {
+ const body = issue(1);
+ const response = await post('/module/integrations/webhook/github', body, githubHeaders(body));
+ expect(response.status).toBe(200);
+
+ const tasks = await tasksOfGoal(goalId);
+ expect(tasks).toHaveLength(1);
+ expect(tasks[0]).toMatchObject({ description: 'Issue 1', note: 'Body 1', complete: false, source_url: `https://github.com/${repo}/issues/1` });
+ expect(await mappingsOf(integrationId)).toMatchObject([{ task_id: tasks[0].id, issue_number: 1, issue_state: 'open' }]);
+ });
+
+ it('does not duplicate the task when the same issue is opened again', async () => {
+ const body = issue(1);
+ await post('/module/integrations/webhook/github', body, githubHeaders(body));
+ expect(await tasksOfGoal(goalId)).toHaveLength(1);
+ });
+
+ it('edits the title and note in place', async () => {
+ const body = { ...issue(1, { title: 'Renamed', body: null }), action: 'edited' };
+ await post('/module/integrations/webhook/github', body, githubHeaders(body));
+ expect((await tasksOfGoal(goalId))[0]).toMatchObject({ description: 'Renamed', note: null });
+ });
+
+ it('completes the task when the issue is closed and reopens it afterwards', async () => {
+ const closed = { ...issue(1), action: 'closed' };
+ await post('/module/integrations/webhook/github', closed, githubHeaders(closed));
+ expect((await tasksOfGoal(goalId))[0].complete).toBe(true);
+ expect((await mappingsOf(integrationId))[0].issue_state).toBe('closed');
+
+ const reopened = { ...issue(1), action: 'reopened' };
+ await post('/module/integrations/webhook/github', reopened, githubHeaders(reopened));
+ expect((await tasksOfGoal(goalId))[0].complete).toBe(false);
+ expect((await mappingsOf(integrationId))[0].issue_state).toBe('open');
+ });
+
+ it('ignores state changes for issues it never mapped', async () => {
+ const body = { ...issue(999), action: 'closed' };
+ const response = await post('/module/integrations/webhook/github', body, githubHeaders(body));
+ expect(response.status).toBe(200);
+ expect(await tasksOfGoal(goalId)).toHaveLength(1);
+ });
+
+ it('stops accepting deliveries once the integration is paused', async () => {
+ const toggle = await api.patch('/module/integrations/toggle', { id: integrationId, isActive: false }, {
+ headers: { Authorization: `Bearer ${jwt}` },
+ });
+ expect(toggle.status).toBe(200);
+
+ const body = issue(2);
+ const response = await post('/module/integrations/webhook/github', body, githubHeaders(body));
+ expect(response.status).toBe(404);
+ expect(await tasksOfGoal(goalId)).toHaveLength(1);
+ });
+ });
+
+ describe('Gitea', () => {
+ const repo = `wh-it/gitea-${Date.now()}`;
+ let integrationId = 0;
+ const issue = (number: number, action = 'opened') => ({
+ action,
+ repository: { full_name: repo },
+ issue: { number, title: `Gitea ${number}`, body: null },
+ });
+
+ beforeAll(async () => {
+ integrationId = await insertIntegration({ provider: 'gitea', projectId: goalId, repoFullName: repo, webhookSecret: SECRET });
+ });
+
+ it('refuses a GitHub-style prefixed signature', async () => {
+ const body = issue(1);
+ const headers = giteaHeaders(body);
+ headers['X-Gitea-Signature'] = 'sha256=' + headers['X-Gitea-Signature'];
+ const response = await post('/module/integrations/webhook/gitea', body, headers);
+ expect(response.status).toBe(401);
+ });
+
+ it('creates, closes and reopens through the full lifecycle', async () => {
+ const opened = issue(1);
+ expect((await post('/module/integrations/webhook/gitea', opened, giteaHeaders(opened))).status).toBe(200);
+ const mapping = (await mappingsOf(integrationId))[0];
+ expect(mapping).toMatchObject({ issue_number: 1, issue_state: 'open' });
+
+ const closed = issue(1, 'closed');
+ await post('/module/integrations/webhook/gitea', closed, giteaHeaders(closed));
+ expect((await mappingsOf(integrationId))[0].issue_state).toBe('closed');
+
+ const reopened = issue(1, 'reopened');
+ await post('/module/integrations/webhook/gitea', reopened, giteaHeaders(reopened));
+ expect((await mappingsOf(integrationId))[0].issue_state).toBe('open');
+
+ const task = (await tasksOfGoal(goalId)).find((t) => t.id === mapping.task_id);
+ expect(task).toMatchObject({ description: 'Gitea 1', complete: false, source_url: `https://gitea.com/${repo}/issues/1` });
+ });
+ });
+
+ describe('GitLab', () => {
+ const externalId = String(700_000 + Math.floor(Math.random() * 100_000));
+ let integrationId = 0;
+ const event = (iid: number, action: string, extra: Record<string, unknown> = {}) => ({
+ object_kind: 'issue',
+ project: { id: Number(externalId), path_with_namespace: 'wh-it/gitlab' },
+ object_attributes: { iid, title: `GitLab ${iid}`, description: 'desc', action, ...extra },
+ });
+
+ beforeAll(async () => {
+ integrationId = await insertIntegration({
+ provider: 'gitlab', projectId: goalId, repoFullName: 'wh-it/gitlab', repoExternalId: externalId, webhookSecret: SECRET,
+ });
+ });
+
+ it('refuses a delivery without the token header', async () => {
+ const response = await post('/module/integrations/webhook/gitlab', event(1, 'open'), {});
+ expect(response.status).toBe(401);
+ });
+
+ it('refuses a wrong token', async () => {
+ const response = await post('/module/integrations/webhook/gitlab', event(1, 'open'), { 'X-Gitlab-Token': 'nope' });
+ expect(response.status).toBe(401);
+ expect(await mappingsOf(integrationId)).toHaveLength(0);
+ });
+
+ it('acknowledges non-issue events without changes', async () => {
+ const response = await post('/module/integrations/webhook/gitlab', { ...event(1, 'open'), object_kind: 'push' }, { 'X-Gitlab-Token': SECRET });
+ expect(response.status).toBe(200);
+ expect(await mappingsOf(integrationId)).toHaveLength(0);
+ });
+
+ it('finds the integration by the numeric project id, not the path', async () => {
+ const response = await post('/module/integrations/webhook/gitlab', event(1, 'open'), { 'X-Gitlab-Token': SECRET });
+ expect(response.status).toBe(200);
+
+ const mapping = (await mappingsOf(integrationId))[0];
+ expect(mapping).toMatchObject({ issue_number: 1, issue_state: 'open' });
+ const task = (await tasksOfGoal(goalId)).find((t) => t.id === mapping.task_id);
+ expect(task).toMatchObject({ description: 'GitLab 1', note: 'desc', source_url: `https://gitlab.com/wh-it/gitlab/-/issues/1` });
+ });
+
+ it('updates, closes and reopens with GitLab action names', async () => {
+ await post('/module/integrations/webhook/gitlab', event(1, 'update', { title: 'GitLab renamed' }), { 'X-Gitlab-Token': SECRET });
+ const mapping = (await mappingsOf(integrationId))[0];
+ expect((await tasksOfGoal(goalId)).find((t) => t.id === mapping.task_id)?.description).toBe('GitLab renamed');
+
+ await post('/module/integrations/webhook/gitlab', event(1, 'close'), { 'X-Gitlab-Token': SECRET });
+ expect((await mappingsOf(integrationId))[0].issue_state).toBe('closed');
+
+ await post('/module/integrations/webhook/gitlab', event(1, 'reopen'), { 'X-Gitlab-Token': SECRET });
+ expect((await mappingsOf(integrationId))[0].issue_state).toBe('open');
+ });
+ });
+});
diff --git a/api/src/tv-modules/integrations/__tests__/providers.test.ts b/api/src/tv-modules/integrations/__tests__/providers.test.ts
new file mode 100644
index 0000000..7eca25b
--- /dev/null
+++ b/api/src/tv-modules/integrations/__tests__/providers.test.ts
@@ -0,0 +1,299 @@
+import { afterEach, beforeAll, describe, expect, it } from 'vitest'
+import nock from 'nock'
+import { createHmac } from 'crypto'
+import {
+ createGitHubWebhook,
+ exchangeGitHubCode,
+ fetchGitHubIssues,
+ fetchGitHubRepos,
+ getGitHubOAuthUrl,
+ updateGitHubIssueState,
+ verifyGitHubWebhookSignature,
+} from '../providers/github.provider'
+import {
+ createGitLabWebhook,
+ exchangeGitLabCode,
+ fetchGitLabIssues,
+ fetchGitLabRepos,
+ getGitLabOAuthUrl,
+ refreshGitLabToken,
+ updateGitLabIssueState,
+ verifyGitLabWebhookToken,
+} from '../providers/gitlab.provider'
+import {
+ createGiteaWebhook,
+ exchangeGiteaCode,
+ fetchGiteaIssues,
+ fetchGiteaRepos,
+ getGiteaOAuthUrl,
+ refreshGiteaToken,
+ updateGiteaIssueState,
+ verifyGiteaToken,
+ verifyGiteaWebhookSignature,
+} from '../providers/gitea.provider'
+
+const GITHUB = 'https://github.com'
+const GITHUB_API = 'https://api.github.com'
+const GITLAB = 'https://gitlab.com'
+const GITLAB_API = 'https://gitlab.com/api/v4'
+const GITEA = 'https://gitea.com'
+const GITEA_API = 'https://gitea.com/api/v1'
+
+const fill = <T>(count: number, make: (i: number) => T): T[] => Array.from({ length: count }, (_, i) => make(i))
+
+beforeAll(() => {
+ nock.disableNetConnect()
+ Object.assign(process.env, {
+ GITHUB_INTEGRATION_CLIENT_ID: 'gh-id',
+ GITHUB_INTEGRATION_CLIENT_SECRET: 'gh-secret',
+ GITHUB_INTEGRATION_CALLBACK_URL: 'https://api.test/module/integrations/oauth/github/callback',
+ GITLAB_INTEGRATION_CLIENT_ID: 'gl-id',
+ GITLAB_INTEGRATION_CLIENT_SECRET: 'gl-secret',
+ GITLAB_INTEGRATION_CALLBACK_URL: 'https://api.test/module/integrations/oauth/gitlab/callback',
+ GITEA_INTEGRATION_CLIENT_ID: 'gt-id',
+ GITEA_INTEGRATION_CLIENT_SECRET: 'gt-secret',
+ GITEA_INTEGRATION_CALLBACK_URL: 'https://api.test/module/integrations/oauth/gitea/callback',
+ })
+})
+
+afterEach(() => {
+ expect(nock.pendingMocks()).toEqual([])
+ nock.cleanAll()
+})
+
+describe('OAuth authorization URLs', () => {
+ it('GitHub asks for the repo scope and carries the state', () => {
+ const url = new URL(getGitHubOAuthUrl('the-state'))
+ expect(url.origin + url.pathname).toBe(`${GITHUB}/login/oauth/authorize`)
+ expect(url.searchParams.get('client_id')).toBe('gh-id')
+ expect(url.searchParams.get('redirect_uri')).toBe(process.env.GITHUB_INTEGRATION_CALLBACK_URL)
+ expect(url.searchParams.get('scope')).toBe('repo')
+ expect(url.searchParams.get('state')).toBe('the-state')
+ })
+
+ it('GitLab asks for the api scope with response_type=code', () => {
+ const url = new URL(getGitLabOAuthUrl('s'))
+ expect(url.origin + url.pathname).toBe(`${GITLAB}/oauth/authorize`)
+ expect(url.searchParams.get('response_type')).toBe('code')
+ expect(url.searchParams.get('scope')).toBe('api')
+ expect(url.searchParams.get('state')).toBe('s')
+ })
+
+ it('Gitea uses its login/oauth path', () => {
+ const url = new URL(getGiteaOAuthUrl('s'))
+ expect(url.origin + url.pathname).toBe(`${GITEA}/login/oauth/authorize`)
+ expect(url.searchParams.get('response_type')).toBe('code')
+ expect(url.searchParams.get('client_id')).toBe('gt-id')
+ })
+
+ it.each([
+ ['GitHub', 'GITHUB_INTEGRATION_CLIENT_ID', () => getGitHubOAuthUrl('s')],
+ ['GitLab', 'GITLAB_INTEGRATION_CALLBACK_URL', () => getGitLabOAuthUrl('s')],
+ ['Gitea', 'GITEA_INTEGRATION_CLIENT_ID', () => getGiteaOAuthUrl('s')],
+ ])('%s refuses to build a URL when the integration is not configured', (_name, envKey, build) => {
+ const saved = process.env[envKey]
+ delete process.env[envKey]
+ expect(build).toThrow('not configured')
+ process.env[envKey] = saved
+ })
+})
+
+describe('code exchange and refresh', () => {
+ it('GitHub posts client credentials and returns the access token', async () => {
+ nock(GITHUB)
+ .post('/login/oauth/access_token', { client_id: 'gh-id', client_secret: 'gh-secret', code: 'c0de' })
+ .matchHeader('accept', 'application/json')
+ .reply(200, { access_token: 'gh-token', token_type: 'bearer' })
+
+ expect(await exchangeGitHubCode('c0de')).toBe('gh-token')
+ })
+
+ it('GitHub rejects a reply without an access token', async () => {
+ nock(GITHUB).post('/login/oauth/access_token').reply(200, { error: 'bad_verification_code' })
+ await expect(exchangeGitHubCode('c0de')).rejects.toThrow('Failed to exchange GitHub code')
+ })
+
+ it('GitLab exchanges with grant_type and redirect_uri and keeps the refresh token', async () => {
+ nock(GITLAB)
+ .post('/oauth/token', (body) =>
+ body.grant_type === 'authorization_code'
+ && body.code === 'c0de'
+ && body.redirect_uri === process.env.GITLAB_INTEGRATION_CALLBACK_URL)
+ .reply(200, { access_token: 'gl-a', refresh_token: 'gl-r', token_type: 'bearer' })
+
+ expect(await exchangeGitLabCode('c0de')).toEqual({ accessToken: 'gl-a', refreshToken: 'gl-r' })
+ })
+
+ it('GitLab refreshes with grant_type=refresh_token', async () => {
+ nock(GITLAB)
+ .post('/oauth/token', (body) => body.grant_type === 'refresh_token' && body.refresh_token === 'old-r')
+ .reply(200, { access_token: 'new-a', refresh_token: 'new-r', token_type: 'bearer' })
+
+ expect(await refreshGitLabToken('old-r')).toEqual({ accessToken: 'new-a', refreshToken: 'new-r' })
+ })
+
+ it('GitLab surfaces a failed refresh', async () => {
+ nock(GITLAB).post('/oauth/token').reply(200, {})
+ await expect(refreshGitLabToken('old-r')).rejects.toThrow('Failed to refresh GitLab token')
+ })
+
+ it('Gitea tolerates a reply without a refresh token', async () => {
+ nock(GITEA)
+ .post('/login/oauth/access_token', (body) => body.grant_type === 'authorization_code' && body.code === 'c0de')
+ .reply(200, { access_token: 'gt-a', token_type: 'bearer' })
+
+ expect(await exchangeGiteaCode('c0de')).toEqual({ accessToken: 'gt-a', refreshToken: null })
+ })
+
+ it('Gitea refreshes and probes the token via /user', async () => {
+ nock(GITEA)
+ .post('/login/oauth/access_token', (body) => body.grant_type === 'refresh_token')
+ .reply(200, { access_token: 'gt-new', refresh_token: 'gt-new-r', token_type: 'bearer' })
+ nock(GITEA_API).get('/user').matchHeader('authorization', 'Bearer gt-new').reply(200, { id: 1 })
+
+ expect(await refreshGiteaToken('gt-r')).toEqual({ accessToken: 'gt-new', refreshToken: 'gt-new-r' })
+ await expect(verifyGiteaToken('gt-new')).resolves.toBeUndefined()
+ })
+})
+
+describe('repository listing', () => {
+ it('GitHub walks every page until a short one and sends the bearer token', async () => {
+ const page1 = fill(100, (i) => ({ id: i, full_name: `o/r${i}`, name: `r${i}`, private: false, description: null, html_url: '' }))
+ nock(GITHUB_API)
+ .get('/user/repos').query((q) => q.page === '1' && q.per_page === '100')
+ .matchHeader('authorization', 'Bearer t')
+ .reply(200, page1)
+ .get('/user/repos').query((q) => q.page === '2')
+ .reply(200, page1.slice(0, 3))
+
+ expect(await fetchGitHubRepos('t')).toHaveLength(103)
+ })
+
+ it('GitLab lists only projects the user is a member of', async () => {
+ nock(GITLAB_API)
+ .get('/projects').query((q) => q.membership === 'true' && q.page === '1')
+ .reply(200, [{ id: 1, path_with_namespace: 'g/p', name: 'p', visibility: 'private', description: null, web_url: '' }])
+
+ expect(await fetchGitLabRepos('t')).toHaveLength(1)
+ })
+
+ it('Gitea pages by 50', async () => {
+ const page = fill(50, (i) => ({ id: i, full_name: `o/r${i}`, name: `r${i}`, private: false, description: null, html_url: '' }))
+ nock(GITEA_API)
+ .get('/user/repos').query((q) => q.limit === '50' && q.page === '1').reply(200, page)
+ .get('/user/repos').query((q) => q.page === '2').reply(200, [])
+
+ expect(await fetchGiteaRepos('t')).toHaveLength(50)
+ })
+})
+
+describe('issue listing', () => {
+ it('GitHub drops pull requests and asks for all states', async () => {
+ nock(GITHUB_API)
+ .get('/repos/o/r/issues').query((q) => q.state === 'all' && q.sort === 'created' && q.since === undefined)
+ .reply(200, [
+ { number: 1, title: 'issue', body: null, state: 'open', html_url: '' },
+ { number: 2, title: 'pr', body: null, state: 'open', html_url: '', pull_request: {} },
+ ])
+
+ const issues = await fetchGitHubIssues('t', 'o/r')
+ expect(issues.map((i) => i.number)).toEqual([1])
+ })
+
+ it('GitHub switches to updated ordering when a since is given', async () => {
+ nock(GITHUB_API)
+ .get('/repos/o/r/issues').query((q) => q.sort === 'updated' && q.since === '2026-01-01T00:00:00.000Z')
+ .reply(200, [])
+
+ expect(await fetchGitHubIssues('t', 'o/r', '2026-01-01T00:00:00.000Z')).toEqual([])
+ })
+
+ it('GitLab filters by updated_after for incremental syncs', async () => {
+ nock(GITLAB_API)
+ .get('/projects/77/issues').query((q) => q.order_by === 'updated_at' && q.updated_after === '2026-01-01')
+ .reply(200, [{ iid: 5, title: 't', description: null, state: 'opened', web_url: '' }])
+
+ expect(await fetchGitLabIssues('t', 77, '2026-01-01')).toHaveLength(1)
+ })
+
+ it('Gitea excludes pull requests server-side with type=issues', async () => {
+ nock(GITEA_API)
+ .get('/repos/o/r/issues').query((q) => q.type === 'issues' && q.state === 'all' && q.limit === '50')
+ .reply(200, [{ number: 1, title: 't', body: null, state: 'closed', html_url: '' }])
+
+ expect(await fetchGiteaIssues({ accessToken: 't', repoFullName: 'o/r' })).toHaveLength(1)
+ })
+})
+
+describe('webhook registration and issue state', () => {
+ it('GitHub registers an issues webhook carrying the secret', async () => {
+ nock(GITHUB_API)
+ .post('/repos/o/r/hooks', (body) =>
+ body.events.includes('issues') && body.config.secret === 's3cret' && body.config.url === 'https://api.test/wh')
+ .reply(201, { id: 42 })
+
+ expect(await createGitHubWebhook('t', 'o/r', 'https://api.test/wh', 's3cret')).toEqual({ id: 42 })
+ })
+
+ it('GitLab registers with issues_events and the token', async () => {
+ nock(GITLAB_API)
+ .post('/projects/77/hooks', (body) => body.issues_events === true && body.token === 's3cret')
+ .reply(201, { id: 7 })
+
+ expect(await createGitLabWebhook('t', 77, 'https://api.test/wh', 's3cret')).toEqual({ id: 7 })
+ })
+
+ it('Gitea registers a gitea-type hook', async () => {
+ nock(GITEA_API)
+ .post('/repos/o/r/hooks', (body) => body.type === 'gitea' && body.config.secret === 's3cret')
+ .reply(201, { id: 9 })
+
+ expect(await createGiteaWebhook({ accessToken: 't', repoFullName: 'o/r', webhookUrl: 'https://api.test/wh', secret: 's3cret' })).toEqual({ id: 9 })
+ })
+
+ it('GitHub closes an issue with state, GitLab with state_event, Gitea with state', async () => {
+ nock(GITHUB_API).patch('/repos/o/r/issues/3', { state: 'closed' }).reply(200, {})
+ nock(GITLAB_API).put('/projects/77/issues/3', { state_event: 'reopen' }).reply(200, {})
+ nock(GITEA_API).patch('/repos/o/r/issues/3', { state: 'closed' }).reply(200, {})
+
+ await updateGitHubIssueState('t', 'o/r', 3, 'closed')
+ await updateGitLabIssueState('t', 77, 3, 'reopen')
+ await updateGiteaIssueState({ accessToken: 't', repoFullName: 'o/r', issueNumber: 3, state: 'closed' })
+ })
+})
+
+describe('webhook signature verification', () => {
+ const body = Buffer.from('{"action":"opened"}')
+ const secret = 'whsec'
+ const hex = createHmac('sha256', secret).update(body).digest('hex')
+
+ it('GitHub accepts the sha256= signature over the raw body', () => {
+ expect(verifyGitHubWebhookSignature(body, `sha256=${hex}`, secret)).toBe(true)
+ })
+
+ it('GitHub rejects a signature computed with another secret', () => {
+ const other = createHmac('sha256', 'nope').update(body).digest('hex')
+ expect(verifyGitHubWebhookSignature(body, `sha256=${other}`, secret)).toBe(false)
+ })
+
+ it('GitHub rejects a signature of the wrong length instead of throwing', () => {
+ expect(verifyGitHubWebhookSignature(body, 'sha256=abc', secret)).toBe(false)
+ expect(verifyGitHubWebhookSignature(body, '', secret)).toBe(false)
+ })
+
+ it('GitHub rejects a valid digest for a different body', () => {
+ expect(verifyGitHubWebhookSignature(Buffer.from('{"action":"closed"}'), `sha256=${hex}`, secret)).toBe(false)
+ })
+
+ it('Gitea uses the bare hex digest', () => {
+ expect(verifyGiteaWebhookSignature({ rawBody: body, signature: hex, secret })).toBe(true)
+ expect(verifyGiteaWebhookSignature({ rawBody: body, signature: `sha256=${hex}`, secret })).toBe(false)
+ expect(verifyGiteaWebhookSignature({ rawBody: body, signature: 'zz', secret })).toBe(false)
+ })
+
+ it('GitLab compares the plain token', () => {
+ expect(verifyGitLabWebhookToken('whsec', 'whsec')).toBe(true)
+ expect(verifyGitLabWebhookToken('whsec ', 'whsec')).toBe(false)
+ expect(verifyGitLabWebhookToken('', 'whsec')).toBe(false)
+ })
+})
diff --git a/api/src/tv-modules/integrations/__tests__/support.ts b/api/src/tv-modules/integrations/__tests__/support.ts
new file mode 100644
index 0000000..21e0c55
--- /dev/null
+++ b/api/src/tv-modules/integrations/__tests__/support.ts
@@ -0,0 +1,103 @@
+import axios, { type AxiosInstance } from 'axios';
+import http from 'http';
+import { Database } from '../../../modules/db';
+import { encrypt } from '../../../utils/crypto';
+import type { IntegrationProvider } from '../types';
+
+export const TEST_LOGIN = '[email protected]';
+export const TEST_PASSWORD = 'user1!#Q';
+
+export type InsertIntegrationArgs = {
+ provider: IntegrationProvider;
+ projectId: number;
+ repoFullName?: string | null;
+ repoExternalId?: string | null;
+ accessToken?: string | null;
+ refreshToken?: string | null;
+ webhookSecret?: string | null;
+ isActive?: boolean;
+};
+
+export type TaskRow = { id: number; description: string; note: string | null; complete: boolean; kanban_order: number; source_url: string | null };
+export type MappingRow = { id: number; task_id: number; issue_number: number; issue_state: string };
+export type IntegrationRow = {
+ id: number; provider: string; access_token_encrypted: string | null; refresh_token_encrypted: string | null;
+ repo_full_name: string | null; last_synced_at: Date | null;
+};
+
+export function createApi(port: number): AxiosInstance {
+ return axios.create({
+ baseURL: `http://localhost:${port}`,
+ validateStatus: () => true,
+ maxRedirects: 0,
+ httpAgent: new http.Agent({ keepAlive: false }),
+ });
+}
+
+export async function loginAndCreateGoal(api: AxiosInstance, name: string): Promise<{ jwt: string; goalId: number }> {
+ const login = await api.post('/module/auth/login', { login: TEST_LOGIN, password: TEST_PASSWORD });
+ if (login.status !== 200) throw new Error(`login failed: ${login.status}`);
+ const jwt = login.data.access as string;
+
+ const goal = await api.post('/module/goals', { name }, { headers: { Authorization: `Bearer ${jwt}` } });
+ if (goal.status !== 200) throw new Error(`goal creation failed: ${goal.status}`);
+ const goalId = (goal.data.response.id ?? goal.data.response.goal?.id) as number;
+ return { jwt, goalId };
+}
+
+export async function cleanupGoal(api: AxiosInstance, jwt: string, goalId: number): Promise<void> {
+ const db = Database.getInstance();
+ // Integrations cascade to their mappings; tasks have no FK to the goal, so
+ // the rows a sync or webhook created are removed explicitly.
+ await db.query('DELETE FROM tasks.integrations WHERE project_id = $1', [goalId]);
+ await db.query('DELETE FROM tasks.tasks WHERE goal_id = $1', [goalId]);
+ await api.delete('/module/goals', { headers: { Authorization: `Bearer ${jwt}` }, data: { goalId } });
+}
+
+export async function insertIntegration(args: InsertIntegrationArgs): Promise<number> {
+ const db = Database.getInstance();
+ const result = await db.query<{ id: number }>(
+ `INSERT INTO tasks.integrations
+ (provider, project_id, repo_full_name, repo_external_id, access_token_encrypted, refresh_token_encrypted, webhook_secret_encrypted, is_active)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ RETURNING id`,
+ [
+ args.provider,
+ args.projectId,
+ args.repoFullName ?? null,
+ args.repoExternalId ?? null,
+ args.accessToken ? encrypt(args.accessToken) : null,
+ args.refreshToken ? encrypt(args.refreshToken) : null,
+ args.webhookSecret ? encrypt(args.webhookSecret) : null,
+ args.isActive ?? true,
+ ],
+ );
+ return result.rows[0].id;
+}
+
+export async function tasksOfGoal(goalId: number): Promise<TaskRow[]> {
+ const db = Database.getInstance();
+ const result = await db.query<TaskRow>(
+ 'SELECT id, description, note, complete, kanban_order, source_url FROM tasks.tasks WHERE goal_id = $1 ORDER BY id',
+ [goalId],
+ );
+ return result.rows;
+}
+
+export async function mappingsOf(integrationId: number): Promise<MappingRow[]> {
+ const db = Database.getInstance();
+ const result = await db.query<MappingRow>(
+ 'SELECT id, task_id, issue_number, issue_state FROM tasks.integration_task_map WHERE integration_id = $1 ORDER BY issue_number',
+ [integrationId],
+ );
+ return result.rows;
+}
+
+export async function integrationsOfGoal(goalId: number): Promise<IntegrationRow[]> {
+ const db = Database.getInstance();
+ const result = await db.query<IntegrationRow>(
+ 'SELECT id, provider, access_token_encrypted, refresh_token_encrypted, repo_full_name, last_synced_at FROM tasks.integrations WHERE project_id = $1 ORDER BY id',
+ [goalId],
+ );
+ return result.rows;
+}
diff --git a/api/src/tv-modules/integrations/types.ts b/api/src/tv-modules/integrations/types.ts
index 2627848..c4c947d 100644
--- a/api/src/tv-modules/integrations/types.ts
+++ b/api/src/tv-modules/integrations/types.ts
@@ -1,4 +1,6 @@
import { type } from 'arktype';
+import type { Request } from 'express';
+import type { AppUser } from '../../core/AppUser';
export const IntegrationsArkTypeAdd = type({
provider: "'github' | 'gitlab' | 'gitea'",
@@ -30,12 +32,37 @@ export const IntegrationsArkTypeSelectRepo = type({
});
export type IntegrationsArgSelectRepo = typeof IntegrationsArkTypeSelectRepo.infer;
-export type IntegrationProvider = 'github' | 'gitlab' | 'gitea';
+export const IntegrationProviderArkType = type("'github' | 'gitlab' | 'gitea'");
+export type IntegrationProvider = typeof IntegrationProviderArkType.infer;
+
+export const INTEGRATIONS_OAUTH_NONCE_COOKIE = 'tv_integrations_oauth';
+export const INTEGRATIONS_OAUTH_NONCE_PATH = '/module/integrations/oauth';
+export const INTEGRATIONS_OAUTH_STATE_TTL_SECONDS = 600;
export type OAuthStatePayload = {
userId: number;
projectId: number;
provider: IntegrationProvider;
+ nonceHash: string;
+};
+
+export type GetOAuthUrlArgs = {
+ provider: IntegrationProvider;
+ projectId: number;
+ userId: number;
+ nonce: string;
+};
+
+export type VerifyOAuthStateArgs = {
+ provider: IntegrationProvider;
+ state: string;
+ nonce: string | undefined;
+};
+
+export type CompleteOAuthCallbackArgs = {
+ provider: IntegrationProvider;
+ code: string;
+ payload: OAuthStatePayload;
};
export type GiteaFetchIssuesArgs = {
@@ -77,3 +104,13 @@ export type RepoItemForClient = {
description: string | null;
url: string;
};
+
+export type CanManageIntegrationsArgs = {
+ user: AppUser;
+ projectId: number;
+};
+
+export type AppUserFromIdArgs = {
+ req: Request;
+ userId: number;
+};