Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5088: import repositories from GitHub App (#5896)
Multica Eveaa110aac9c1f
diff --git a/.env.example b/.env.exampleindex a7949ee5ad..418e191277 100644--- a/.env.example+++ b/.env.example@@ -258,11 +258,11 @@ CORS_ALLOWED_ORIGINS=# GITHUB_APP_SLUG is the tail of https://github.com/apps/<slug>.GITHUB_APP_SLUG=GITHUB_WEBHOOK_SECRET=-# Optional: GitHub App identity for App-authenticated REST calls. When set,-# the setup callback enriches the installation row with the real account-# login (org / user name) immediately after install. When unset, the row-# is created with the "unknown" placeholder and the next `installation`-# webhook from GitHub overwrites it — set both to skip that interim flash.+# Optional for webhook-only deployments, but required for PR-card CI /+# mergeability and Settings → Repositories → Choose from GitHub. These+# credentials let the server authenticate as the App, mint short-lived+# installation tokens, and enrich the installation row with the real account+# login immediately.# GITHUB_APP_ID is the numeric "App ID" shown on the App's settings page.# GITHUB_APP_PRIVATE_KEY is the full PEM block (including BEGIN/END lines)# generated under "Private keys" on that same page; preserve newlines.diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex ed5f3d2ed5..c31e26e818 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -251,8 +251,8 @@ multica config set auto_update_check_interval 12h|---|---|---|| `GITHUB_APP_SLUG` | 空 | GitHub App の slug(`https://github.com/apps/<slug>` の末尾部分)。設定 → GitHub のインストールボタン URL を構成します || `GITHUB_WEBHOOK_SECRET` | 空 | GitHub App に設定した Webhook secret。すべての `pull_request` / `installation` delivery の HMAC-SHA256 検証に使われ、setup コールバックの state token の HMAC キーとしても使われます |-| `GITHUB_APP_ID` | 空 | App 設定ページに表示される数値の App ID。`GITHUB_APP_PRIVATE_KEY` と併せて、PR カードの CI ステータスとマージ可否に必須で、インストール時点で連携先のアカウント名を取得するためにも使われます |-| `GITHUB_APP_PRIVATE_KEY` | 空 | App の RSA 秘密鍵の完全な PEM ブロック(`-----BEGIN/END-----` 行を含み、改行を保ったまま)。`GITHUB_APP_ID` と併せて、App として認証し、PR カードの CI ステータスとマージ可否の基になる GitHub API スナップショットを取得するために使われます |+| `GITHUB_APP_ID` | 空 | App 設定ページに表示される数値の App ID。`GITHUB_APP_PRIVATE_KEY` と併せて、PR カードの CI ステータスとマージ可否、Settings → Repositories → GitHub から選択する機能、インストール時の連携先アカウント名取得に使われます |+| `GITHUB_APP_PRIVATE_KEY` | 空 | App の RSA 秘密鍵の完全な PEM ブロック(`-----BEGIN/END-----` 行を含み、改行を保持)。`GITHUB_APP_ID` と併せて、App 認証による PR スナップショットとリポジトリ参照に使われます |**いずれかの必須変数が設定されていない場合の動作:**@@ -263,6 +263,7 @@ multica config set auto_update_check_interval 12h- PR カードに **CI ステータスもマージ可否も表示されません** — 連携はきれいに縮退します: PR は引き続きミラーリングされ、イシューは引き続き自動で紐づき、マージ時に Done へ移動します。- インストール直後、接続カードには一時的に `Connected to unknown` とも表示されます。GitHub から `installation.created` webhook が届くと(通常は数秒以内)、Multica は行を実際の組織名/ユーザー名に更新し、リアルタイムブロードキャストを発行するため、開いている Settings → GitHub タブは手動更新なしで反映されます。+- サーバーがリポジトリ一覧に必要な installation token を発行できないため、Settings → Repositories → GitHub から選択する機能は無効になります。**注:** `GITHUB_WEBHOOK_SECRET` はインストールフローの state token の署名キーとして再利用されるため、運用者は secret を 1 つだけ管理すればよいです。これは GitHub App の *Client* secret では**ありません** — Client secret は OAuth 関連であり、この連携では使われません。完全な手順は [GitHub 連携 → セルフホストのセットアップ](/github-integration#self-host-setup)を参照してください。diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex 0217e97fd3..1715a218ac 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -251,8 +251,8 @@ multica config set auto_update_check_interval 12h|---|---|---|| `GITHUB_APP_SLUG` | 비어 있음 | GitHub App의 slug (`https://github.com/apps/<slug>`의 끝부분). 설정 → GitHub 설치 버튼 URL을 구성합니다 || `GITHUB_WEBHOOK_SECRET` | 비어 있음 | GitHub App에 설정한 Webhook secret. 모든 `pull_request` / `installation` delivery의 HMAC-SHA256 검증에 사용되며, setup 콜백 state token의 HMAC 키로도 사용됩니다 |-| `GITHUB_APP_ID` | 비어 있음 | App 설정 페이지에 표시되는 숫자 App ID. `GITHUB_APP_PRIVATE_KEY`와 함께, PR 카드의 CI 상태와 머지 가능 여부에 필수이며, 설치 시점에 연결된 계정 이름을 가져오는 데에도 사용됩니다 |-| `GITHUB_APP_PRIVATE_KEY` | 비어 있음 | App RSA 비공개 키의 전체 PEM 블록 (`-----BEGIN/END-----` 줄 포함, 줄바꿈 유지). `GITHUB_APP_ID`와 함께, App으로 인증하고 PR 카드의 CI 상태와 머지 가능 여부의 기반이 되는 GitHub API 스냅샷을 가져오는 데 사용됩니다 |+| `GITHUB_APP_ID` | 비어 있음 | App 설정 페이지에 표시되는 숫자 App ID. `GITHUB_APP_PRIVATE_KEY`와 함께 PR 카드의 CI 상태와 머지 가능 여부, Settings → Repositories → GitHub에서 선택 기능, 설치 시 연결된 계정 이름 가져오기에 사용됩니다 |+| `GITHUB_APP_PRIVATE_KEY` | 비어 있음 | App RSA 비공개 키의 전체 PEM 블록(`-----BEGIN/END-----` 줄 포함, 줄바꿈 유지). `GITHUB_APP_ID`와 함께 App 인증 PR 스냅샷과 저장소 탐색에 사용됩니다 |**필수 변수 중 하나라도 설정하지 않았을 때의 동작:**@@ -263,6 +263,7 @@ multica config set auto_update_check_interval 12h- PR 카드에 **CI 상태도 머지 가능 여부도 표시되지 않습니다** — 연동은 깔끔하게 축소됩니다: PR은 계속 미러링되고, 이슈는 계속 자동 연결되며 머지 시 Done으로 이동합니다.- 설치 직후 연결 카드에 잠시 `Connected to unknown`도 표시됩니다. GitHub의 `installation.created` 웹훅이 도착하면(보통 몇 초 이내) Multica가 행을 실제 조직/사용자 이름으로 갱신하고 실시간 브로드캐스트를 보내, 열려 있는 Settings → GitHub 탭이 수동 새로고침 없이 업데이트됩니다.+- 서버가 저장소 목록에 필요한 installation token을 발급할 수 없으므로 Settings → Repositories → GitHub에서 선택 기능이 비활성화됩니다.**참고:** `GITHUB_WEBHOOK_SECRET`은 설치 흐름 state token의 서명 키로 재사용되므로, 운영자는 secret 하나만 관리하면 됩니다. 이것은 GitHub App의 *Client* secret이 **아닙니다** — Client secret은 OAuth 관련이며 이 연동에서는 사용되지 않습니다. 전체 안내는 [GitHub 연동 → 자체 호스팅 설정](/github-integration#self-host-setup)을 참고하세요.diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 6fa608d247..2dc709a894 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -256,8 +256,8 @@ The [GitHub PR ↔ issue integration](/github-integration) needs `GITHUB_APP_SLU|---|---|---|| `GITHUB_APP_SLUG` | empty | The slug of your GitHub App (the tail of `https://github.com/apps/<slug>`). Drives the Settings → GitHub install button URL || `GITHUB_WEBHOOK_SECRET` | empty | The Webhook secret you set on the GitHub App. Used for HMAC-SHA256 verification of every `pull_request` / `installation` delivery, and as the HMAC key for the setup-callback state token |-| `GITHUB_APP_ID` | empty | Numeric App ID from the App's settings page. Required (with `GITHUB_APP_PRIVATE_KEY`) for the PR card's CI status and mergeability, and to fetch the connected account name on install |-| `GITHUB_APP_PRIVATE_KEY` | empty | Full PEM block of the App's RSA private key (including `-----BEGIN/END-----` lines, newlines preserved). Required (with `GITHUB_APP_ID`) to authenticate as the App and pull the GitHub API snapshot behind the PR card's CI status and mergeability |+| `GITHUB_APP_ID` | empty | Numeric App ID from the App's settings page. Required (with `GITHUB_APP_PRIVATE_KEY`) for PR-card CI status and mergeability, Settings → Repositories → Choose from GitHub, and fetching the connected account name on install |+| `GITHUB_APP_PRIVATE_KEY` | empty | Full App RSA private-key PEM block (including `-----BEGIN/END-----` lines, newlines preserved). Required (with `GITHUB_APP_ID`) for App-authenticated PR snapshots and repository browsing |**Behavior when either of the required variables is unset:**@@ -268,6 +268,7 @@ The [GitHub PR ↔ issue integration](/github-integration) needs `GITHUB_APP_SLU- The PR card shows **no CI status or mergeability** — the integration degrades cleanly: PRs still mirror, and issues still auto-link and move to Done on merge.- The connection card also briefly shows `Connected to unknown` after install. Multica refreshes the row to the real org/user name as soon as GitHub delivers the `installation.created` webhook (typically within a few seconds), and broadcasts a realtime update so any open Settings → GitHub tab reflects the change without a manual refresh.+- Settings → Repositories → Choose from GitHub is disabled because the server cannot mint the installation token needed to list repositories.**Note:** `GITHUB_WEBHOOK_SECRET` is reused as the signing key for the install-flow state token, so operators only need to manage one secret. It is **not** the GitHub App's *Client* secret — Client secrets are OAuth-related and not used by this integration. See [GitHub integration → Self-host setup](/github-integration#self-host-setup) for the full walkthrough.diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex 2791bbbc16..0151c0daf0 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -256,8 +256,8 @@ multica config set auto_update_check_interval 12h|---|---|---|| `GITHUB_APP_SLUG` | 空 | 你的 GitHub App slug(`https://github.com/apps/<slug>` 的尾部)。Settings → GitHub 里安装按钮的跳转 URL 用它拼 || `GITHUB_WEBHOOK_SECRET` | 空 | 你在 GitHub App 上设置的 Webhook secret。每条 `pull_request` / `installation` delivery 都用它做 HMAC-SHA256 校验;同一个值也用作 setup 回调里 state token 的签名密钥 |-| `GITHUB_APP_ID` | 空 | App 设置页上的数字 App ID。配合 `GITHUB_APP_PRIVATE_KEY`,是 PR 卡片 CI 状态与可合并性的必填项,同时也用于在安装那一刻直接从 GitHub 取到关联账号名 |-| `GITHUB_APP_PRIVATE_KEY` | 空 | App RSA 私钥的完整 PEM 块(包含 `-----BEGIN/END-----` 两行,保留换行)。配合 `GITHUB_APP_ID`,用于以 App 身份鉴权并拉取 PR 卡片 CI 状态与可合并性背后的 GitHub API 快照 |+| `GITHUB_APP_ID` | 空 | App 设置页上的数字 App ID。配合 `GITHUB_APP_PRIVATE_KEY`,用于 PR 卡片 CI 状态与可合并性、Settings → Repositories → 从 GitHub 选择,以及安装时直接获取关联账号名 |+| `GITHUB_APP_PRIVATE_KEY` | 空 | App RSA 私钥的完整 PEM 块(包含 `-----BEGIN/END-----` 两行,保留换行)。配合 `GITHUB_APP_ID`,用于 App 鉴权的 PR 快照和仓库浏览 |**任一必填变量未设时:**@@ -268,6 +268,7 @@ multica config set auto_update_check_interval 12h- PR 卡片**不显示任何 CI 状态或可合并性**——集成干净降级:PR 照常镜像,issue 照常自动关联并在 merge 时转 Done。- 安装完成后,连接卡片还会先短暂显示 `已连接到 unknown`。等 GitHub 的 `installation.created` webhook 到达(通常几秒内),Multica 会把 row 刷成真实的组织/用户名,并通过 realtime 推送让正在打开的 Settings → GitHub 页面无需手动刷新即可更新。+- Settings → Repositories → 从 GitHub 选择会被禁用,因为服务端无法签发列出仓库所需的 installation token。**注意:** `GITHUB_WEBHOOK_SECRET` 同时被复用为 install 流程里 state token 的签名密钥,所以运维只需要维护一个 secret。它**不是** GitHub App 的 *Client* secret——Client secret 是 OAuth 用的,和本集成无关。完整配置流程见 [GitHub 集成 → Self-Host 配置](/github-integration#self-host-配置)。diff --git a/apps/docs/content/docs/github-integration.ja.mdx b/apps/docs/content/docs/github-integration.ja.mdxindex 14436f6b2b..73a89412bd 100644--- a/apps/docs/content/docs/github-integration.ja.mdx+++ b/apps/docs/content/docs/github-integration.ja.mdx@@ -149,7 +149,7 @@ GITHUB_APP_PRIVATE_KEY=<BEGIN/END 行を含む完全な PEM ブロック>- Settings の `Connect GitHub` が**無効**になり、「not configured」のヒントが表示されます。- `/api/webhooks/github` エンドポイントが **`503 github webhooks not configured`** を返します — Multica は secret なしでイベントを処理することを拒否し、すべての署名を黙って有効として扱うことはありません。-`GITHUB_APP_ID` と `GITHUB_APP_PRIVATE_KEY` は現在、**PR カードの CI ステータスとマージ可否に必須**です — これらにより Multica は App として認証し(App JWT → installation token)、各カードの基になる GitHub API スナップショットを取得します。秘密鍵は App 設定ページの **Private keys → Generate a private key** で生成し、PEM ブロック全体(`-----BEGIN/END RSA PRIVATE KEY-----` の行を含む)を改行を保ったまま env 変数に貼り付けてください。これらがない場合、連携は**きれいに縮退**します: PR は引き続きミラーリングされ、イシューは引き続き自動で紐づき、マージ時に Done へ移動し、接続済みアカウント名も引き続き `installation.created` webhook から解決されます — ただし PR カードには CI やマージ状態が表示されません。+`GITHUB_APP_ID` と `GITHUB_APP_PRIVATE_KEY` は、**PR カードの CI ステータスとマージ可否**、および **Settings → Repositories → GitHub から選択**の両方に必要です。これらにより Multica は App として認証し(App JWT → installation token)、PR カードの GitHub API スナップショットを取得するとともに、metadata read のみに限定した短命 token で installation のリポジトリを一覧します。秘密鍵は App 設定ページの **Private keys → Generate a private key** で生成し、PEM ブロック全体(`-----BEGIN/END RSA PRIVATE KEY-----` の行を含む)を改行を保ったまま env 変数に貼り付けてください。これらがない場合、連携は**きれいに縮退**します: PR は引き続きミラーリングされ、イシューは引き続き自動で紐づき、マージ時に Done へ移動し、接続済みアカウント名も `installation.created` webhook から解決されます — ただし PR カードには CI やマージ状態が表示されず、リポジトリ参照も無効になります。`FRONTEND_ORIGIN` も設定されている必要があります(どのプロダクションのセルフホストでもすでに設定されています)。インストール後、setup コールバックがユーザーを `<FRONTEND_ORIGIN>/settings?tab=github` に戻します。diff --git a/apps/docs/content/docs/github-integration.ko.mdx b/apps/docs/content/docs/github-integration.ko.mdxindex 7a5612632a..8b63156b92 100644--- a/apps/docs/content/docs/github-integration.ko.mdx+++ b/apps/docs/content/docs/github-integration.ko.mdx@@ -149,7 +149,7 @@ GITHUB_APP_PRIVATE_KEY=<BEGIN/END 줄을 포함한 전체 PEM 블록>- Settings의 `Connect GitHub`이 **비활성화**되고 "not configured" 힌트가 표시됩니다.- `/api/webhooks/github` 엔드포인트가 **`503 github webhooks not configured`**를 반환합니다 — Multica는 secret 없이 이벤트를 처리하기를 거부하며, 모든 서명을 조용히 유효한 것으로 취급하지 않습니다.-`GITHUB_APP_ID`와 `GITHUB_APP_PRIVATE_KEY`는 이제 **PR 카드의 CI 상태와 머지 가능 여부에 필수**입니다 — 이 둘로 Multica가 App으로 인증하고(App JWT → installation token) 각 카드의 기반이 되는 GitHub API 스냅샷을 가져옵니다. 비공개 키는 App 설정 페이지의 **Private keys → Generate a private key**에서 생성한 뒤, PEM 블록 전체(`-----BEGIN/END RSA PRIVATE KEY-----` 줄 포함)를 줄바꿈을 유지한 채 env 값에 붙여넣으세요. 이 둘이 없으면 연동은 **깔끔하게 축소**됩니다: PR은 계속 미러링되고, 이슈는 계속 자동 연결되며 머지 시 Done으로 이동하고, 연결된 계정 이름도 계속 `installation.created` 웹훅에서 확인됩니다 — 다만 PR 카드에는 CI나 머지 상태가 표시되지 않습니다.+`GITHUB_APP_ID`와 `GITHUB_APP_PRIVATE_KEY`는 **PR 카드의 CI 상태와 머지 가능 여부** 및 **Settings → Repositories → GitHub에서 선택** 기능 모두에 필요합니다. 이 둘로 Multica가 App으로 인증하고(App JWT → installation token), PR 카드의 GitHub API 스냅샷을 가져오며, metadata read로 제한된 단명 token으로 installation의 저장소를 나열합니다. 비공개 키는 App 설정 페이지의 **Private keys → Generate a private key**에서 생성한 뒤, PEM 블록 전체(`-----BEGIN/END RSA PRIVATE KEY-----` 줄 포함)를 줄바꿈을 유지한 채 env 값에 붙여넣으세요. 이 둘이 없으면 연동은 **깔끔하게 축소**됩니다: PR은 계속 미러링되고, 이슈는 계속 자동 연결되며 머지 시 Done으로 이동하고, 연결된 계정 이름도 `installation.created` 웹훅에서 확인됩니다 — 다만 PR 카드에는 CI나 머지 상태가 표시되지 않고 저장소 탐색도 비활성화됩니다.`FRONTEND_ORIGIN`도 설정되어 있어야 합니다(어떤 프로덕션 자체 호스팅이든 이미 설정되어 있습니다). 설치 후 setup 콜백이 사용자를 `<FRONTEND_ORIGIN>/settings?tab=github`으로 다시 돌려보냅니다.diff --git a/apps/docs/content/docs/github-integration.mdx b/apps/docs/content/docs/github-integration.mdxindex 1da1048a7f..68dc9a6c2a 100644--- a/apps/docs/content/docs/github-integration.mdx+++ b/apps/docs/content/docs/github-integration.mdx@@ -162,7 +162,7 @@ GITHUB_APP_PRIVATE_KEY=<full PEM block, including BEGIN/END lines>- `Connect GitHub` in Settings is **disabled** and shows a "not configured" hint.- The `/api/webhooks/github` endpoint returns **`503 github webhooks not configured`** — Multica refuses to process events with no secret, rather than silently treating every signature as valid.-`GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY` are now **required for the PR card's CI status and mergeability** — they let Multica authenticate as the App (App JWT → installation token) and pull the GitHub API snapshot each card is built from. Generate the key under **Private keys → Generate a private key** on the App's settings page; paste the full PEM block (including the `-----BEGIN/END RSA PRIVATE KEY-----` lines) into the env var, preserving newlines. Without them the integration **degrades cleanly**: PRs still mirror, issues still auto-link and move to Done on merge, and the connected account name still resolves from the `installation.created` webhook — but the PR card shows no CI or merge status.+`GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY` are required for both **PR-card CI status and mergeability** and **Settings → Repositories → Choose from GitHub**. They let Multica authenticate as the App (App JWT → installation token), pull each PR card's GitHub API snapshot, and mint a short-lived metadata-only token to list an installation's repositories. Generate the key under **Private keys → Generate a private key** on the App's settings page; paste the full PEM block (including the `-----BEGIN/END RSA PRIVATE KEY-----` lines) into the env var, preserving newlines. Without them the integration **degrades cleanly**: PRs still mirror, issues still auto-link and move to Done on merge, and the connected account name still resolves from the `installation.created` webhook — but the PR card shows no CI or merge status and repository browsing is disabled.`FRONTEND_ORIGIN` must also be set (it already is for any production self-host); the setup callback bounces the user back to `<FRONTEND_ORIGIN>/settings?tab=github` after install.diff --git a/apps/docs/content/docs/github-integration.zh.mdx b/apps/docs/content/docs/github-integration.zh.mdxindex 710b56e5fa..3919a58278 100644--- a/apps/docs/content/docs/github-integration.zh.mdx+++ b/apps/docs/content/docs/github-integration.zh.mdx@@ -161,7 +161,7 @@ GITHUB_APP_PRIVATE_KEY=<完整 PEM 块,包含 BEGIN/END 行>- Settings 里 `Connect GitHub` 按钮会被 **disable**,并显示「not configured」提示- `/api/webhooks/github` 直接返回 **`503 github webhooks not configured`**——Multica 在 secret 没配置时拒绝处理事件,不会出现「没 secret 也接受 webhook」的安全坑-`GITHUB_APP_ID` 和 `GITHUB_APP_PRIVATE_KEY` 现在是 **PR 卡片 CI 状态与可合并性的必填项**——它们让 Multica 以 App 身份鉴权(App JWT → installation token)并拉取每张卡片所依赖的 GitHub API 快照。私钥从 App 设置页 **Private keys → Generate a private key** 生成,把整段 PEM(含 `-----BEGIN/END RSA PRIVATE KEY-----` 两行)粘到 env 里,保留换行。不配这两个时集成**干净降级**:PR 照常镜像、issue 照常自动关联并在 merge 时转 Done、关联账号名也仍由 `installation.created` webhook 解析——只是 PR 卡片不显示任何 CI 或 merge 状态。+`GITHUB_APP_ID` 和 `GITHUB_APP_PRIVATE_KEY` 同时用于 **PR 卡片的 CI 状态与可合并性**和 **Settings → Repositories → 从 GitHub 选择**。它们让 Multica 以 App 身份鉴权(App JWT → installation token)、拉取 PR 卡片依赖的 GitHub API 快照,并签发仅有 metadata read 权限的短效 token 来列出 installation 的仓库。私钥从 App 设置页 **Private keys → Generate a private key** 生成,把整段 PEM(含 `-----BEGIN/END RSA PRIVATE KEY-----` 两行)粘到 env 里,保留换行。不配这两个时集成会**干净降级**:PR 照常镜像、issue 照常自动关联并在 merge 时转 Done、关联账号名仍由 `installation.created` webhook 解析——但 PR 卡片不显示 CI/merge 状态,仓库浏览也会被禁用。`FRONTEND_ORIGIN` 也必须设置(任何生产 self-host 都已经设了)——setup 回调结束后用它把用户跳回 `<FRONTEND_ORIGIN>/settings?tab=github`。diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 63ca4c9ea2..0c82c8142b 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -136,6 +136,7 @@ import type {NotificationPreferences,GitHubPullRequest,ListGitHubInstallationsResponse,+ ListGitHubRepositoriesResponse,GitHubConnectResponse,ListVCSConnectionsResponse,ConnectVCSRequest,@@ -288,6 +289,12 @@ import {EMPTY_LABEL,EMPTY_LIST_LABELS_RESPONSE,EMPTY_RESOURCE_LABELS_RESPONSE,+ GitHubConnectResponseSchema,+ ListGitHubInstallationsResponseSchema,+ ListGitHubRepositoriesResponseSchema,+ EMPTY_GITHUB_CONNECT_RESPONSE,+ EMPTY_LIST_GITHUB_INSTALLATIONS_RESPONSE,+ EMPTY_LIST_GITHUB_REPOSITORIES_RESPONSE,} from "./schemas";/** Identifies the calling client to the server.@@ -2840,12 +2847,54 @@ export class ApiClient {}// GitHub integration- async getGitHubConnectURL(workspaceId: string): Promise<GitHubConnectResponse> {- return this.fetch(`/api/workspaces/${workspaceId}/github/connect`);+ async getGitHubConnectURL(+ workspaceId: string,+ returnTo?: "github" | "repositories",+ ): Promise<GitHubConnectResponse> {+ const search = new URLSearchParams();+ if (returnTo) search.set("return_to", returnTo);+ const suffix = search.size > 0 ? `?${search.toString()}` : "";+ const raw = await this.fetch<unknown>(+ `/api/workspaces/${workspaceId}/github/connect${suffix}`,+ );+ return parseWithFallback(+ raw,+ GitHubConnectResponseSchema,+ EMPTY_GITHUB_CONNECT_RESPONSE,+ { endpoint: "GET /api/workspaces/:id/github/connect" },+ );}async listGitHubInstallations(workspaceId: string): Promise<ListGitHubInstallationsResponse> {- return this.fetch(`/api/workspaces/${workspaceId}/github/installations`);+ const raw = await this.fetch<unknown>(+ `/api/workspaces/${workspaceId}/github/installations`,+ );+ return parseWithFallback(+ raw,+ ListGitHubInstallationsResponseSchema,+ EMPTY_LIST_GITHUB_INSTALLATIONS_RESPONSE,+ { endpoint: "GET /api/workspaces/:id/github/installations" },+ );+ }++ async listGitHubInstallationRepositories(+ workspaceId: string,+ installationId: string,+ params: { page?: number; per_page?: number } = {},+ ): Promise<ListGitHubRepositoriesResponse> {+ const search = new URLSearchParams();+ if (params.page !== undefined) search.set("page", String(params.page));+ if (params.per_page !== undefined) search.set("per_page", String(params.per_page));+ const suffix = search.size > 0 ? `?${search.toString()}` : "";+ const raw = await this.fetch<unknown>(+ `/api/workspaces/${workspaceId}/github/installations/${installationId}/repositories${suffix}`,+ );+ return parseWithFallback(+ raw,+ ListGitHubRepositoriesResponseSchema,+ EMPTY_LIST_GITHUB_REPOSITORIES_RESPONSE,+ { endpoint: "GET /api/workspaces/:id/github/installations/:installationId/repositories" },+ );}async deleteGitHubInstallation(workspaceId: string, installationId: string): Promise<void> {diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex a14466a7e3..59c8ea122a 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -24,6 +24,44 @@ afterEach(() => {// app in past incidents. The contract is: a malformed response degrades to// an empty/safe shape, never throws into React.describe("ApiClient schema fallback", () => {+ describe("GitHub repository import", () => {+ it("falls back safely when installation or repository responses are malformed", async () => {+ stubFetchJson({ installations: "not-an-array", configured: true });+ const client = new ApiClient("https://api.example.test");+ await expect(client.listGitHubInstallations("ws-1")).resolves.toEqual({+ installations: [],+ configured: false,+ repository_browse_configured: false,+ can_manage: false,+ });++ stubFetchJson({ repositories: [{ id: "wrong-type" }] });+ await expect(+ client.listGitHubInstallationRepositories("ws-1", "installation-1"),+ ).resolves.toEqual({+ repositories: [],+ total_count: 0,+ next_page: null,+ });+ });++ it("adds the allowlisted repository return target to the connect request", async () => {+ stubFetchJson({+ configured: true,+ url: "https://github.com/apps/multica/installations/new",+ });+ const client = new ApiClient("https://api.example.test");++ await client.getGitHubConnectURL("ws-1", "repositories");++ const fetchMock = vi.mocked(fetch);+ expect(fetchMock).toHaveBeenCalledWith(+ "https://api.example.test/api/workspaces/ws-1/github/connect?return_to=repositories",+ expect.any(Object),+ );+ });+ });+describe("listTimeline", () => {it("falls back to an empty array when the body is null", async () => {stubFetchJson(null);diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex a1c8750d41..0c714bf67c 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -20,6 +20,7 @@ import type {CreateBillingPortalSessionResponse,CronPreviewResponse,GroupedIssuesResponse,+ GitHubConnectResponse,GitHubPullRequest,InboxItem,InboxWorkspaceUnread,@@ -32,6 +33,8 @@ import type {IssueTableGroupsResponse,IssueTableRowsResponse,ListIssuesResponse,+ ListGitHubInstallationsResponse,+ ListGitHubRepositoriesResponse,ListLabelsResponse,ListWebhookDeliveriesResponse,NotificationPreferenceResponse,@@ -46,6 +49,63 @@ import type {import type { CloudRuntimeNode } from "../runtimes/cloud-runtime";import type { CreateFeedbackResponse } from "../feedback/types";+export const GitHubInstallationSchema = z.object({+ id: z.string(),+ workspace_id: z.string(),+ installation_id: z.number().optional(),+ account_login: z.string(),+ account_type: z.string(),+ account_avatar_url: z.string().nullable(),+ created_at: z.string(),+ connected_by: z.string().optional(),+}).loose();++export const ListGitHubInstallationsResponseSchema = z.object({+ installations: z.array(GitHubInstallationSchema).default([]),+ configured: z.boolean().optional().default(false),+ repository_browse_configured: z.boolean().optional().default(false),+ can_manage: z.boolean().optional().default(false),+}).loose();++export const EMPTY_LIST_GITHUB_INSTALLATIONS_RESPONSE: ListGitHubInstallationsResponse = {+ installations: [],+ configured: false,+ repository_browse_configured: false,+ can_manage: false,+};++export const GitHubConnectResponseSchema = z.object({+ url: z.string().optional(),+ configured: z.boolean().optional().default(false),+}).loose();++export const EMPTY_GITHUB_CONNECT_RESPONSE: GitHubConnectResponse = {+ configured: false,+};++export const GitHubRepositorySchema = z.object({+ id: z.number(),+ full_name: z.string(),+ html_url: z.string(),+ clone_url: z.string(),+ description: z.string().nullable(),+ private: z.boolean(),+ archived: z.boolean(),+ default_branch: z.string(),+}).loose();++export const ListGitHubRepositoriesResponseSchema = z.object({+ repositories: z.array(GitHubRepositorySchema).default([]),+ total_count: z.number().optional().default(0),+ next_page: z.number().nullable().optional().default(null),+}).loose();++export const EMPTY_LIST_GITHUB_REPOSITORIES_RESPONSE: ListGitHubRepositoriesResponse = {+ repositories: [],+ total_count: 0,+ next_page: null,+};+export const GitHubPullRequestSchema = z.object({id: z.string(),provider: z.string().optional().default("github"),diff --git a/packages/core/github/queries.ts b/packages/core/github/queries.tsindex 24bbbf4742..389104df11 100644--- a/packages/core/github/queries.ts+++ b/packages/core/github/queries.ts@@ -1,9 +1,11 @@-import { queryOptions } from "@tanstack/react-query";+import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query";import { api } from "../api";export const githubKeys = {all: (wsId: string) => ["github", wsId] as const,installations: (wsId: string) => [...githubKeys.all(wsId), "installations"] as const,+ repositories: (wsId: string, installationId: string) =>+ [...githubKeys.all(wsId), "installations", installationId, "repositories"] as const,pullRequests: (issueId: string) => ["github", "pull-requests", issueId] as const,};@@ -14,6 +16,22 @@ export const githubInstallationsOptions = (wsId: string) =>enabled: !!wsId,});+export const githubInstallationRepositoriesOptions = (+ wsId: string,+ installationId: string,+) =>+ infiniteQueryOptions({+ queryKey: githubKeys.repositories(wsId, installationId),+ queryFn: ({ pageParam }) =>+ api.listGitHubInstallationRepositories(wsId, installationId, {+ page: pageParam,+ per_page: 100,+ }),+ initialPageParam: 1,+ getNextPageParam: (lastPage) => lastPage.next_page ?? undefined,+ enabled: !!wsId && !!installationId,+ });+export const issuePullRequestsOptions = (issueId: string) =>queryOptions({queryKey: githubKeys.pullRequests(issueId),diff --git a/packages/core/types/github.ts b/packages/core/types/github.tsindex a3828d4971..8d40424e5a 100644--- a/packages/core/types/github.ts+++ b/packages/core/types/github.ts@@ -121,6 +121,9 @@ export interface ListGitHubInstallationsResponse {installations: GitHubInstallation[];/** Whether the deployment has GitHub App credentials configured. When false, the Connect button is hidden / disabled. */configured: boolean;+ /** Whether the server can mint installation tokens to browse repositories.+ * Older backends omit this field; callers must treat absence as false. */+ repository_browse_configured?: boolean;/** Whether the caller can connect / disconnect installations. Non-admin* members get `false` along with installations that omit `installation_id`.* Older backends predating MUL-2413 omit the field; treat absence as@@ -133,3 +136,20 @@ export interface GitHubConnectResponse {url?: string;configured: boolean;}++export interface GitHubRepository {+ id: number;+ full_name: string;+ html_url: string;+ clone_url: string;+ description: string | null;+ private: boolean;+ archived: boolean;+ default_branch: string;+}++export interface ListGitHubRepositoriesResponse {+ repositories: GitHubRepository[];+ total_count: number;+ next_page: number | null;+}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex b10a46e262..c31ec48662 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -137,6 +137,8 @@ export type {GitHubPullRequestMergeStateStatus,GitHubPullRequestState,ListGitHubInstallationsResponse,+ GitHubRepository,+ ListGitHubRepositoriesResponse,GitHubConnectResponse,} from "./github";export type {diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex ac4c7c4e78..5ed05510ad 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -643,6 +643,27 @@"url_empty": "(empty URL)","description_placeholder": "Description (e.g. Go backend + Next.js frontend)","add": "Add repository",+ "connect_github": "Connect GitHub",+ "choose_from_github": "Choose from GitHub",+ "github_not_configured": "GitHub connection is not configured for this deployment.",+ "github_browse_not_configured": "Repository browsing requires GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY.",+ "github_connect_failed": "Could not connect GitHub. Try again.",+ "github_picker_title": "Choose GitHub repositories",+ "github_picker_description": "Select repositories to add to this workspace. Existing manual entries stay unchanged.",+ "github_account": "GitHub account",+ "github_search_placeholder": "Search loaded repositories",+ "github_loading": "Loading repositories…",+ "github_load_failed": "Could not load repositories from GitHub. Check the installation access and try again.",+ "github_empty": "This installation has no accessible repositories.",+ "github_no_search_results": "No loaded repositories match this search.",+ "github_private": "Private",+ "github_archived": "Archived",+ "github_added": "Added",+ "github_load_more": "Load more",+ "github_selected_count": "{{count}} selected",+ "github_cancel": "Cancel",+ "github_import": "Add repositories",+ "complete_manual_entry_first": "Complete or remove the empty manual repository before importing.","save": "Save","saving": "Saving...","saved_hint": "All changes saved",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex c885f5a6ee..ffc39899c0 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -635,6 +635,27 @@"url_empty": "(空の URL)","description_placeholder": "説明(例: Go バックエンド + Next.js フロントエンド)","add": "リポジトリを追加",+ "connect_github": "GitHub に接続",+ "choose_from_github": "GitHub から選択",+ "github_not_configured": "この環境では GitHub 接続が設定されていません。",+ "github_browse_not_configured": "リポジトリの参照には GITHUB_APP_ID と GITHUB_APP_PRIVATE_KEY が必要です。",+ "github_connect_failed": "GitHub に接続できませんでした。もう一度お試しください。",+ "github_picker_title": "GitHub リポジトリを選択",+ "github_picker_description": "このワークスペースに追加するリポジトリを選択します。既存の手動設定は変更されません。",+ "github_account": "GitHub アカウント",+ "github_search_placeholder": "読み込み済みのリポジトリを検索",+ "github_loading": "リポジトリを読み込み中…",+ "github_load_failed": "GitHub からリポジトリを読み込めませんでした。インストール権限を確認して再試行してください。",+ "github_empty": "このインストールでアクセスできるリポジトリはありません。",+ "github_no_search_results": "読み込み済みのリポジトリに一致するものがありません。",+ "github_private": "非公開",+ "github_archived": "アーカイブ済み",+ "github_added": "追加済み",+ "github_load_more": "さらに読み込む",+ "github_selected_count": "{{count}} 件選択",+ "github_cancel": "キャンセル",+ "github_import": "リポジトリを追加",+ "complete_manual_entry_first": "空の手動リポジトリを入力するか削除してからインポートしてください。","save": "保存","saving": "保存中...","saved_hint": "すべての変更を保存しました",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex aa76ffc374..84eb71ed94 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -487,6 +487,27 @@"url_empty": "(빈 URL)","description_placeholder": "설명(예: Go 백엔드 + Next.js 프런트엔드)","add": "저장소 추가",+ "connect_github": "GitHub 연결",+ "choose_from_github": "GitHub에서 선택",+ "github_not_configured": "이 배포에는 GitHub 연결이 설정되어 있지 않습니다.",+ "github_browse_not_configured": "저장소를 탐색하려면 GITHUB_APP_ID와 GITHUB_APP_PRIVATE_KEY가 필요합니다.",+ "github_connect_failed": "GitHub에 연결하지 못했습니다. 다시 시도해 주세요.",+ "github_picker_title": "GitHub 저장소 선택",+ "github_picker_description": "이 워크스페이스에 추가할 저장소를 선택하세요. 기존 수동 설정은 변경되지 않습니다.",+ "github_account": "GitHub 계정",+ "github_search_placeholder": "불러온 저장소 검색",+ "github_loading": "저장소 불러오는 중…",+ "github_load_failed": "GitHub에서 저장소를 불러오지 못했습니다. 설치 권한을 확인한 후 다시 시도해 주세요.",+ "github_empty": "이 설치에서 접근 가능한 저장소가 없습니다.",+ "github_no_search_results": "불러온 저장소 중 검색 결과가 없습니다.",+ "github_private": "비공개",+ "github_archived": "보관됨",+ "github_added": "추가됨",+ "github_load_more": "더 불러오기",+ "github_selected_count": "{{count}}개 선택",+ "github_cancel": "취소",+ "github_import": "저장소 추가",+ "complete_manual_entry_first": "비어 있는 수동 저장소를 입력하거나 삭제한 후 가져오세요.","save": "저장","saving": "저장하는 중...","saved_hint": "모든 변경사항 저장됨",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 605d50266c..83fab88185 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -642,6 +642,27 @@"url_empty": "(空 URL)","description_placeholder": "描述(例如:Go 后端 + Next.js 前端)","add": "添加仓库",+ "connect_github": "连接 GitHub",+ "choose_from_github": "从 GitHub 选择",+ "github_not_configured": "当前部署尚未配置 GitHub 连接。",+ "github_browse_not_configured": "浏览仓库需要配置 GITHUB_APP_ID 和 GITHUB_APP_PRIVATE_KEY。",+ "github_connect_failed": "无法连接 GitHub,请重试。",+ "github_picker_title": "选择 GitHub 仓库",+ "github_picker_description": "选择要添加到当前工作区的仓库,现有手动配置不会被修改。",+ "github_account": "GitHub 账号",+ "github_search_placeholder": "搜索已加载的仓库",+ "github_loading": "正在加载仓库…",+ "github_load_failed": "无法从 GitHub 加载仓库,请检查安装权限后重试。",+ "github_empty": "该安装下没有可访问的仓库。",+ "github_no_search_results": "已加载的仓库中没有匹配项。",+ "github_private": "私有",+ "github_archived": "已归档",+ "github_added": "已添加",+ "github_load_more": "加载更多",+ "github_selected_count": "已选择 {{count}} 个",+ "github_cancel": "取消",+ "github_import": "添加仓库",+ "complete_manual_entry_first": "请先补全或删除空的手动仓库配置,再从 GitHub 导入。","save": "保存","saving": "保存中...","saved_hint": "所有改动已保存",diff --git a/packages/views/settings/components/repositories-tab.test.tsx b/packages/views/settings/components/repositories-tab.test.tsxindex bbbc2a569d..be99610366 100644--- a/packages/views/settings/components/repositories-tab.test.tsx+++ b/packages/views/settings/components/repositories-tab.test.tsx@@ -7,6 +7,9 @@ import enCommon from "../../locales/en/common.json";import enSettings from "../../locales/en/settings.json";const mockUpdateWorkspace = vi.hoisted(() => vi.fn());+const mockGetGitHubConnectURL = vi.hoisted(() => vi.fn());+const mockFetchNextPage = vi.hoisted(() => vi.fn());+const mockNavReplace = vi.hoisted(() => vi.fn());const mockToastSuccess = vi.hoisted(() => vi.fn());const workspaceRef = vi.hoisted(() => ({current: {@@ -22,10 +25,62 @@ const workspaceRef = vi.hoisted(() => ({const membersRef = vi.hoisted(() => ({current: [{ user_id: "user-1", role: "owner" as "owner" | "admin" | "member" }],}));+const githubRef = vi.hoisted(() => ({+ current: {+ installations: [] as { id: string; account_login: string }[],+ configured: true,+ repository_browse_configured: true,+ can_manage: true,+ },+}));+const githubQueryStateRef = vi.hoisted(() => ({+ current: {+ isPending: false,+ isFetching: false,+ },+}));+const githubRepositoriesRef = vi.hoisted(() => ({+ current: [] as {+ id: number;+ full_name: string;+ html_url: string;+ clone_url: string;+ description: string | null;+ private: boolean;+ archived: boolean;+ default_branch: string;+ }[],+}));+const searchParamsRef = vi.hoisted(() => ({+ current: new URLSearchParams("tab=repositories"),+}));vi.mock("@tanstack/react-query", () => ({- useQuery: () => ({ data: membersRef.current }),+ useQuery: (options: { queryKey: readonly unknown[] }) => {+ if (options.queryKey.includes("installations")) {+ return { data: githubRef.current, ...githubQueryStateRef.current };+ }+ return { data: membersRef.current };+ },+ useInfiniteQuery: () => ({+ data: {+ pages: [+ {+ repositories: githubRepositoriesRef.current,+ total_count: githubRepositoriesRef.current.length,+ next_page: null,+ },+ ],+ },+ isPending: false,+ isError: false,+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: mockFetchNextPage,+ }),useQueryClient: () => ({ setQueryData: vi.fn() }),+ queryOptions: <T,>(options: T) => options,+ infiniteQueryOptions: <T,>(options: T) => options,}));vi.mock("@multica/core/hooks", () => ({@@ -42,7 +97,10 @@ vi.mock("@multica/core/workspace/queries", () => ({}));vi.mock("@multica/core/api", () => ({- api: { updateWorkspace: mockUpdateWorkspace },+ api: {+ updateWorkspace: mockUpdateWorkspace,+ getGitHubConnectURL: mockGetGitHubConnectURL,+ },}));vi.mock("@multica/core/auth", () => {@@ -58,7 +116,18 @@ vi.mock("sonner", () => ({toast: { success: mockToastSuccess, error: vi.fn() },}));-import { RepositoriesTab } from "./repositories-tab";+vi.mock("../../navigation", () => ({+ useNavigation: () => ({+ push: vi.fn(),+ replace: mockNavReplace,+ back: vi.fn(),+ pathname: "/acme/settings",+ searchParams: searchParamsRef.current,+ getShareableUrl: (path: string) => `https://app.example${path}`,+ }),+}));++import { RepositoriesTab, repositoryIdentity } from "./repositories-tab";const TEST_RESOURCES = {en: { common: enCommon, settings: enSettings },@@ -83,6 +152,21 @@ describe("RepositoriesTab — automatic updates", () => {repos: [{ url: "https://github.com/multica-ai/multica" }],};membersRef.current = [{ user_id: "user-1", role: "owner" }];+ githubRef.current = {+ installations: [],+ configured: true,+ repository_browse_configured: true,+ can_manage: true,+ };+ githubQueryStateRef.current = {+ isPending: false,+ isFetching: false,+ };+ githubRepositoriesRef.current = [];+ searchParamsRef.current = new URLSearchParams("tab=repositories");+ mockNavReplace.mockImplementation((path: string) => {+ searchParamsRef.current = new URLSearchParams(path.split("?")[1] ?? "");+ });mockUpdateWorkspace.mockImplementation(async (_id: string, payload: { repos: { url: string; description?: string }[] }) => ({...workspaceRef.current,@@ -229,4 +313,159 @@ describe("RepositoriesTab — automatic updates", () => {expect(screen.getAllByRole("textbox").every((input) => input.hasAttribute("disabled"))).toBe(true);expect(screen.queryByRole("button", { name: /Add repository/ })).toBeNull();});++ it("starts GitHub connection with the signed repository return target", async () => {+ const user = setupUser();+ mockGetGitHubConnectURL.mockResolvedValue({+ configured: true,+ url: "https://github.com/apps/multica/installations/new",+ });+ const open = vi.spyOn(window, "open").mockImplementation(() => null);+ render(<RepositoriesTab />, { wrapper: I18nWrapper });++ await user.click(screen.getByRole("button", { name: "Connect GitHub" }));++ await waitFor(() => {+ expect(mockGetGitHubConnectURL).toHaveBeenCalledWith(+ "workspace-1",+ "repositories",+ );+ expect(open).toHaveBeenCalledWith(+ "https://github.com/apps/multica/installations/new",+ "_blank",+ "noopener",+ );+ });+ open.mockRestore();+ });++ it("keeps GitHub import disabled when repository browsing is unavailable", () => {+ githubRef.current = {+ installations: [],+ configured: true,+ repository_browse_configured: false,+ can_manage: true,+ };+ render(<RepositoriesTab />, { wrapper: I18nWrapper });++ const button = screen.getByRole("button", { name: "Connect GitHub" });+ expect(+ button.hasAttribute("disabled") ||+ button.getAttribute("aria-disabled") === "true",+ ).toBe(true);+ expect(button.getAttribute("title")).toContain("GITHUB_APP_ID");+ });++ it("imports selected GitHub repositories and deduplicates HTTPS against SSH", async () => {+ workspaceRef.current = {+ ...workspaceRef.current,+ repos: [{ url: "[email protected]:multica-ai/multica.git" }],+ };+ githubRef.current = {+ installations: [{ id: "installation-row-1", account_login: "multica-ai" }],+ configured: true,+ repository_browse_configured: true,+ can_manage: true,+ };+ githubRepositoriesRef.current = [+ {+ id: 1,+ full_name: "multica-ai/multica",+ html_url: "https://github.com/multica-ai/multica",+ clone_url: "https://github.com/multica-ai/multica.git",+ description: "Existing repository",+ private: false,+ archived: false,+ default_branch: "main",+ },+ {+ id: 2,+ full_name: "multica-ai/console",+ html_url: "https://github.com/multica-ai/console",+ clone_url: "https://github.com/multica-ai/console.git",+ description: "Console app",+ private: true,+ archived: false,+ default_branch: "main",+ },+ ];+ const user = setupUser();+ render(<RepositoriesTab />, { wrapper: I18nWrapper });++ await user.click(+ screen.getByRole("button", { name: "Choose from GitHub" }),+ );+ const checkboxes = screen.getAllByRole("checkbox");+ expect(checkboxes).toHaveLength(2);+ expect(+ checkboxes[0]!.hasAttribute("disabled") ||+ checkboxes[0]!.getAttribute("aria-disabled") === "true",+ ).toBe(true);++ await user.click(checkboxes[1]!);+ await user.click(screen.getByRole("button", { name: "Add repositories" }));++ await waitFor(() => {+ expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {+ repos: [+ { url: "[email protected]:multica-ai/multica.git" },+ {+ url: "https://github.com/multica-ai/console.git",+ description: "Console app",+ },+ ],+ });+ });+ });++ it("preserves repository path casing when comparing clone URLs", () => {+ expect(+ repositoryIdentity("https://GitHub.com/Acme/Repo.git"),+ ).toBe("github.com/Acme/Repo");+ expect(+ repositoryIdentity("[email protected]:acme/repo.git"),+ ).toBe("github.com/acme/repo");+ });++ it("opens the picker after returning from a GitHub connection", async () => {+ githubRef.current = {+ installations: [{ id: "installation-row-1", account_login: "multica-ai" }],+ configured: true,+ repository_browse_configured: true,+ can_manage: true,+ };+ searchParamsRef.current = new URLSearchParams(+ "tab=repositories&github_connected=1",+ );++ render(<RepositoriesTab />, { wrapper: I18nWrapper });++ expect(+ await screen.findByRole("heading", {+ name: "Choose GitHub repositories",+ }),+ ).toBeTruthy();+ expect(mockNavReplace).toHaveBeenCalledWith(+ "/acme/settings?tab=repositories",+ );+ });++ it("clears the GitHub callback query after an empty installation result", async () => {+ searchParamsRef.current = new URLSearchParams(+ "tab=repositories&github_connected=1",+ );++ render(<RepositoriesTab />, { wrapper: I18nWrapper });++ await waitFor(() => {+ expect(mockNavReplace).toHaveBeenCalledWith(+ "/acme/settings?tab=repositories",+ );+ });+ expect(+ screen.queryByRole("heading", {+ name: "Choose GitHub repositories",+ }),+ ).toBeNull();+ });});diff --git a/packages/views/settings/components/repositories-tab.tsx b/packages/views/settings/components/repositories-tab.tsxindex 34d7d2cf22..f6ddaca032 100644--- a/packages/views/settings/components/repositories-tab.tsx+++ b/packages/views/settings/components/repositories-tab.tsx@@ -1,9 +1,26 @@"use client";import { useCallback, useEffect, useMemo, useState } from "react";-import { Plus, Trash2 } from "lucide-react";+import { LoaderCircle, Plus, Search, Trash2 } from "lucide-react";import { Input } from "@multica/ui/components/ui/input";import { Button } from "@multica/ui/components/ui/button";+import { Badge } from "@multica/ui/components/ui/badge";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@multica/ui/components/ui/select";import {AlertDialog,AlertDialogAction,@@ -15,13 +32,26 @@ import {AlertDialogTitle,} from "@multica/ui/components/ui/alert-dialog";import { toast } from "sonner";-import { useQuery, useQueryClient } from "@tanstack/react-query";+import {+ useInfiniteQuery,+ useQuery,+ useQueryClient,+} from "@tanstack/react-query";import { useAuthStore } from "@multica/core/auth";import { useWorkspaceId } from "@multica/core/hooks";import { useCurrentWorkspace } from "@multica/core/paths";import { memberListOptions, workspaceKeys } from "@multica/core/workspace/queries";+import {+ githubInstallationRepositoriesOptions,+ githubInstallationsOptions,+} from "@multica/core/github";import { api } from "@multica/core/api";-import type { Workspace, WorkspaceRepo } from "@multica/core/types";+import type {+ GitHubRepository,+ Workspace,+ WorkspaceRepo,+} from "@multica/core/types";+import { useNavigation } from "../../navigation";import { useT } from "../../i18n";import {SettingsCard,@@ -30,6 +60,7 @@ import {SettingsTab,} from "./settings-layout";import { useAutoSave } from "./use-auto-save";+import { GitHubMark } from "./github-mark";const EMPTY_REPOSITORIES: WorkspaceRepo[] = [];@@ -42,21 +73,105 @@ function repositoriesEqual(left: WorkspaceRepo[], right: WorkspaceRepo[]) {);}+export function repositoryIdentity(rawURL: string): string | null {+ const value = rawURL.trim();+ if (!value) return null;++ let host = "";+ let path = "";+ if (!value.includes("://")) {+ const scpLike = value.match(/^(?:[^@\s/]+@)?([^:\s/]+):(.+)$/);+ if (scpLike) {+ host = scpLike[1] ?? "";+ path = scpLike[2] ?? "";+ }+ }+ if (!host) {+ try {+ const parsed = new URL(value);+ host = parsed.hostname;+ path = parsed.pathname;+ } catch {+ return null;+ }+ }++ const normalizedPath = path+ .replace(/^\/+|\/+$/g, "")+ .replace(/\.git$/i, "");+ if (!host || !normalizedPath) return null;+ return `${host.toLowerCase()}/${normalizedPath}`;+}+export function RepositoriesTab() {const { t } = useT("settings");const user = useAuthStore((state) => state.user);const workspace = useCurrentWorkspace();const wsId = useWorkspaceId();const queryClient = useQueryClient();+ const navigation = useNavigation();const { data: members = [] } = useQuery(memberListOptions(wsId));const [repositories, setRepositories] = useState<WorkspaceRepo[]>(workspace?.repos ?? EMPTY_REPOSITORIES,);const [pendingRemovalIndex, setPendingRemovalIndex] = useState<number | null>(null);+ const [connectingGitHub, setConnectingGitHub] = useState(false);+ const [githubPickerOpen, setGitHubPickerOpen] = useState(false);+ const [selectedInstallationID, setSelectedInstallationID] = useState("");+ const [selectedRepositories, setSelectedRepositories] = useState<+ Map<number, GitHubRepository>+ >(new Map());+ const [repositorySearch, setRepositorySearch] = useState("");const currentMember = members.find((member) => member.user_id === user?.id) ?? null;const canManageWorkspace =currentMember?.role === "owner" || currentMember?.role === "admin";+ const {+ data: githubData,+ isPending: githubInstallationsPending,+ isFetching: githubInstallationsFetching,+ } = useQuery({+ ...githubInstallationsOptions(wsId),+ enabled: !!wsId && canManageWorkspace,+ });+ const githubInstallations = useMemo(+ () => githubData?.installations ?? [],+ [githubData?.installations],+ );+ const githubConnectConfigured = githubData?.configured === true;+ const githubBrowseConfigured =+ githubData?.repository_browse_configured === true;+ const githubRepositoriesQuery = useInfiniteQuery({+ ...githubInstallationRepositoriesOptions(wsId, selectedInstallationID),+ enabled:+ githubPickerOpen &&+ canManageWorkspace &&+ githubBrowseConfigured &&+ !!selectedInstallationID,+ });+ const githubRepositories = useMemo(+ () =>+ githubRepositoriesQuery.data?.pages.flatMap(+ (page) => page.repositories,+ ) ?? [],+ [githubRepositoriesQuery.data?.pages],+ );+ const existingRepositoryIdentities = useMemo(+ () =>+ new Set(+ repositories+ .map((repository) => repositoryIdentity(repository.url))+ .filter((identity): identity is string => !!identity),+ ),+ [repositories],+ );+ const filteredGitHubRepositories = useMemo(() => {+ const search = repositorySearch.trim().toLowerCase();+ if (!search) return githubRepositories;+ return githubRepositories.filter((repository) =>+ repository.full_name.toLowerCase().includes(search),+ );+ }, [githubRepositories, repositorySearch]);useEffect(() => {setRepositories(workspace?.repos ?? EMPTY_REPOSITORIES);@@ -65,6 +180,53 @@ export function RepositoriesTab() {// eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally keyed on workspace identity}, [workspace?.id]);+ useEffect(() => {+ if (+ selectedInstallationID &&+ githubInstallations.some(+ (installation) => installation.id === selectedInstallationID,+ )+ ) {+ return;+ }+ setSelectedInstallationID(githubInstallations[0]?.id ?? "");+ }, [githubInstallations, selectedInstallationID]);++ useEffect(() => {+ const connected = navigation.searchParams.get("github_connected") === "1";+ const githubError = navigation.searchParams.get("github_error");+ if ((!connected && !githubError) || !canManageWorkspace) return;+ if (+ !githubError &&+ (githubInstallationsPending || githubInstallationsFetching)+ ) {+ return;+ }++ if (githubError) {+ toast.error(t(($) => $.repositories.github_connect_failed));+ } else if (githubInstallations.length > 0 && githubBrowseConfigured) {+ setSelectedInstallationID(githubInstallations[0]!.id);+ setGitHubPickerOpen(true);+ } else if (githubInstallations.length > 0) {+ toast.error(t(($) => $.repositories.github_browse_not_configured));+ }++ const next = new URLSearchParams(navigation.searchParams);+ next.delete("github_connected");+ next.delete("github_error");+ const search = next.toString();+ navigation.replace(`${navigation.pathname}${search ? `?${search}` : ""}`);+ }, [+ canManageWorkspace,+ githubBrowseConfigured,+ githubInstallations,+ githubInstallationsFetching,+ githubInstallationsPending,+ navigation,+ t,+ ]);+const savedRepositories = workspace?.repos ?? EMPTY_REPOSITORIES;const draft = useMemo(() => repositories, [repositories]);const saveRepositories = useCallback(@@ -114,6 +276,83 @@ export function RepositoriesTab() {setRepositories((current) => [...current, { url: "" }]);};+ const openGitHubPicker = () => {+ setSelectedInstallationID(+ selectedInstallationID || githubInstallations[0]?.id || "",+ );+ setGitHubPickerOpen(true);+ };++ const handleGitHubAction = async () => {+ if (githubInstallations.length > 0) {+ openGitHubPicker();+ return;+ }+ setConnectingGitHub(true);+ try {+ const response = await api.getGitHubConnectURL(wsId, "repositories");+ if (!response.configured || !response.url) {+ toast.error(t(($) => $.repositories.github_not_configured));+ return;+ }+ window.open(response.url, "_blank", "noopener");+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : t(($) => $.repositories.github_connect_failed),+ );+ } finally {+ setConnectingGitHub(false);+ }+ };++ const closeGitHubPicker = () => {+ setGitHubPickerOpen(false);+ setSelectedRepositories(new Map());+ setRepositorySearch("");+ };++ const toggleGitHubRepository = (+ repository: GitHubRepository,+ checked: boolean,+ ) => {+ setSelectedRepositories((current) => {+ const next = new Map(current);+ if (checked) next.set(repository.id, repository);+ else next.delete(repository.id);+ return next;+ });+ };++ const importGitHubRepositories = () => {+ if (!allUrlsValid) {+ toast.error(t(($) => $.repositories.complete_manual_entry_first));+ return;+ }+ const additions: WorkspaceRepo[] = [];+ const known = new Set(existingRepositoryIdentities);+ for (const repository of selectedRepositories.values()) {+ const identity = repositoryIdentity(repository.clone_url);+ if (!identity || known.has(identity) || repository.archived) continue;+ known.add(identity);+ additions.push({+ url: repository.clone_url,+ ...(repository.description?.trim()+ ? { description: repository.description.trim() }+ : {}),+ });+ }+ if (additions.length === 0) {+ closeGitHubPicker();+ return;+ }+ const next = [...repositories, ...additions];+ setRepositories(next);+ autoSave.saveNow(next);+ closeGitHubPicker();+ };+const removeRepository = (index: number) => {const next = repositories.filter((_, repoIndex) => repoIndex !== index);setRepositories(next);@@ -191,11 +430,37 @@ export function RepositoriesTab() {))}{canManageWorkspace ? (- <div className="flex items-center justify-between gap-3 px-4 py-3.5">- <Button variant="outline" size="sm" onClick={addRepository}>- <Plus className="size-3.5" />- {t(($) => $.repositories.add)}- </Button>+ <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3.5">+ <div className="flex flex-wrap items-center gap-2">+ <Button variant="outline" size="sm" onClick={addRepository}>+ <Plus className="size-3.5" />+ {t(($) => $.repositories.add)}+ </Button>+ <Button+ size="sm"+ onClick={handleGitHubAction}+ disabled={+ connectingGitHub ||+ !githubBrowseConfigured ||+ (!githubConnectConfigured &&+ githubInstallations.length === 0)+ }+ title={+ !githubBrowseConfigured+ ? t(($) => $.repositories.github_browse_not_configured)+ : undefined+ }+ >+ {connectingGitHub ? (+ <LoaderCircle className="size-3.5 animate-spin" />+ ) : (+ <GitHubMark className="size-3.5" />+ )}+ {githubInstallations.length > 0+ ? t(($) => $.repositories.choose_from_github)+ : t(($) => $.repositories.connect_github)}+ </Button>+ </div>{!allUrlsValid ? (<span className="text-xs text-muted-foreground">{t(($) => $.repositories.url_empty)}@@ -210,6 +475,187 @@ export function RepositoriesTab() {</SettingsCard></SettingsSection>+ <Dialog+ open={githubPickerOpen}+ onOpenChange={(open) => {+ if (!open) closeGitHubPicker();+ }}+ >+ <DialogContent className="flex max-h-[85vh] flex-col gap-0 p-0 sm:max-w-2xl">+ <DialogHeader className="border-b px-6 py-5">+ <DialogTitle>+ {t(($) => $.repositories.github_picker_title)}+ </DialogTitle>+ <DialogDescription>+ {t(($) => $.repositories.github_picker_description)}+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-3 px-6 py-4">+ {githubInstallations.length > 1 ? (+ <Select+ items={githubInstallations.map((installation) => ({+ value: installation.id,+ label: installation.account_login,+ }))}+ value={selectedInstallationID}+ onValueChange={(value) =>+ setSelectedInstallationID(value ?? "")+ }+ >+ <SelectTrigger+ aria-label={t(($) => $.repositories.github_account)}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {githubInstallations.map((installation) => (+ <SelectItem+ key={installation.id}+ value={installation.id}+ >+ {installation.account_login}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : githubInstallations[0] ? (+ <p className="text-xs text-muted-foreground">+ {t(($) => $.repositories.github_account)}:{" "}+ <span className="font-medium text-foreground">+ {githubInstallations[0].account_login}+ </span>+ </p>+ ) : null}++ <div className="relative">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />+ <Input+ value={repositorySearch}+ onChange={(event) => setRepositorySearch(event.target.value)}+ placeholder={t(+ ($) => $.repositories.github_search_placeholder,+ )}+ aria-label={t(+ ($) => $.repositories.github_search_placeholder,+ )}+ className="pl-8"+ />+ </div>+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto border-y">+ {githubRepositoriesQuery.isPending ? (+ <div className="flex items-center justify-center gap-2 px-6 py-12 text-sm text-muted-foreground">+ <LoaderCircle className="size-4 animate-spin" />+ {t(($) => $.repositories.github_loading)}+ </div>+ ) : githubRepositoriesQuery.isError ? (+ <div className="px-6 py-12 text-center text-sm text-muted-foreground">+ {t(($) => $.repositories.github_load_failed)}+ </div>+ ) : filteredGitHubRepositories.length === 0 ? (+ <div className="px-6 py-12 text-center text-sm text-muted-foreground">+ {repositorySearch+ ? t(($) => $.repositories.github_no_search_results)+ : t(($) => $.repositories.github_empty)}+ </div>+ ) : (+ <div className="divide-y">+ {filteredGitHubRepositories.map((repository) => {+ const identity = repositoryIdentity(repository.clone_url);+ const alreadyAdded =+ !!identity && existingRepositoryIdentities.has(identity);+ const disabled = alreadyAdded || repository.archived;+ return (+ <label+ key={repository.id}+ htmlFor={`github-repository-${repository.id}`}+ className="flex items-start gap-3 px-6 py-3.5"+ >+ <Checkbox+ id={`github-repository-${repository.id}`}+ checked={+ alreadyAdded ||+ selectedRepositories.has(repository.id)+ }+ disabled={disabled}+ onCheckedChange={(checked) =>+ toggleGitHubRepository(+ repository,+ checked === true,+ )+ }+ className="mt-0.5"+ />+ <span className="min-w-0 flex-1 space-y-1">+ <span className="flex flex-wrap items-center gap-2">+ <span className="truncate text-sm font-medium">+ {repository.full_name}+ </span>+ {repository.private ? (+ <Badge variant="secondary">+ {t(($) => $.repositories.github_private)}+ </Badge>+ ) : null}+ {repository.archived ? (+ <Badge variant="outline">+ {t(($) => $.repositories.github_archived)}+ </Badge>+ ) : null}+ {alreadyAdded ? (+ <Badge variant="outline">+ {t(($) => $.repositories.github_added)}+ </Badge>+ ) : null}+ </span>+ {repository.description ? (+ <span className="block truncate text-xs text-muted-foreground">+ {repository.description}+ </span>+ ) : null}+ </span>+ </label>+ );+ })}+ </div>+ )}++ {githubRepositoriesQuery.hasNextPage ? (+ <div className="flex justify-center border-t p-3">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => githubRepositoriesQuery.fetchNextPage()}+ disabled={githubRepositoriesQuery.isFetchingNextPage}+ >+ {githubRepositoriesQuery.isFetchingNextPage+ ? t(($) => $.repositories.github_loading)+ : t(($) => $.repositories.github_load_more)}+ </Button>+ </div>+ ) : null}+ </div>++ <DialogFooter className="m-0 border-t bg-muted/30 px-6 py-4">+ <p className="mr-auto text-xs text-muted-foreground">+ {t(($) => $.repositories.github_selected_count, {+ count: selectedRepositories.size,+ })}+ </p>+ <Button variant="ghost" onClick={closeGitHubPicker}>+ {t(($) => $.repositories.github_cancel)}+ </Button>+ <Button+ onClick={importGitHubRepositories}+ disabled={selectedRepositories.size === 0 || !allUrlsValid}+ >+ {t(($) => $.repositories.github_import)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+<AlertDialogopen={pendingRemovalIndex !== null}onOpenChange={(open) => {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex af7ef91fa5..11d5a95989 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -943,6 +943,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Group(func(r chi.Router) {r.Use(middleware.RequireWorkspaceRoleFromURL(queries, "id", "owner", "admin"))r.Get("/github/connect", h.GitHubConnect)+ r.Get("/github/installations/{installationId}/repositories", h.ListGitHubInstallationRepositories)r.Delete("/github/installations/{installationId}", h.DeleteGitHubInstallation)// VCS connect / disconnect / webhook regeneration (admin-only).r.Post("/vcs/connections", h.ConnectVCS)diff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex 4566cd875d..75f89e0288 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -30,10 +30,15 @@ import ()// githubAPIBase is the base URL for GitHub's REST API. Mutable so tests can-// point fetchInstallationAccount at an httptest server without touching the-// real GitHub.+// point App-authenticated calls at an httptest server without touching GitHub.var githubAPIBase = "https://api.github.com"+const (+ githubReturnToGitHub = "github"+ githubReturnToRepositories = "repositories"+ githubAPIResponseLimit = 4 << 20+)+// ── Response shapes ─────────────────────────────────────────────────────────// GitHubInstallationResponse is the JSON shape returned by the installation@@ -136,6 +141,23 @@ type GitHubConnectResponse struct {Configured bool `json:"configured"`}+type GitHubRepositoryResponse struct {+ ID int64 `json:"id"`+ FullName string `json:"full_name"`+ HTMLURL string `json:"html_url"`+ CloneURL string `json:"clone_url"`+ Description *string `json:"description"`+ Private bool `json:"private"`+ Archived bool `json:"archived"`+ DefaultBranch string `json:"default_branch"`+}++type GitHubRepositoriesResponse struct {+ Repositories []GitHubRepositoryResponse `json:"repositories"`+ TotalCount int64 `json:"total_count"`+ NextPage *int `json:"next_page"`+}+func githubInstallationToResponse(i db.GithubInstallation) GitHubInstallationResponse {instID := i.InstallationIDreturn GitHubInstallationResponse{@@ -347,46 +369,89 @@ func githubWebhookSecret() string { return strings.TrimSpace(os.Getenv("GITHUB_W// frontend never offers a flow that the backend would reject.func isGitHubConfigured() bool { return githubAppSlug() != "" && githubWebhookSecret() != "" }+// isGitHubRepositoryBrowseConfigured is deliberately separate from the+// install-flow flag. The App slug + webhook secret are enough to connect an+// installation, but browsing its repositories also requires App JWT+// credentials so the server can mint a short-lived installation token.+func isGitHubRepositoryBrowseConfigured() bool {+ return strings.TrimSpace(os.Getenv("GITHUB_APP_ID")) != "" &&+ strings.TrimSpace(os.Getenv("GITHUB_APP_PRIVATE_KEY")) != ""+}+// signState produces an opaque token that binds a workspace ID to the// install flow so the setup callback can recover the workspace without// trusting query params alone. Format: "<workspaceID>.<nonce>.<sigHex>".func signState(workspaceID string) (string, error) {+ return signStateForReturn(workspaceID, githubReturnToGitHub)+}++func signStateForReturn(workspaceID, returnTo string) (string, error) {secret := githubWebhookSecret()if secret == "" {return "", errors.New("github integration is not configured")}+ if !isAllowedGitHubReturnTo(returnTo) {+ return "", errors.New("invalid github return target")+ }nonceBytes := make([]byte, 12)if _, err := rand.Read(nonceBytes); err != nil {return "", err}nonce := hex.EncodeToString(nonceBytes)+ payload := workspaceID + "." + nonce+ if returnTo != githubReturnToGitHub {+ payload = workspaceID + "." + returnTo + "." + nonce+ }mac := hmac.New(sha256.New, []byte(secret))- mac.Write([]byte(workspaceID))- mac.Write([]byte("."))- mac.Write([]byte(nonce))+ mac.Write([]byte(payload))sig := hex.EncodeToString(mac.Sum(nil))- return workspaceID + "." + nonce + "." + sig, nil+ return payload + "." + sig, nil}func verifyState(token string) (string, bool) {+ workspaceID, _, ok := verifyStateWithReturn(token)+ return workspaceID, ok+}++func verifyStateWithReturn(token string) (workspaceID, returnTo string, ok bool) {secret := githubWebhookSecret()if secret == "" {- return "", false+ return "", "", false}parts := strings.Split(token, ".")- if len(parts) != 3 {- return "", false+ if len(parts) != 3 && len(parts) != 4 {+ return "", "", false+ }+ workspaceID = parts[0]+ returnTo = githubReturnToGitHub+ nonceIndex := 1+ if len(parts) == 4 {+ returnTo = parts[1]+ nonceIndex = 2+ if !isAllowedGitHubReturnTo(returnTo) {+ return "", "", false+ }}- workspaceID, nonce, sig := parts[0], parts[1], parts[2]+ sig := parts[nonceIndex+1]+ payload := strings.Join(parts[:nonceIndex+1], ".")mac := hmac.New(sha256.New, []byte(secret))- mac.Write([]byte(workspaceID))- mac.Write([]byte("."))- mac.Write([]byte(nonce))+ mac.Write([]byte(payload))expected := hex.EncodeToString(mac.Sum(nil))if !hmac.Equal([]byte(expected), []byte(sig)) {- return "", false+ return "", "", false+ }+ return workspaceID, returnTo, true+}++func isAllowedGitHubReturnTo(returnTo string) bool {+ return returnTo == githubReturnToGitHub || returnTo == githubReturnToRepositories+}++func githubSettingsURL(frontend, returnTo string) string {+ if !isAllowedGitHubReturnTo(returnTo) {+ returnTo = githubReturnToGitHub}- return workspaceID, true+ return strings.TrimRight(frontend, "/") + "/settings?tab=" + url.QueryEscape(returnTo)}// GitHubConnect (GET /api/workspaces/{id}/github/connect) returns the URL the@@ -401,8 +466,16 @@ func (h *Handler) GitHubConnect(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, GitHubConnectResponse{Configured: false})return}+ returnTo := strings.TrimSpace(r.URL.Query().Get("return_to"))+ if returnTo == "" {+ returnTo = githubReturnToGitHub+ }+ if !isAllowedGitHubReturnTo(returnTo) {+ writeError(w, http.StatusBadRequest, "invalid return target")+ return+ }slug := githubAppSlug()- state, err := signState(workspaceID)+ state, err := signStateForReturn(workspaceID, returnTo)if err != nil {writeError(w, http.StatusInternalServerError, "failed to sign state")return@@ -431,17 +504,22 @@ func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {if frontend == "" {frontend = "http://localhost:3000"}- settingsURL := strings.TrimRight(frontend, "/") + "/settings?tab=github"+ settingsURL := githubSettingsURL(frontend, githubReturnToGitHub)- if installationIDStr == "" || state == "" {+ if state == "" {http.Redirect(w, r, settingsURL+"&github_error=missing_params", http.StatusFound)return}- workspaceID, ok := verifyState(state)+ workspaceID, returnTo, ok := verifyStateWithReturn(state)if !ok {http.Redirect(w, r, settingsURL+"&github_error=invalid_state", http.StatusFound)return}+ settingsURL = githubSettingsURL(frontend, returnTo)+ if installationIDStr == "" {+ http.Redirect(w, r, settingsURL+"&github_error=missing_params", http.StatusFound)+ return+ }installationID, err := strconv.ParseInt(installationIDStr, 10, 64)if err != nil {http.Redirect(w, r, settingsURL+"&github_error=bad_installation_id", http.StatusFound)@@ -652,12 +730,209 @@ func (h *Handler) ListGitHubInstallations(w http.ResponseWriter, r *http.Requestout = append(out, resp)}writeJSON(w, http.StatusOK, map[string]any{- "installations": out,- "configured": isGitHubConfigured(),- "can_manage": canManage,+ "installations": out,+ "configured": isGitHubConfigured(),+ "repository_browse_configured": isGitHubRepositoryBrowseConfigured(),+ "can_manage": canManage,})}+// ListGitHubInstallationRepositories returns the repositories accessible to a+// workspace-bound GitHub App installation. The route is admin-only because+// private repository names are sensitive. The path takes our installation row+// UUID (not GitHub's numeric installation id), and the workspace ownership+// check happens before any GitHub API call.+func (h *Handler) ListGitHubInstallationRepositories(w http.ResponseWriter, r *http.Request) {+ workspaceID := chi.URLParam(r, "id")+ if _, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id"); !ok {+ return+ }+ installationRowID := chi.URLParam(r, "installationId")+ rowUUID, ok := parseUUIDOrBadRequest(w, installationRowID, "installation id")+ if !ok {+ return+ }+ row, err := h.Queries.GetGitHubInstallationByID(r.Context(), rowUUID)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "github installation not found")+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to load github installation")+ return+ }+ if uuidToString(row.WorkspaceID) != workspaceID {+ writeError(w, http.StatusNotFound, "github installation not found")+ return+ }+ if !isGitHubRepositoryBrowseConfigured() {+ writeError(w, http.StatusServiceUnavailable, "github repository browsing is not configured")+ return+ }+ page, ok := parseGitHubPageParam(w, r, "page", 1, 1, 100000)+ if !ok {+ return+ }+ perPage, ok := parseGitHubPageParam(w, r, "per_page", 100, 1, 100)+ if !ok {+ return+ }++ repositories, err := fetchGitHubInstallationRepositories(+ r.Context(),+ row.InstallationID,+ page,+ perPage,+ )+ if err != nil {+ slog.Warn("github: list installation repositories failed", "err", err)+ writeError(w, http.StatusBadGateway, "failed to list github repositories")+ return+ }+ writeJSON(w, http.StatusOK, repositories)+}++func parseGitHubPageParam(+ w http.ResponseWriter,+ r *http.Request,+ name string,+ defaultValue, minValue, maxValue int,+) (int, bool) {+ raw := strings.TrimSpace(r.URL.Query().Get(name))+ if raw == "" {+ return defaultValue, true+ }+ value, err := strconv.Atoi(raw)+ if err != nil || value < minValue || value > maxValue {+ writeError(w, http.StatusBadRequest, "invalid "+name)+ return 0, false+ }+ return value, true+}++func fetchGitHubInstallationRepositories(+ ctx context.Context,+ installationID int64,+ page, perPage int,+) (GitHubRepositoriesResponse, error) {+ appJWT, err := signGitHubAppJWT(time.Now())+ if err != nil {+ return GitHubRepositoriesResponse{}, err+ }+ if appJWT == "" {+ return GitHubRepositoriesResponse{}, errors.New("github App JWT credentials unavailable")+ }++ client := &http.Client{Timeout: 15 * time.Second}+ tokenEndpoint := fmt.Sprintf(+ "%s/app/installations/%d/access_tokens",+ strings.TrimRight(githubAPIBase, "/"),+ installationID,+ )+ tokenReq, err := http.NewRequestWithContext(+ ctx,+ http.MethodPost,+ tokenEndpoint,+ strings.NewReader(`{"permissions":{"metadata":"read"}}`),+ )+ if err != nil {+ return GitHubRepositoriesResponse{}, err+ }+ setGitHubAPIHeaders(tokenReq, appJWT)+ tokenReq.Header.Set("Content-Type", "application/json")+ tokenResp, err := client.Do(tokenReq)+ if err != nil {+ return GitHubRepositoriesResponse{}, fmt.Errorf("create installation token: %w", err)+ }+ defer tokenResp.Body.Close()+ if tokenResp.StatusCode != http.StatusCreated {+ _, _ = io.Copy(io.Discard, io.LimitReader(tokenResp.Body, githubAPIResponseLimit))+ return GitHubRepositoriesResponse{}, fmt.Errorf("create installation token: github status %d", tokenResp.StatusCode)+ }+ var tokenBody struct {+ Token string `json:"token"`+ }+ if err := json.NewDecoder(io.LimitReader(tokenResp.Body, githubAPIResponseLimit)).Decode(&tokenBody); err != nil {+ return GitHubRepositoriesResponse{}, fmt.Errorf("decode installation token: %w", err)+ }+ if tokenBody.Token == "" {+ return GitHubRepositoriesResponse{}, errors.New("github returned an empty installation token")+ }+ defer revokeGitHubInstallationToken(client, tokenBody.Token)++ repositoriesEndpoint := fmt.Sprintf(+ "%s/installation/repositories?page=%d&per_page=%d",+ strings.TrimRight(githubAPIBase, "/"),+ page,+ perPage,+ )+ repositoriesReq, err := http.NewRequestWithContext(ctx, http.MethodGet, repositoriesEndpoint, nil)+ if err != nil {+ return GitHubRepositoriesResponse{}, err+ }+ setGitHubAPIHeaders(repositoriesReq, tokenBody.Token)+ repositoriesResp, err := client.Do(repositoriesReq)+ if err != nil {+ return GitHubRepositoriesResponse{}, fmt.Errorf("list installation repositories: %w", err)+ }+ defer repositoriesResp.Body.Close()+ if repositoriesResp.StatusCode != http.StatusOK {+ _, _ = io.Copy(io.Discard, io.LimitReader(repositoriesResp.Body, githubAPIResponseLimit))+ return GitHubRepositoriesResponse{}, fmt.Errorf("list installation repositories: github status %d", repositoriesResp.StatusCode)+ }+ var body struct {+ TotalCount int64 `json:"total_count"`+ Repositories []struct {+ ID int64 `json:"id"`+ FullName string `json:"full_name"`+ HTMLURL string `json:"html_url"`+ CloneURL string `json:"clone_url"`+ Description *string `json:"description"`+ Private bool `json:"private"`+ Archived bool `json:"archived"`+ DefaultBranch string `json:"default_branch"`+ } `json:"repositories"`+ }+ if err := json.NewDecoder(io.LimitReader(repositoriesResp.Body, githubAPIResponseLimit)).Decode(&body); err != nil {+ return GitHubRepositoriesResponse{}, fmt.Errorf("decode installation repositories: %w", err)+ }+ out := GitHubRepositoriesResponse{+ Repositories: make([]GitHubRepositoryResponse, 0, len(body.Repositories)),+ TotalCount: body.TotalCount,+ }+ for _, repository := range body.Repositories {+ out.Repositories = append(out.Repositories, GitHubRepositoryResponse(repository))+ }+ if int64(page*perPage) < body.TotalCount {+ nextPage := page + 1+ out.NextPage = &nextPage+ }+ return out, nil+}++func setGitHubAPIHeaders(req *http.Request, token string) {+ req.Header.Set("Accept", "application/vnd.github+json")+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("X-GitHub-Api-Version", "2022-11-28")+}++func revokeGitHubInstallationToken(client *http.Client, token string) {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ endpoint := strings.TrimRight(githubAPIBase, "/") + "/installation/token"+ req, err := http.NewRequestWithContext(ctx, http.MethodDelete, endpoint, nil)+ if err != nil {+ return+ }+ setGitHubAPIHeaders(req, token)+ resp, err := client.Do(req)+ if err != nil {+ return+ }+ defer resp.Body.Close()+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, githubAPIResponseLimit))+}+func (h *Handler) DeleteGitHubInstallation(w http.ResponseWriter, r *http.Request) {workspaceID := chi.URLParam(r, "id")wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.goindex 701b0efd3d..2a5ada35dd 100644--- a/server/internal/handler/github_test.go+++ b/server/internal/handler/github_test.go@@ -14,6 +14,7 @@ import ("fmt""net/http""net/http/httptest"+ "net/url""reflect""strings""testing"@@ -242,6 +243,9 @@ func TestStateRoundTrip(t *testing.T) {if err != nil {t.Fatalf("signState: %v", err)}+ if parts := strings.Split(tok, "."); len(parts) != 3 {+ t.Fatalf("default return state has %d parts, want legacy 3-part format", len(parts))+ }got, ok := verifyState(tok)if !ok {t.Fatal("verifyState rejected a freshly-signed token")@@ -264,6 +268,103 @@ func TestStateRoundTrip(t *testing.T) {}}+func TestStateRoundTripWithRepositoryReturnTarget(t *testing.T) {+ t.Setenv("GITHUB_WEBHOOK_SECRET", "test-secret-123")+ wsID := "11111111-2222-3333-4444-555555555555"++ tok, err := signStateForReturn(wsID, githubReturnToRepositories)+ if err != nil {+ t.Fatalf("signStateForReturn: %v", err)+ }+ if parts := strings.Split(tok, "."); len(parts) != 4 {+ t.Fatalf("repository return state has %d parts, want 4", len(parts))+ }+ gotWorkspaceID, gotReturnTo, ok := verifyStateWithReturn(tok)+ if !ok {+ t.Fatal("verifyStateWithReturn rejected a freshly-signed token")+ }+ if gotWorkspaceID != wsID || gotReturnTo != githubReturnToRepositories {+ t.Errorf(+ "verifyStateWithReturn() = (%q, %q), want (%q, %q)",+ gotWorkspaceID,+ gotReturnTo,+ wsID,+ githubReturnToRepositories,+ )+ }++ tampered := strings.Replace(tok, ".repositories.", ".github.", 1)+ if _, _, ok := verifyStateWithReturn(tampered); ok {+ t.Error("tampered return target should fail verification")+ }+}++func TestGitHubConnectRepositoryReturnTarget(t *testing.T) {+ t.Setenv("GITHUB_APP_SLUG", "multica-test")+ t.Setenv("GITHUB_WEBHOOK_SECRET", "test-secret-123")+ wsID := "11111111-2222-3333-4444-555555555555"++ req := httptest.NewRequest(+ http.MethodGet,+ "/api/workspaces/"+wsID+"/github/connect?return_to=repositories",+ nil,+ )+ req = withURLParam(req, "id", wsID)+ rec := httptest.NewRecorder()+ (&Handler{}).GitHubConnect(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("GitHubConnect: got %d (%s)", rec.Code, rec.Body.String())+ }+ var body GitHubConnectResponse+ if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {+ t.Fatalf("decode connect response: %v", err)+ }+ installURL, err := url.Parse(body.URL)+ if err != nil {+ t.Fatalf("parse install URL: %v", err)+ }+ _, returnTo, ok := verifyStateWithReturn(installURL.Query().Get("state"))+ if !ok || returnTo != githubReturnToRepositories {+ t.Fatalf("signed return target = %q, valid=%v, want repositories", returnTo, ok)+ }++ badReq := httptest.NewRequest(+ http.MethodGet,+ "/api/workspaces/"+wsID+"/github/connect?return_to=https://evil.example",+ nil,+ )+ badReq = withURLParam(badReq, "id", wsID)+ badRec := httptest.NewRecorder()+ (&Handler{}).GitHubConnect(badRec, badReq)+ if badRec.Code != http.StatusBadRequest {+ t.Fatalf("invalid return target: got %d, want 400", badRec.Code)+ }+}++func TestGitHubSetupCallbackRepositoryReturnTarget(t *testing.T) {+ t.Setenv("GITHUB_WEBHOOK_SECRET", "test-secret-123")+ t.Setenv("FRONTEND_ORIGIN", "https://app.multica.test/")+ wsID := "11111111-2222-3333-4444-555555555555"+ state, err := signStateForReturn(wsID, githubReturnToRepositories)+ if err != nil {+ t.Fatalf("signStateForReturn: %v", err)+ }++ req := httptest.NewRequest(+ http.MethodGet,+ "/api/github/setup?installation_id=not-a-number&state="+url.QueryEscape(state),+ nil,+ )+ rec := httptest.NewRecorder()+ (&Handler{}).GitHubSetupCallback(rec, req)+ if rec.Code != http.StatusFound {+ t.Fatalf("GitHubSetupCallback: got %d, want 302", rec.Code)+ }+ if got := rec.Header().Get("Location"); got != "https://app.multica.test/settings?tab=repositories&github_error=bad_installation_id" {+ t.Fatalf("redirect = %q, want repository settings error", got)+ }+}+func TestSignStateRequiresSecret(t *testing.T) {t.Setenv("GITHUB_WEBHOOK_SECRET", "")if _, err := signState("ws"); err == nil {@@ -1788,6 +1889,7 @@ func TestGitHubRoutes_RoleGating(t *testing.T) {const slug = "github-routes-role-gating"_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)+ _, _ = testPool.Exec(ctx, `DELETE FROM "user" WHERE email LIKE $1`, "github-routes-"+slug+"-%")var wsID stringif err := testPool.QueryRow(ctx, `@@ -1860,6 +1962,7 @@ INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, $3)r.Group(func(r chi.Router) {r.Use(middleware.RequireWorkspaceRoleFromURL(testHandler.Queries, "id", "owner", "admin"))r.Get("/github/connect", testHandler.GitHubConnect)+ r.Get("/github/installations/{installationId}/repositories", testHandler.ListGitHubInstallationRepositories)r.Delete("/github/installations/{installationId}", testHandler.DeleteGitHubInstallation)})})@@ -1904,6 +2007,16 @@ INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, $3)}})+ t.Run("GET repositories remains owner/admin only", func(t *testing.T) {+ path := "/api/workspaces/" + wsID + "/github/installations/" + uuidToString(createdInst.ID) + "/repositories"+ if code := exercise(t, http.MethodGet, path, memberUserID); code != http.StatusForbidden {+ t.Errorf("member GET repositories: want 403, got %d", code)+ }+ if code := exercise(t, http.MethodGet, path, outsiderUserID); code != http.StatusNotFound {+ t.Errorf("outsider GET repositories: want 404, got %d", code)+ }+ })+t.Run("DELETE installation remains owner/admin only", func(t *testing.T) {// Member: 403 — middleware rejects before the handler runs.if code := exercise(t, http.MethodDelete, "/api/workspaces/"+wsID+"/github/installations/"+uuidToString(createdInst.ID), memberUserID); code != http.StatusForbidden {@@ -2213,6 +2326,134 @@ func TestSignGitHubAppJWT_ClaimsAndSignature(t *testing.T) {}}+func TestFetchGitHubInstallationRepositories(t *testing.T) {+ pemBytes, key := generateTestRSAKeyPEM(t)+ t.Setenv("GITHUB_APP_ID", "424242")+ t.Setenv("GITHUB_APP_PRIVATE_KEY", string(pemBytes))++ const installationID int64 = 314159+ var tokenRevoked bool+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodPost && r.URL.Path == "/app/installations/314159/access_tokens":+ bearer := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")+ if bearer == "" {+ http.Error(w, "missing app jwt", http.StatusUnauthorized)+ return+ }+ if _, err := jwt.Parse(bearer, func(token *jwt.Token) (any, error) {+ return &key.PublicKey, nil+ }); err != nil {+ http.Error(w, "bad app jwt", http.StatusUnauthorized)+ return+ }+ var tokenRequest struct {+ Permissions map[string]string `json:"permissions"`+ }+ if err := json.NewDecoder(r.Body).Decode(&tokenRequest); err != nil {+ http.Error(w, "bad token request", http.StatusBadRequest)+ return+ }+ if !reflect.DeepEqual(tokenRequest.Permissions, map[string]string{"metadata": "read"}) {+ http.Error(w, "overbroad token permissions", http.StatusBadRequest)+ return+ }+ writeJSON(w, http.StatusCreated, map[string]any{"token": "installation-secret"})+ case r.Method == http.MethodGet && r.URL.Path == "/installation/repositories":+ if got := r.Header.Get("Authorization"); got != "Bearer installation-secret" {+ http.Error(w, "bad installation token", http.StatusUnauthorized)+ return+ }+ if r.URL.Query().Get("page") != "2" || r.URL.Query().Get("per_page") != "1" {+ http.Error(w, "bad pagination", http.StatusBadRequest)+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "total_count": 3,+ "repositories": []map[string]any{{+ "id": 9,+ "full_name": "acme/private-repo",+ "html_url": "https://github.com/acme/private-repo",+ "clone_url": "https://github.com/acme/private-repo.git",+ "description": "Private repository",+ "private": true,+ "archived": false,+ "default_branch": "main",+ }},+ })+ case r.Method == http.MethodDelete && r.URL.Path == "/installation/token":+ tokenRevoked = r.Header.Get("Authorization") == "Bearer installation-secret"+ w.WriteHeader(http.StatusNoContent)+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(srv.Close)+ oldBase := githubAPIBase+ githubAPIBase = srv.URL+ t.Cleanup(func() { githubAPIBase = oldBase })++ got, err := fetchGitHubInstallationRepositories(+ context.Background(),+ installationID,+ 2,+ 1,+ )+ if err != nil {+ t.Fatalf("fetchGitHubInstallationRepositories: %v", err)+ }+ if len(got.Repositories) != 1 {+ t.Fatalf("repositories = %d, want 1", len(got.Repositories))+ }+ repository := got.Repositories[0]+ if repository.FullName != "acme/private-repo" || !repository.Private {+ t.Errorf("repository = %+v, want mapped private repository", repository)+ }+ if got.TotalCount != 3 || got.NextPage == nil || *got.NextPage != 3 {+ t.Errorf("pagination = total %d, next %v; want total 3, next 3", got.TotalCount, got.NextPage)+ }+ if !tokenRevoked {+ t.Error("installation token was not revoked after repository listing")+ }+}++func TestListGitHubInstallationRepositoriesRejectsCrossWorkspaceRow(t *testing.T) {+ if testHandler == nil {+ t.Skip("handler test fixture not initialized (no DB?)")+ }+ ctx := context.Background()+ const installationID int64 = 818181+ row, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ InstallationID: installationID,+ AccountLogin: "cross-workspace-acct",+ AccountType: "Organization",+ })+ if err != nil {+ t.Fatalf("CreateGitHubInstallation: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)+ })++ otherWorkspaceID := "11111111-2222-3333-4444-555555555555"+ req := httptest.NewRequest(+ http.MethodGet,+ "/api/workspaces/"+otherWorkspaceID+"/github/installations/"+uuidToString(row.ID)+"/repositories",+ nil,+ )+ rec := httptest.NewRecorder()+ router := chi.NewRouter()+ router.Get(+ "/api/workspaces/{id}/github/installations/{installationId}/repositories",+ testHandler.ListGitHubInstallationRepositories,+ )+ router.ServeHTTP(rec, req)+ if rec.Code != http.StatusNotFound {+ t.Fatalf("cross-workspace row: got %d (%s), want 404", rec.Code, rec.Body.String())+ }+}+// TestFetchInstallationAccount_AuthenticatedPopulatesRow simulates the// GitHub `/app/installations/{id}` endpoint with a JWT-gated mock and// verifies that fetchInstallationAccount, when fully configured,