diff --git a/platform/github-app/README.md b/platform/github-app/README.md index d9011b2e..49211a7c 100644 --- a/platform/github-app/README.md +++ b/platform/github-app/README.md @@ -161,6 +161,108 @@ unavailable greetings fall back to the plain score table. Missing classifier credentials disable intent labeling. Issue and pull request text is never stored; opting in sends it to the configured classification provider. +## Bring your own AI service (BYOK) + +The repository's **AI service** tab lets an administrator choose the platform +service or a separately configured service for that repository. From +, open a repository and select +**AI service**. Supply a public HTTPS API base URL, API key, model identifier and +protocol, save the settings, then explicitly run **Test connection**. Saving or +testing does not enable content classification: intent labels remain off until +the administrator enables them and selects existing repository labels. + +- **OpenAI-compatible Chat Completions (`llm`)** supports both content + classification and generated comment greetings. Comments have their own + opt-in switch and prompt; the author-score table is not an AI code review. +- **Jev Decisions (`jev`)** supports content classification only. It does not + generate greetings. +- **Repository isolation.** Configuration and encrypted credentials belong to + the repository ID and current owner, with live repository permission checks. + Reading needs repository write access; saving, replacing or removing keys, + and connection tests require repository admin access. A different repository + cannot reuse the saved credentials through its settings. Same-owner renames + keep the configuration; transfer to a different owner disables the previous + provider configuration and credentials until the new owner configures the + service explicitly. A key from the previous owner is never inherited. +- **Credential handling.** API keys are encrypted at rest and are never echoed + back into HTML or API responses. A saved-key indicator is not the key itself. + Leave the key input empty to keep a saved key, enter a new key to replace it, + or use the explicit remove-key action. Changing the endpoint or protocol + requires a fresh key so an existing credential cannot be sent to a different + service by changing only its URL. Secrets stay on the server; browser storage and + frontend environment variables must not contain them. +- **Testing and billing.** Test connection is an explicit request using the + saved configuration. It stores no Issue/PR sample text and makes no GitHub + writes. Your provider bills requests made with your key, including the test. + Failure of a repository's own service never silently falls back to the + platform service; optional classification or greeting generation must report + or handle the failure without using platform AI credentials. +- **Endpoint boundary.** Supply an HTTPS base URL with a public hostname, not a + complete request URL with query parameters or a fragment. IP literals, + private/internal hostnames and URL credentials are rejected. Requests do not + follow redirects, so a provider cannot redirect the saved credential to + another host. Select the protocol explicitly; a model name does not select + the protocol for you. Public A/AAAA answers and CNAME chains are checked before + each request, with bounded DNS time and response size. Workers fetch performs + its own DNS lookup afterward, so this is not DNS address pinning and does not + eliminate a rebinding race. Adding private/VPC egress requires a separate + endpoint policy. + +### Operator setup for BYOK + +Apply the additive bot migration `0008_byok.sql` before enabling the repository AI +service routes. It stores provider configuration and encrypted key ciphertext; +it does not put plaintext API keys in D1. Configure the Worker secret +`BYOK_ENCRYPTION_KEY` with **32 random bytes encoded as base64url**. Generate a +new value once with Node's `crypto.randomBytes(32).toString("base64url")` and +install it through Wrangler's secret input, outside version control. This is an +operator encryption secret, separate from a user's provider API key and from +`LLM_API_KEY` or `OPENROUTER_API_KEY`. + +Keep this encryption secret stable across deployments. Replacing it without a +planned re-encryption process makes previously saved keys unreadable. There is +no automatic re-encryption command; affected users must provide their keys again. +Unreadable BYOK keys disable AI without switching to platform credentials. Do not +add it to public Worker vars, the frontend bundle, example configuration or +request logs. BYOK needs the encryption secret even when platform AI providers +are unavailable; platform configuration alone does not enable any repository's +classification switch. + +### BYOK API + +Use the existing `Authorization: Bearer ghf_...` authentication with an +explicit `bot` token scope. Changes and tests recheck current GitHub admin +permission; reads use the existing one-minute permission cache and require +repository write access. These routes do not return the provider API key. + +| Method | Path | Purpose | +| --- | --- | --- | +| `GET` | `/api/v1/repos/{owner}/{repo}/ai-provider` | Read provider metadata. | +| `PATCH` | `/api/v1/repos/{owner}/{repo}/ai-provider` | Choose platform or BYOK settings; optionally replace the key. | +| `POST` | `/api/v1/repos/{owner}/{repo}/ai-provider/test` | Explicitly test the saved connection; send JSON `{}`. | +| `DELETE` | `/api/v1/repos/{owner}/{repo}/ai-provider/key` | Remove the saved BYOK key; send JSON `{}`. | + +Send `Content-Type: application/json` with write/test requests. A BYOK update +contains `mode: "byok"`, `provider: "llm"` or `"jev"`, `base_url`, `model`, and +an optional `api_key`. A first save or an endpoint/protocol change requires a +new `api_key`; omitting it or sending an empty string keeps a valid existing +key only for the same endpoint and protocol. Keys must contain 8–4,096 printable +ASCII characters without internal spaces; outer spaces are trimmed. For Jev, the model must belong to +the supported `typesafe/jev-1.13` family. Use `{"mode":"platform"}` to explicitly +select the operator-managed platform provider. Switching modes does not remove +a saved BYOK credential; use the separate key removal endpoint to do that. +Removing the key selects BYOK with no usable credential, rather than silently +enabling the platform provider. + +Provider metadata contains only +`{mode, provider, base_url, model, has_key, storage_available, ready, updated_at}`. +`has_key` indicates credential presence for the selected service, not the key itself; +`storage_available` reports migration/encryption configuration availability. +`ready` describes locally usable configuration, not a successful upstream +connection test. `updated_at` is an ISO 8601 timestamp string, or `null` +for a configuration without a saved update. Keys, ciphertext, upstream response +bodies and submitted sample text must not be exposed as provider metadata. + ## Desktop console After GitHub sign-in, `/admin` opens the global Dashboard. Its flat metric strip, @@ -192,7 +294,7 @@ numbered items. Changing parallel-consumer completion timestamps does not reorde the task list or legacy setup list (issue #370). Chronological activity and the API's recent-job summary retain their own purposes. -Repository settings have separate settings, preview, backfill, cleanup and +Repository settings have separate settings, AI service, preview, backfill, cleanup and activity tabs. Processing switches require current admin permission and affect future events. Historical scans remain explicit. Intent preview sends a sample title/body to the same classifier using saved, current allowed labels; it never diff --git a/platform/github-app/migrations/0008_byok.sql b/platform/github-app/migrations/0008_byok.sql new file mode 100644 index 00000000..ed5566d2 --- /dev/null +++ b/platform/github-app/migrations/0008_byok.sql @@ -0,0 +1,14 @@ +-- Optional repository-owned AI provider configuration. Plaintext API keys are +-- never stored. encrypted_key contains versioned AES-GCM ciphertext and nonce; +-- its authenticated data binds repository, owner, provider and canonical URL. +CREATE TABLE ai_providers ( + repository INTEGER PRIMARY KEY, + owner TEXT NOT NULL, + mode TEXT NOT NULL CHECK(mode IN ('platform','byok')), + provider TEXT NOT NULL CHECK(provider IN ('llm','jev')), + base_url TEXT NOT NULL, + model TEXT NOT NULL, + encrypted_key TEXT, + updated INTEGER NOT NULL, + updated_by TEXT NOT NULL +); diff --git a/platform/github-app/scripts/dev-dashboard.mts b/platform/github-app/scripts/dev-dashboard.mts index 8c23fa25..8381928a 100644 --- a/platform/github-app/scripts/dev-dashboard.mts +++ b/platform/github-app/scripts/dev-dashboard.mts @@ -29,6 +29,7 @@ async function main() { const sessionId = randomUUID(); const userToken = "local-dashboard-fixture-user-token"; const secret = randomBytes(32).toString("hex"); + const byokSecret = randomBytes(32).toString("base64url"); const now = Date.now(); const jevEndpoint = "https://openrouter.ai/api/alpha/decisions"; let openrouterKey = ""; @@ -67,6 +68,11 @@ async function main() { let lastDecision: { status: number; latencyMs: number; requestVersion: string; requestSha256: string; model?: string; usage?: { inputTokens: number; outputTokens: number; cost?: number } } | null = null; const outbound = async (request: Request) => { const url = new URL(request.url); + // Only the explicit live preview may query the fixed public DoH service, + // and only for the real provider used in this fixture. Never forward auth. + if (liveJev && url.origin === "https://cloudflare-dns.com" && url.pathname === "/dns-query" && + url.searchParams.get("name") === "openrouter.ai" && ["1", "28"].includes(url.searchParams.get("type") || "") && request.method === "GET") + return fetch(url.href, { headers: { Accept: "application/dns-json" }, redirect: "manual", signal: AbortSignal.timeout(5000) }); if (liveJev && request.url === jevEndpoint && request.method === "POST") { if (request.headers.get("authorization") !== `Bearer ${openrouterKey}`) return Response.json({ error: "Unexpected model credential" }, { status: 403 }); @@ -158,6 +164,7 @@ async function main() { bindings: { APP_ID: "123", APP_SLUG: "ghfind-review", APP_CLIENT_ID: "local-fixture-client", APP_CLIENT_SECRET: "local-fixture-secret", APP_PRIVATE_KEY: privateKey, WEBHOOK_SECRET: "local-fixture-webhook", SESSION_SECRET: secret, + BYOK_ENCRYPTION_KEY: byokSecret, ENABLED: "true", EMAIL_ENABLED: "false", EMAIL_FROM: "preview@example.invalid", ALLOWED_ACCOUNTS: installationCount === 2 ? "sample,harbor" : "sample", LLM_BASE_URL: "", LLM_MODEL: "", TRIAGE_PROVIDER: liveJev ? "jev" : "llm", OPENROUTER_API_KEY: openrouterKey, JEV_MODEL: "typesafe/jev-1.13", JEV_THRESHOLD: "0.8", @@ -166,15 +173,15 @@ async function main() { await mf.ready; console.log("Local Worker runtime ready; applying actual D1 migrations..."); const db = await mf.getD1Database("DB"); - const migrations = (await readdir(join(appRoot, "migrations"))).filter((name) => /^000[1-7]_.*\.sql$/.test(name)).sort(); - if (migrations.length !== 7) throw new Error("Expected all seven actual Worker migrations"); + const migrations = (await readdir(join(appRoot, "migrations"))).filter((name) => /^000[1-8]_.*\.sql$/.test(name)).sort(); + if (migrations.length !== 8) throw new Error("Expected all eight actual Worker migrations"); const migrationStatements = []; for (const migration of migrations) { for (const sql of unstable_splitSqlQuery(await readFile(join(appRoot, "migrations", migration), "utf8"))) migrationStatements.push(db.prepare(sql)); } await db.batch(migrationStatements); - console.log("All seven migrations applied; seeding synthetic dashboard rows..."); + console.log("All eight migrations applied; seeding synthetic dashboard rows..."); // Same AES-GCM format and session lookup used by production authentication. if (!globalThis.crypto) Object.defineProperty(globalThis, "crypto", { value: webcrypto }); const encrypted = await seal({ SESSION_SECRET: secret } as Env, userToken); @@ -236,7 +243,7 @@ async function main() { const currentLedger = async () => { // Loopback-only read-only diagnostics of the real D1 fixture ledger. Hashes // demonstrate preview admission did not update existing rows or save input. - const tables = ["jobs", "audit_log", "triage_labels", "repo_settings"] as const; + const tables = ["jobs", "audit_log", "triage_labels", "repo_settings", "ai_providers"] as const; const rows = await db.batch(tables.flatMap(table => [db.prepare(`SELECT COUNT(*) AS count FROM ${table}`), db.prepare(`SELECT * FROM ${table} ORDER BY rowid LIMIT 1000`)])); return Object.fromEntries(tables.map((table, index) => { const count = Number(rows[index * 2].results[0].count); return [table, { count, truncated: count > 1000, sha256: createHash("sha256").update(JSON.stringify(rows[index * 2 + 1].results)).digest("hex") }]; })); }; diff --git a/platform/github-app/src/admin-i18n.ts b/platform/github-app/src/admin-i18n.ts index d56c772b..533b3e2f 100644 --- a/platform/github-app/src/admin-i18n.ts +++ b/platform/github-app/src/admin-i18n.ts @@ -3,7 +3,8 @@ import type { Locale } from "./i18n"; const baseKeys = ["overview","repositories","tasks","activity","installations","workspace","navigation","openMenu","closeMenu","overviewLead","repositoriesLead","tasksLead","activityLead","search","filter","all","active","paused","on","off","admin","readOnly","updated","openSettings","page","previous","next","scoped","scope","partial","window","jobs","pending","running","failed","done","recentTasks","viewAll","repositoryStatus","noActivity","noResults","processingHint","settings","settingsHint","saveHint","backfillHelp","cleanupHelp","allRetained","due","stale","preview","previewLead","previewDisclosure","previewTitle","previewBody","previewKind","issue","pullRequest","runPreview","previewOnly","previewCandidates","previewNoMatch","previewSelected","previewThreshold","previewInvalid","previewNoCandidates","previewNotConfigured","previewRateLimited","previewUnavailable","cleanupTasks","scanned","nextRepoPage","historyLimit","cleanupLimit"] as const; const globalKeys = ["allAccounts","globalLead","globalCoverage","globalPartial","accounts","accountsLead","writableRepositories","visibleRepositories","workQueue","accountDashboard","accountPage","coverageLimited"] as const; const interactionKeys = ["switchAccount", "currentAccount", "manageInstallations", "clearSearch", "submitting", "submittedHint", "accountScope", "unsavedChanges"] as const; -const keys = [...baseKeys, ...interactionKeys, ...globalKeys] as const; +const aiKeys = ["aiService","aiLead","aiMode","aiPlatform","aiByok","aiProtocol","aiOpenAI","aiJev","aiBaseUrl","aiModel","aiKey","aiKeySaved","aiKeyMissing","aiKeyHint","aiSave","aiTest","aiTestHint","aiRemove","aiRemoveConfirm","aiRemoved","aiSaved","aiTested","aiInvalid","aiKeyRequired","aiStorageUnavailable","aiUnavailable","aiRateLimited","aiPrivacy","aiCapabilities","aiNoFallback","aiReady","aiNotReady","aiPlatformHint","aiShowKey","aiHideKey"] as const; +const keys = [...baseKeys, ...interactionKeys, ...globalKeys, ...aiKeys, "aiGreetingsUnavailable", "aiModelHint", "aiSavedConfiguration"] as const; export type AdminMessages = Record; const interactionCatalogs: Record = { en: "Switch account|Current account|Manage installations|Clear search|Submitting…|Waiting for the server. Please keep this page open.|GitHub account|You have unsaved settings. Leave this page and discard your changes?", @@ -39,8 +40,39 @@ const globalCatalogs: Record = { vi: "Tất cả tài khoản|Tác vụ, điều khiển kho mã và thay đổi gần đây trên các tài khoản GitHub.|Đã kiểm tra {checked}/{total} tài khoản · {authorized} kho mã có quyền ghi trong {checkedRepos} kho đã kiểm tra.|Phạm vi giới hạn ở các tài khoản và trang kho mã hiển thị. Chuyển trang để xem phần còn lại.|Tài khoản|Quyền hiện tại và tác vụ lưu trữ trong phạm vi tài khoản và kho mã hiển thị.|Kho mã có quyền ghi|Kho mã đang hiển thị|Hàng đợi tác vụ|Mở bảng điều khiển tài khoản|Trang tài khoản|Phạm vi hạn chế", ar: "جميع الحسابات|المهام وعناصر التحكم في المستودعات والتغييرات الأخيرة عبر حسابات GitHub.|تم فحص {checked} من {total} حسابات · {authorized} مستودعات قابلة للكتابة من {checkedRepos} تم فحصها.|تقتصر التغطية على الحسابات وصفحة المستودعات المعروضة. استخدم الصفحات لفحص النطاق المتبقي.|الحسابات|الصلاحيات الحالية والمهام المحفوظة ضمن نطاق الحسابات والمستودعات المعروض.|المستودعات القابلة للكتابة|المستودعات المعروضة|قائمة المهام|فتح لوحة تحكم الحساب|صفحة الحسابات|تغطية محدودة", }; +const aiCatalogs: Record = { + en: "AI service|Choose this repository’s AI service. Processing and allowed labels stay unchanged.|Service mode|Platform service|Your own provider (BYOK)|Protocol|OpenAI compatible|Jev classifier|Base URL|Model|API key|A key is saved; its value is hidden.|No key is saved.|Leave blank to keep the saved key. Changing the URL or protocol requires a new key.|Save service|Test connection|Tests the saved configuration with a small synthetic request. Save changes first. Your provider may charge for this test.|Delete key|I confirm deletion of this repository’s saved key.|The saved key was deleted.|AI service saved.|Connection test succeeded.|Check the protocol, HTTPS base URL, and model.|Enter a new API key when changing the URL or protocol.|Secure key storage is unavailable. Contact the platform administrator.|The saved AI service could not be reached or authenticated. Check its settings and try again.|Too many connection tests. Try again in a minute.|In BYOK mode, when enabled, issue or PR titles, bodies and label candidates are sent to your endpoint. Your provider bills you. This configuration applies only to this repository.|Jev supports label classification only. OpenAI compatible services can also generate AI greetings.|An unavailable BYOK service never falls back to the platform. Saving a service does not enable intent labeling or comments.|Ready|Not ready|Uses the platform’s configured AI service. Custom-provider fields apply only in BYOK mode.|Show key|Hide key", + zh: "AI 服务|选择本仓库的 AI 服务,处理开关和允许标签保持不变。|服务模式|平台服务|自有服务(BYOK)|协议|OpenAI 兼容|Jev 分类器|基础 URL|模型|API 密钥|已保存密钥,其内容不会显示。|尚未保存密钥。|留空保留原密钥。更改 URL 或协议时必须输入新密钥。|保存服务|测试连接|用少量虚构内容测试已保存的配置,请先保存更改。服务商可能对此测试收费。|删除密钥|我确认删除本仓库已保存的密钥。|已删除保存的密钥。|已保存 AI 服务。|连接测试成功。|请检查协议、HTTPS 基础 URL 和模型。|更改 URL 或协议时请输入新 API 密钥。|安全密钥存储不可用,请联系平台管理员。|无法连接或验证已保存的 AI 服务,请检查配置后重试。|连接测试过多,请稍等一分钟再试。|在 BYOK 模式下,启用后 Issue 或 PR 的标题、正文和候选标签会发送到你的服务端点,费用由你的服务商收取。此配置仅适用于本仓库。|Jev 仅支持标签分类;OpenAI 兼容服务还可生成 AI 欢迎语。|自有服务不可用时不会回退到平台。保存服务不会自动启用意图标签或评论。|已就绪|未就绪|使用平台配置的 AI 服务。自有服务字段仅适用于 BYOK 模式。|显示密钥|隐藏密钥", + ja: "AI サービス|本リポジトリの AI サービスを選択します。処理と許可ラベルは変更されません。|サービスモード|プラットフォームのサービス|独自プロバイダー(BYOK)|プロトコル|OpenAI 互換|Jev 分類器|ベース URL|モデル|API キー|キーは保存済みです。値は表示されません。|キーは未保存です。|空欄なら保存済みキーを維持します。URL またはプロトコルの変更には新しいキーが必要です。|サービスを保存|接続をテスト|少量の架空データで保存済み設定をテストします。先に保存してください。料金が発生する場合があります。|キーを削除|本リポジトリの保存済みキーの削除を確認します。|キーを削除しました。|AI サービスを保存しました。|接続テストに成功しました。|プロトコル、HTTPS ベース URL、モデルを確認してください。|URL またはプロトコルを変更する場合、新しい API キーを入力してください。|安全なキー保存を利用できません。管理者にお問い合わせください。|保存済みサービスへの接続または認証に失敗しました。設定を確認して再試行してください。|テストが多すぎます。1分後に再試行してください。|BYOK モードで有効にすると Issue や PR のタイトル、本文、候補ラベルを独自のエンドポイントに送信します。料金はプロバイダーから請求されます。本リポジトリのみに適用されます。|Jev はラベル分類のみ対応します。OpenAI 互換サービスは AI 挨拶文も生成できます。|BYOK が利用できなくてもプラットフォームに切り替わりません。保存してもラベルやコメントは有効になりません。|準備完了|未準備|プラットフォームの AI サービスを使用します。独自プロバイダーの項目は BYOK モード専用です。|キーを表示|キーを隠す", + ko: "AI 서비스|이 저장소의 AI 서비스를 선택하세요. 처리 및 허용 라벨 설정은 바뀌지 않습니다.|서비스 모드|플랫폼 서비스|자체 제공업체 (BYOK)|프로토콜|OpenAI 호환|Jev 분류기|기본 URL|모델|API 키|키가 저장되어 있으며 값은 표시되지 않습니다.|저장된 키가 없습니다.|비워 두면 원래 키를 유지합니다. URL 또는 프로토콜 변경에는 새 키가 필요합니다.|서비스 저장|연결 테스트|가상 요청으로 저장된 설정을 테스트합니다. 먼저 저장하세요. 제공업체가 요금을 청구할 수 있습니다.|키 삭제|이 저장소에 저장된 키 삭제를 확인합니다.|키를 삭제했습니다.|AI 서비스를 저장했습니다.|연결 테스트에 성공했습니다.|프로토콜, HTTPS 기본 URL 및 모델을 확인하세요.|URL 또는 프로토콜 변경 시 새 API 키를 입력하세요.|보안 키 저장소를 사용할 수 없습니다. 관리자에게 문의하세요.|저장된 서비스에 연결하거나 인증할 수 없습니다. 설정을 확인하고 다시 시도하세요.|테스트가 너무 많습니다. 1분 후 다시 시도하세요.|BYOK 모드에서 활성화하면 Issue 또는 PR 제목, 본문과 후보 라벨을 자체 엔드포인트에 전송합니다. 제공업체가 비용을 청구합니다. 이 저장소에만 적용됩니다.|Jev는 라벨 분류만 지원합니다. OpenAI 호환 서비스는 AI 인사말도 생성할 수 있습니다.|BYOK 실패 시 플랫폼으로 전환하지 않습니다. 저장해도 라벨이나 댓글은 활성화되지 않습니다.|준비됨|준비 안 됨|플랫폼에 설정된 AI 서비스를 사용합니다. 자체 제공업체 필드는 BYOK 모드 전용입니다.|키 표시|키 숨기기", + es: "Servicio de IA|Elige la IA de este repositorio. El procesamiento y las etiquetas permitidas no cambian.|Modo de servicio|Servicio de la plataforma|Proveedor propio (BYOK)|Protocolo|Compatible con OpenAI|Clasificador Jev|URL base|Modelo|Clave API|Hay una clave guardada; su valor está oculto.|No hay clave guardada.|Déjalo vacío para conservar la clave. Cambiar la URL o el protocolo requiere una clave nueva.|Guardar servicio|Probar conexión|Prueba la configuración guardada con una petición ficticia. Guarda antes. Tu proveedor puede cobrar por la prueba.|Eliminar clave|Confirmo eliminar la clave guardada de este repositorio.|Se eliminó la clave.|Servicio de IA guardado.|La conexión se probó correctamente.|Revisa el protocolo, la URL base HTTPS y el modelo.|Introduce una clave nueva al cambiar la URL o el protocolo.|El almacenamiento seguro no está disponible. Contacta al administrador.|No se pudo conectar o autenticar el servicio. Revisa su configuración e inténtalo de nuevo.|Demasiadas pruebas. Inténtalo en un minuto.|En modo BYOK, al activarlo, los títulos, contenidos y etiquetas candidatas de issues o PR se envían a tu endpoint. Tu proveedor te cobra. Solo se aplica a este repositorio.|Jev solo clasifica etiquetas. Los servicios compatibles con OpenAI también generan saludos de IA.|BYOK nunca usa la plataforma como alternativa si falla. Guardarlo no activa etiquetas ni comentarios.|Listo|No preparado|Usa el servicio de IA de la plataforma. Los campos del proveedor propio solo se aplican en BYOK.|Mostrar clave|Ocultar clave", + pt: "Serviço de IA|Escolha a IA deste repositório. O processamento e os rótulos permitidos não mudam.|Modo de serviço|Serviço da plataforma|Seu provedor (BYOK)|Protocolo|Compatível com OpenAI|Classificador Jev|URL base|Modelo|Chave de API|Uma chave está salva; seu valor está oculto.|Nenhuma chave salva.|Deixe em branco para manter a chave. Alterar URL ou protocolo exige uma nova chave.|Salvar serviço|Testar conexão|Testa a configuração salva com uma solicitação fictícia. Salve antes. Seu provedor pode cobrar pelo teste.|Excluir chave|Confirmo a exclusão da chave salva deste repositório.|A chave foi excluída.|Serviço de IA salvo.|Teste de conexão concluído.|Confira o protocolo, a URL base HTTPS e o modelo.|Insira uma nova chave ao alterar a URL ou o protocolo.|O armazenamento seguro não está disponível. Contate o administrador.|Não foi possível conectar ou autenticar o serviço. Confira a configuração e tente novamente.|Muitos testes. Tente novamente em um minuto.|No modo BYOK, quando ativado, títulos, conteúdo e rótulos candidatos de issues ou PR são enviados ao seu endpoint. Seu provedor cobra de você. Vale apenas para este repositório.|Jev oferece apenas classificação de rótulos. Serviços compatíveis com OpenAI também geram saudações de IA.|BYOK nunca recorre à plataforma se falhar. Salvar não ativa rótulos nem comentários.|Pronto|Não pronto|Usa a IA configurada na plataforma. Campos do provedor próprio só se aplicam em BYOK.|Mostrar chave|Ocultar chave", + id: "Layanan AI|Pilih AI repositori ini. Pengaturan pemrosesan dan label tidak berubah.|Mode layanan|Layanan platform|Penyedia sendiri (BYOK)|Protokol|Kompatibel OpenAI|Pengklasifikasi Jev|URL dasar|Model|Kunci API|Kunci tersimpan; nilainya disembunyikan.|Belum ada kunci tersimpan.|Kosongkan untuk mempertahankan kunci. Mengubah URL atau protokol memerlukan kunci baru.|Simpan layanan|Uji koneksi|Menguji konfigurasi tersimpan dengan permintaan sintetis. Simpan dahulu. Penyedia dapat mengenakan biaya.|Hapus kunci|Saya mengonfirmasi penghapusan kunci repositori ini.|Kunci telah dihapus.|Layanan AI tersimpan.|Uji koneksi berhasil.|Periksa protokol, URL dasar HTTPS, dan model.|Masukkan kunci baru saat mengubah URL atau protokol.|Penyimpanan aman tidak tersedia. Hubungi administrator.|Layanan tidak dapat dihubungi atau diautentikasi. Periksa pengaturan lalu coba lagi.|Terlalu banyak uji. Coba dalam satu menit.|Dalam mode BYOK, saat aktif, judul, isi, dan kandidat label issue atau PR dikirim ke endpoint Anda. Penyedia menagih Anda. Hanya berlaku untuk repositori ini.|Jev hanya mendukung klasifikasi label. Layanan kompatibel OpenAI juga menghasilkan sapaan AI.|BYOK yang gagal tidak beralih ke platform. Menyimpan tidak mengaktifkan label atau komentar.|Siap|Belum siap|Menggunakan AI platform. Bidang penyedia sendiri hanya berlaku dalam mode BYOK.|Tampilkan kunci|Sembunyikan kunci", + vi: "Dịch vụ AI|Chọn AI của kho mã này. Cài đặt xử lý và nhãn không đổi.|Chế độ dịch vụ|Dịch vụ nền tảng|Nhà cung cấp riêng (BYOK)|Giao thức|Tương thích OpenAI|Bộ phân loại Jev|URL cơ sở|Mô hình|Khóa API|Đã lưu khóa; giá trị được ẩn.|Chưa lưu khóa.|Để trống để giữ khóa. Đổi URL hoặc giao thức cần khóa mới.|Lưu dịch vụ|Kiểm tra kết nối|Kiểm tra cấu hình đã lưu bằng yêu cầu giả lập. Hãy lưu trước. Nhà cung cấp có thể tính phí.|Xóa khóa|Tôi xác nhận xóa khóa của kho mã này.|Đã xóa khóa.|Đã lưu dịch vụ AI.|Kiểm tra kết nối thành công.|Kiểm tra giao thức, URL cơ sở HTTPS và mô hình.|Nhập khóa mới khi đổi URL hoặc giao thức.|Bộ lưu trữ an toàn không khả dụng. Liên hệ quản trị viên.|Không thể kết nối hoặc xác thực dịch vụ. Kiểm tra cài đặt và thử lại.|Quá nhiều lần kiểm tra. Thử lại sau một phút.|Ở chế độ BYOK, khi bật, tiêu đề, nội dung và nhãn ứng viên của issue hoặc PR được gửi đến endpoint của bạn. Nhà cung cấp tính phí cho bạn. Chỉ áp dụng cho kho mã này.|Jev chỉ phân loại nhãn. Dịch vụ tương thích OpenAI còn tạo lời chào AI.|BYOK thất bại sẽ không chuyển sang nền tảng. Lưu không bật nhãn hay bình luận.|Sẵn sàng|Chưa sẵn sàng|Dùng AI của nền tảng. Các trường nhà cung cấp riêng chỉ áp dụng ở BYOK.|Hiện khóa|Ẩn khóa", + ar: "خدمة الذكاء الاصطناعي|اختر خدمة هذا المستودع. لا تتغير المعالجة والتسميات المسموحة.|وضع الخدمة|خدمة المنصة|مزودك الخاص (BYOK)|البروتوكول|متوافق مع OpenAI|مصنف Jev|عنوان URL الأساسي|النموذج|مفتاح API|تم حفظ مفتاح وقيمته مخفية.|لا يوجد مفتاح محفوظ.|اتركه فارغًا للاحتفاظ بالمفتاح. تغيير العنوان أو البروتوكول يتطلب مفتاحًا جديدًا.|حفظ الخدمة|اختبار الاتصال|يختبر الإعدادات المحفوظة بطلب اصطناعي صغير. احفظ أولًا. قد يفرض مزودك رسومًا.|حذف المفتاح|أؤكد حذف مفتاح هذا المستودع المحفوظ.|تم حذف المفتاح.|تم حفظ الخدمة.|نجح اختبار الاتصال.|تحقق من البروتوكول وعنوان HTTPS الأساسي والنموذج.|أدخل مفتاحًا جديدًا عند تغيير العنوان أو البروتوكول.|التخزين الآمن غير متاح. اتصل بالمسؤول.|تعذر الاتصال بالخدمة أو مصادقتها. تحقق من الإعدادات وحاول مجددًا.|اختبارات كثيرة. حاول بعد دقيقة.|في وضع BYOK، عند التفعيل تُرسل عناوين issues أو PR ومحتواها والتسميات المرشحة إلى عنوانك. يتحمل حسابك لدى المزود التكلفة. يخص هذا المستودع فقط.|يدعم Jev تصنيف التسميات فقط. تنشئ الخدمات المتوافقة مع OpenAI تحيات أيضًا.|لا ترجع BYOK إلى المنصة عند الفشل. حفظ الخدمة لا يفعّل التسميات أو التعليقات.|جاهز|غير جاهز|يستخدم خدمة المنصة. حقول المزود الخاص تخص وضع BYOK فقط.|إظهار المفتاح|إخفاء المفتاح", +}; +const aiSupplement: Record = { + en: "This repository has no AI greeting service configured. Enabled comments use the plain score template.|For Jev use typesafe/jev-1.13 or a dated model such as typesafe/jev-1.13-20260917.|Saved service", + zh: "本仓库尚未配置可生成 AI 问候的服务。启用评论后将使用固定的评分模板。|Jev 模型需为 typesafe/jev-1.13 或带日期的版本,如 typesafe/jev-1.13-20260917。|已保存的服务", + ja: "本リポジトリに AI 挨拶サービスが設定されていません。有効なコメントには定型のスコアテンプレートを使用します。|Jev は typesafe/jev-1.13 または typesafe/jev-1.13-20260917 のような日付付きモデルを使用してください。|保存済みサービス", + ko: "이 저장소에 AI 인사말 서비스가 설정되지 않았습니다. 활성화된 댓글은 기본 점수 템플릿을 사용합니다.|Jev는 typesafe/jev-1.13 또는 typesafe/jev-1.13-20260917 같은 날짜 버전을 사용하세요.|저장된 서비스", + es: "Este repositorio no tiene un servicio de saludos de IA configurado. Los comentarios usan la plantilla de puntuación simple.|Para Jev usa typesafe/jev-1.13 o una versión fechada como typesafe/jev-1.13-20260917.|Servicio guardado", + pt: "Este repositório não tem serviço de saudações de IA configurado. Os comentários usam o modelo simples de pontuação.|Para Jev use typesafe/jev-1.13 ou uma versão datada como typesafe/jev-1.13-20260917.|Serviço salvo", + id: "Repositori ini belum memiliki layanan sapaan AI. Komentar aktif memakai templat skor biasa.|Untuk Jev gunakan typesafe/jev-1.13 atau versi bertanggal seperti typesafe/jev-1.13-20260917.|Layanan tersimpan", + vi: "Kho mã này chưa cấu hình dịch vụ lời chào AI. Bình luận đang bật dùng mẫu điểm cơ bản.|Với Jev, dùng typesafe/jev-1.13 hoặc bản có ngày như typesafe/jev-1.13-20260917.|Dịch vụ đã lưu", + ar: "لم يُضبط لهذا المستودع خدمة تحيات بالذكاء الاصطناعي. تستخدم التعليقات المفعلة قالب الدرجة البسيط.|استخدم مع Jev النموذج typesafe/jev-1.13 أو إصدارًا مؤرخًا مثل typesafe/jev-1.13-20260917.|الخدمة المحفوظة", +}; export const ADMIN_MESSAGES = Object.fromEntries(Object.entries(catalogs).map(([locale, text]) => { - const values = (text + "|" + interactionCatalogs[locale as Locale] + "|" + globalCatalogs[locale as Locale]).split("|"); + const values = (text + "|" + interactionCatalogs[locale as Locale] + "|" + globalCatalogs[locale as Locale] + "|" + aiCatalogs[locale as Locale] + "|" + aiSupplement[locale as Locale]).split("|"); if (values.length !== keys.length) throw new Error(`Incomplete admin catalog: ${locale}`); return [locale, Object.fromEntries(keys.map((key, i) => [key, values[i]]))]; })) as Record; + +/** Known service actions never expose implementation names or stored details. */ +export function aiAuditLabel(locale: Locale, action: string): string | undefined { + const d = ADMIN_MESSAGES[locale]; + if (action === "ai_provider.update") return d.aiSaved; + if (action === "ai_provider.key_remove") return d.aiRemoved; + if (action === "ai_provider.test") return d.aiTested; + return undefined; +} diff --git a/platform/github-app/src/admin-script.ts b/platform/github-app/src/admin-script.ts index 4d858fdd..49db42ac 100644 --- a/platform/github-app/src/admin-script.ts +++ b/platform/github-app/src/admin-script.ts @@ -36,7 +36,11 @@ pickers.forEach(p=>{const trigger=p.querySelector('summary'),links=()=>[...p.que }); document.addEventListener('click',e=>{if(!pickers.some(p=>p.contains(e.target)))closePickers()}); menu?.addEventListener('click',()=>closePickers()); -const settingsForm=document.querySelector('form[action^="/admin/repo?"]'),language=document.getElementById('lang'),originalLanguage=language?.value; +const aiForm=document.querySelector('.ai-provider-form'); +const syncAIFields=()=>{if(!aiForm)return;const own=aiForm.querySelector('input[name=mode]:checked')?.value==='byok',fields=aiForm.querySelector('[data-ai-byok-fields]'),platform=aiForm.querySelector('[data-ai-platform-hint]');if(fields)fields.hidden=!own;if(platform)platform.hidden=own;['base_url','model'].forEach(name=>{const input=aiForm.querySelector('[name='+name+']');if(input)input.required=own})}; +aiForm?.addEventListener('change',e=>{if(e.target.name==='mode')syncAIFields()});syncAIFields(); +document.querySelectorAll('[data-key-visibility]').forEach(button=>button.addEventListener('click',()=>{const input=document.getElementById(button.getAttribute('aria-controls'));if(!input)return;const show=input.type==='password';input.type=show?'text':'password';button.setAttribute('aria-pressed',String(show));button.textContent=show?button.dataset.hide:button.dataset.show})); +const settingsForm=document.querySelector('form[data-settings-form],form[action^="/admin/repo?"]'),language=document.getElementById('lang'),originalLanguage=language?.value; const snapshot=()=>settingsForm?JSON.stringify([...new FormData(settingsForm)].map(([key,value])=>[key,typeof value==='string'?value:value.name])):''; const initialSettings=snapshot();let leaving=false; const dirty=()=>!!settingsForm&&!leaving&&snapshot()!==initialSettings; @@ -55,7 +59,7 @@ document.addEventListener('submit',e=>{const form=e.target;if(!(form instanceof if(form===settingsForm)leaving=true;form.setAttribute('aria-busy','true');form.setAttribute('data-pending','');buttons.forEach(b=>b.setAttribute('aria-disabled','true'));if(e.submitter?.tagName==='BUTTON')e.submitter.textContent=app?.dataset.submitting||'Submitting…'; state.status.className='form-pending';state.status.setAttribute('role','status');state.status.textContent=app?.dataset.submitHint||'Waiting for the server.';form.append(state.status);pending.set(form,state); }); -addEventListener('pageshow',e=>{restoreForms();if(e.persisted){leaving=false;if(side?.hasAttribute('data-open'))setOpen(false);closePickers()}}); +addEventListener('pageshow',e=>{restoreForms();syncAIFields();if(e.persisted){leaving=false;if(side?.hasAttribute('data-open'))setOpen(false);closePickers()}}); document.querySelectorAll('[data-local-filter]').forEach(form=>{const search=form.querySelector('input[type=search]'),status=form.querySelector('select[name=processing]'),clear=form.querySelector('[data-search-clear]'),rows=[...document.querySelectorAll('[data-repo-row]')],empty=document.querySelector('[data-filter-empty]'); const filter=sync=>{const q=(search?.value||'').trim().toLowerCase(),s=status?.value||'';let count=0;rows.forEach(row=>{const visible=(!q||row.dataset.repoName.toLowerCase().includes(q))&&(!s||row.dataset.processing===s);row.hidden=!visible;if(visible)count++});if(empty)empty.hidden=count>0;if(clear)clear.hidden=!search?.value; if(sync){const u=new URL(location.href);if(search?.value.trim())u.searchParams.set('q',search.value.trim());else u.searchParams.delete('q');if(s)u.searchParams.set('processing',s);else u.searchParams.delete('processing');history.replaceState(history.state,'',u.pathname+u.search+u.hash);document.querySelectorAll('[data-repo-pagination] a,[data-repo-settings],[data-repo-row] a[href^="/admin/repo?"],[data-repo-toggle]').forEach(element=>{const attribute=element.tagName==='FORM'?'action':'href',link=new URL(element.getAttribute(attribute),location.origin),prefix=element.closest('[data-repo-pagination]')?'':'return_';[['q',search?.value.trim()||''],['processing',s]].forEach(([key,value])=>{if(value)link.searchParams.set(prefix+key,value);else link.searchParams.delete(prefix+key)});element.setAttribute(attribute,link.pathname+link.search)})} diff --git a/platform/github-app/src/admin-style.ts b/platform/github-app/src/admin-style.ts index d305e949..ab2833e4 100644 --- a/platform/github-app/src/admin-style.ts +++ b/platform/github-app/src/admin-style.ts @@ -10,5 +10,7 @@ export const ADMIN_STYLE = ` @media(max-width:1100px){.admin-main,.admin-top{padding-inline:22px}.workspace-split{grid-template-columns:1fr;gap:0}.workspace-split>.work-section+section{border-inline-start:0;padding-inline-start:0}.admin-top .navlink{display:none}.account-name{max-width:190px}} @media(max-width:950px){.admin-app{grid-template-columns:190px minmax(0,1fr)}.sidebar{padding-inline:8px}.repo-operation{grid-template-columns:1fr}.operation-help{border-inline-start:0!important;padding-inline-start:0!important}.setting-section{grid-template-columns:190px minmax(0,1fr);gap:24px}.repo-settings .settings-grid{grid-template-columns:1fr}.kpi{padding-inline:16px}.admin-top .tools{gap:5px}.admin-top #lang{max-width:90px}} @media(max-width:720px){.admin-app{display:block}.sidebar{position:fixed;inset-block:0;inset-inline-start:0;width:260px;max-width:85vw;height:100dvh;transform:translateX(-100%);visibility:hidden;transition:transform .15s}.admin-app[dir=rtl] .sidebar,[dir=rtl] .sidebar{transform:translateX(100%)}.sidebar[data-open]{transform:translateX(0)!important;visibility:visible}.sidebar-close{display:grid;place-items:center;position:absolute;top:16px;inset-inline-end:12px;width:40px;height:40px;border:1px solid var(--border);border-radius:4px;background:var(--bg);color:var(--fg);cursor:pointer}.sidebar-overlay[data-open]{display:block;position:fixed;inset:0;background:#0006;z-index:15}.mobile-menu{display:grid;place-items:center;width:36px;height:36px;flex:none;border:1px solid var(--border);border-radius:4px;background:var(--bg);color:var(--fg);cursor:pointer}.side-link{min-height:44px}.admin-top{position:sticky;top:0;z-index:8;flex-wrap:wrap;gap:8px;padding:8px 16px;min-height:56px}.context{max-width:100%;gap:6px}.account-name{max-width:140px}.account-static{gap:4px}.context>.account-static>.context-badge{display:none}.account-picker summary>.context-badge{display:none}.account-picker summary{gap:5px;padding:0 4px}.account-chevron{margin-inline-start:3px}.account-popover{max-width:calc(100vw - 64px)}.account-popover .context-badge{display:grid}.context-manage{padding:7px 6px;font-size:10px;min-height:36px;display:flex;align-items:center}.admin-top .tools{margin-inline-start:auto;max-width:100%}.admin-top .theme button{width:25px;height:25px}.admin-main{padding:22px 16px 30px}.page-head{flex-wrap:wrap;gap:14px;margin-bottom:18px}.page-head h1{font-size:22px}.page-head p{font-size:12px}.kpi-strip{grid-template-columns:repeat(2,minmax(0,1fr));margin-bottom:22px}.kpi{padding:16px 12px}.kpi:nth-child(2){border-inline-end:0}.kpi:nth-child(n+3){border-top:1px solid var(--border)}.kpi:nth-child(3){padding-inline-start:0}.kpi-value{font-size:26px}.kpi-hint{font-size:10px}.filter-bar{gap:10px}.filter-bar .search-field{max-width:none;min-width:200px}.filter-bar select{max-width:210px}.work-section{margin-bottom:24px!important}.setting-section{grid-template-columns:1fr;gap:14px;padding:20px 0}.setting-description{max-width:100%}.setting-controls{max-width:none}.repo-tabs{gap:20px;margin-bottom:20px}.repo-operation{gap:20px}.settings-save{padding:12px 0}.settings-save p{max-width:170px}.settings-save .btn{white-space:nowrap}.pagination{align-items:flex-start}.pagination .actions{gap:6px}.admin-foot{padding:16px}.installation-directory .context-badge{display:none}.admin-main .table td{padding:12px}.admin-main .btn,.filter-bar select{min-height:40px}.filter-bar input[type=search],.filter-bar input[type=text],.preview-form input[type=text],.admin-main textarea{font-size:16px;min-height:44px}.setting-description p,.operation-help p{font-size:13px}.scope-note{font-size:12px;gap:6px;padding-bottom:14px}} +.ai-fields{display:grid;gap:12px}.ai-fields .field{min-width:0}.ai-fields input[type=url],.ai-fields input[type=text],.ai-fields input[type=password]{width:100%;min-width:0;padding:10px 12px;border:1px solid var(--border);border-radius:4px;background:var(--bg);color:var(--fg);font:inherit;font-size:13px}.ai-fields .field select{max-width:100%;min-height:38px;border-radius:4px}.credential-field{display:flex;align-items:center;gap:8px;min-width:0}.credential-field input{flex:1}.credential-field .btn{flex:none}.ai-provider-form .setting-description p+p{margin-top:12px}.ai-provider-form~.setting-section .check{align-items:flex-start}.ai-provider-form [hidden]{display:none!important} +@media(max-width:720px){.ai-fields input[type=url],.ai-fields input[type=text],.ai-fields input[type=password],.ai-fields .field select{font-size:16px;min-height:44px}.credential-field{flex-wrap:wrap}.credential-field input{flex-basis:200px}.credential-field .btn{min-height:44px}} @media(prefers-reduced-motion:reduce){.sidebar,.admin-app .btn{transition:none}} `; diff --git a/platform/github-app/src/admin-ui.ts b/platform/github-app/src/admin-ui.ts index 673b67e0..019cf7fa 100644 --- a/platform/github-app/src/admin-ui.ts +++ b/platform/github-app/src/admin-ui.ts @@ -1,5 +1,5 @@ import { format, type Locale, type Messages } from "./i18n"; -import { ADMIN_MESSAGES, type AdminMessages } from "./admin-i18n"; +import { ADMIN_MESSAGES, aiAuditLabel, type AdminMessages } from "./admin-i18n"; import type { AdminGlobalData } from "./admin-global-data"; import { JOB_KINDS, JOB_STATES, type AdminData, type AdminTask, type AdminAudit } from "./admin-data"; @@ -39,7 +39,7 @@ export function adminLink(context: AdminContext, path: string, extra: Recordpath===context.path)?.[0] ?? "overview"; + const active = context.path === "/admin" ? "overview" : context.path === "/admin/repo" || context.path === "/admin/intent-preview" || context.path.startsWith("/admin/ai-provider") ? "repositories" : context.path === "/admin/installations" || !context.installation ? "installations" : Object.entries(paths).find(([,path])=>path===context.path)?.[0] ?? "overview"; const nav = (Object.keys(paths) as (keyof typeof paths)[]).map(key => `${icons[key]}${e(d[key])}`).join(""); const installs = context.installations ?? (context.installation ? [{ id: Number(context.installation),account: context.account || `#${context.installation}` }] : []); const current = installs.find(x => String(x.id) === context.installation); const accountName = context.global ? d.allAccounts : current?.account || context.account || d.installations; const accountBadge = ``; - const switchPath = context.path === "/admin/repo" || context.path === "/admin/intent-preview" ? paths.repositories : Object.values(paths).includes(context.path as typeof paths[keyof typeof paths]) ? context.path : paths.overview; + const switchPath = context.path === "/admin/repo" || context.path === "/admin/intent-preview" || context.path.startsWith("/admin/ai-provider") ? paths.repositories : Object.values(paths).includes(context.path as typeof paths[keyof typeof paths]) ? context.path : paths.overview; const accountPicker = !installs.length ? `` : (installs.length > 1 || context.global) ? `` : `${e(d.manageInstallations)}`; return `
${accountPicker}
${controls}
${content}
`; } @@ -111,7 +111,7 @@ export function globalDashboardPage(c:AdminContext,t:Messages,data:AdminGlobalVi export function repositoriesPage(c:AdminContext,t:Messages,data:AdminData,csrf:string,url:URL){ const d=ADMIN_MESSAGES[c.locale],q=(url.searchParams.get("q")??"").trim(),processing=url.searchParams.get("processing")??""; c={...c,repositoryQuery:{q,processing}}; - const rows=data.repositories.map(r=>{const active=r.settings.issuesEnabled||r.settings.prsEnabled,visible=(!q||r.fullName.toLowerCase().includes(q.toLowerCase()))&&(!processing||(active?"active":"paused")===processing);return `${e(r.fullName)}${e(r.admin?d.admin:d.readOnly)}${r.admin?`
`:`${e(active?d.active:d.paused)}`}${feature(r.settings.commentsEnabled,d)}${feature(r.settings.triageEnabled,d)}${r.lastActivity?date(r.lastActivity):e(d.noActivity)}${e(d.openSettings)}`}).join(""); + const rows=data.repositories.map(r=>{const active=r.settings.issuesEnabled||r.settings.prsEnabled,visible=(!q||r.fullName.toLowerCase().includes(q.toLowerCase()))&&(!processing||(active?"active":"paused")===processing);return `${e(r.fullName)}${e(r.admin?d.admin:d.readOnly)}${r.admin?`
`:`${e(active?d.active:d.paused)}`}${feature(r.settings.commentsEnabled,d)}${feature(r.settings.triageEnabled,d)}${r.lastActivity?date(r.lastActivity):e(d.noActivity)}${e(d.openSettings)} ${e(d.aiService)}`}).join(""); const shown=data.repositories.some(r=>(!q||r.fullName.toLowerCase().includes(q.toLowerCase()))&&(!processing||(r.settings.issuesEnabled||r.settings.prsEnabled?"active":"paused")===processing)); return pageHead(d.repositories,d.repositoriesLead,button(t.admin.manageAccess,"https://github.com/settings/installations"))+scopeNote(data,d)+(data.repositories.length?`
${c.lang?``:""}${c.repoPage&&c.repoPage>1?``:""}
${rows}
${e(t.setup.repository)}${e(t.admin.processing)}${e(t.admin.comments)}${e(t.admin.triage)}${e(d.updated)}${e(t.setup.action)}

${e(d.noResults)}

${e(d.processingHint)}

`:emptyRepositories(t))+repoPagination(c,data,{q,processing}); } @@ -131,7 +131,7 @@ function detail(t:Messages,x:AdminAudit){ } export function auditList(c:AdminContext,t:Messages,rows:AdminAudit[],compact=false){ if(!rows.length)return `

${e(t.admin.activityEmpty)}

`; - return `
${compact?"":``}${rows.map(x=>`${compact?"":``}`).join("")}
${e(ADMIN_MESSAGES[c.locale].activity)}${e(t.setup.repository)}${e(ADMIN_MESSAGES[c.locale].updated)}
${e(t.admin.activityActions[x.action as keyof typeof t.admin.activityActions]??x.action)}${detail(t,x)?`${e(detail(t,x))}`:""}${e(x.actor)} · ${e(t.admin.activityVia[x.via])}${compact?`
${date(x.created)}`:""}
${e(x.fullName)}${date(x.created)}
`; + return `
${compact?"":``}${rows.map(x=>`${compact?"":``}`).join("")}
${e(ADMIN_MESSAGES[c.locale].activity)}${e(t.setup.repository)}${e(ADMIN_MESSAGES[c.locale].updated)}
${e(aiAuditLabel(c.locale,x.action)??t.admin.activityActions[x.action as keyof typeof t.admin.activityActions]??x.action)}${detail(t,x)?`${e(detail(t,x))}`:""}${e(x.actor)} · ${e(t.admin.activityVia[x.via])}${compact?`
${date(x.created)}`:""}
${e(x.fullName)}${date(x.created)}
`; } export function activityPage(c:AdminContext,t:Messages,data:AdminData,url:URL){ diff --git a/platform/github-app/src/api.ts b/platform/github-app/src/api.ts index 4a6032ef..aadc5a87 100644 --- a/platform/github-app/src/api.ts +++ b/platform/github-app/src/api.ts @@ -1,4 +1,6 @@ import { audit, recentAudit } from "./audit"; +import { AIProviderError, getAIProvider, putAIProvider, removeAIProviderKey, resolveAIEnv, type AIProviderMetadata } from "./byok"; +import { testAIProvider } from "./provider-test"; import { repoLabels } from "./repo-labels"; import { cancelCleanup, @@ -220,6 +222,11 @@ async function body(request: Request): Promise> { } } const iso = (ms: number) => new Date(ms).toISOString(); +const providerJson = (x: AIProviderMetadata) => ({ + mode: x.mode, provider: x.provider, base_url: x.baseUrl, model: x.model, + has_key: x.hasKey, storage_available: x.storageAvailable, ready: x.ready, + updated_at: x.updatedAt === null ? null : iso(x.updatedAt), +}); const jobJson = (x: Job) => ({ id: x.id, kind: x.kind, @@ -231,6 +238,7 @@ const jobJson = (x: Job) => ({ }); async function status(env: Env, c: Context) { + const aiEnv = await resolveAIEnv(env, c.repository, c.fullName); const [settings, last, recent, failed, cleanup, log] = await Promise.all([ getSettings(env, c.repository, c.fullName), lastBackfill(env, c.repository), @@ -255,8 +263,8 @@ async function status(env: Env, c: Context) { }, viewer: { login: c.login, admin: c.admin }, bot_enabled: env.ENABLED === "true", - llm_configured: llmConfigured(env), - triage_configured: triageConfigured(env), + llm_configured: llmConfigured(aiEnv), + triage_configured: triageConfigured(aiEnv), settings: settingsJson(settings), backfill: last ? { state: last.state, result: last.result, updated_at: iso(last.updated) } @@ -277,6 +285,8 @@ async function route( if (rest === "" && method === "GET") return json(await status(env, c)); if (rest === "/settings" && method === "GET") return json({ settings: settingsJson(await getSettings(env, c.repository, c.fullName)) }); + if (rest === "/ai-provider" && method === "GET") + return json({ ai_provider: providerJson(await getAIProvider(env, c.repository, c.fullName)) }); const cleanupMatch = /^\/cleanups\/([0-9a-f-]{36})(\/confirm|\/cancel)?$/.exec(rest); if (cleanupMatch && method === "GET") { const cleanup = await getCleanup(env, c.repository, cleanupMatch[1]); @@ -286,13 +296,26 @@ async function route( items: await cleanupItems(env, cleanup.id), }); } - if (method !== "POST" && method !== "PATCH") + if (method !== "POST" && method !== "PATCH" && !(method === "DELETE" && rest === "/ai-provider/key")) throw new Failure(405, "method_not_allowed"); if (!c.admin) throw new Failure(403, "admin_required"); const input = await body(request); const log = (action: string, detail?: Record) => audit(env, c.repository, c.login, "api", action, detail); + if (rest === "/ai-provider" && method === "PATCH") { + const config = await putAIProvider(env, c.repository, c.fullName, input, { login: c.login, via: "api" }); + return json({ ai_provider: providerJson(config) }); + } + if ((rest === "/ai-provider/key" && method === "DELETE") || (rest === "/ai-provider/test" && method === "POST")) { + if (Object.keys(input).length) throw new Failure(400, "invalid_body"); + if (method === "DELETE") + return json({ ai_provider: providerJson(await removeAIProviderKey(env, c.repository, c.fullName, { login: c.login, via: "api" })) }); + const result = await testAIProvider(env, c.repository, c.fullName); + await log("ai_provider.test", result); + return json({ connected: true, ...result }); + } + if (rest === "/settings" && method === "PATCH") { const current = await getSettings(env, c.repository, c.fullName); let next; @@ -455,6 +478,11 @@ export async function api(request: Request, env: Env): Promise { const c = await authorize(env, request, match[1], match[2], deadline); return await route(env, request, c, (match[3] ?? "").replace(/\/$/, "")); } catch (error) { + if (error instanceof AIProviderError) { + const response = json({ error: error.code }, error.status); + if (error.code === "rate_limited") response.headers.set("Retry-After", "60"); + return response; + } if (error instanceof Failure) { const response = json({ error: error.code }, error.status); if (error.retryAfter) diff --git a/platform/github-app/src/byok.ts b/platform/github-app/src/byok.ts new file mode 100644 index 00000000..53abeb6d --- /dev/null +++ b/platform/github-app/src/byok.ts @@ -0,0 +1,473 @@ +import { JEV_BASE_URL, JEV_MODEL, jevConfigured } from "./jev"; +import { AIProviderError, canonicalProviderBaseUrl } from "./provider-http"; +export { AIProviderError } from "./provider-http"; + +declare global { + interface Env { + BYOK_ENCRYPTION_KEY?: string; + } +} + +export interface AIProviderMetadata { + mode: "platform" | "byok"; + provider: "llm" | "jev"; + baseUrl: string; + model: string; + hasKey: boolean; + storageAvailable: boolean; + ready: boolean; + updatedAt: number | null; +} +export type AIProviderActor = string | { login: string; via: "web" | "api" }; +interface ProviderRow { + repository: number; + owner: string; + mode: "platform" | "byok"; + provider: "llm" | "jev"; + base_url: string; + model: string; + encrypted_key: string | null; + updated: number; +} +const LLM_BASE_URL = "https://api.stepfun.com/v1"; +const LLM_MODEL = "step-3.7-flash"; +const encoder = new TextEncoder(); +function invalid(): never { + throw new AIProviderError("invalid_config"); +} + +function context(repository: number, fullName: string): string { + if ( + !Number.isSafeInteger(repository) || + repository < 1 || + typeof fullName !== "string" || + fullName.length > 256 || + !/^[a-z0-9][a-z0-9-]*\/[a-z0-9_.-]+$/i.test(fullName) + ) + invalid(); + return fullName.split("/")[0].toLowerCase(); +} +function actorValue(actor: AIProviderActor, via: "web" | "api" = "web") { + const value = typeof actor === "string" ? { login: actor, via } : actor; + if ( + !value || + typeof value.login !== "string" || + !value.login.length || + value.login.length > 100 || + /[\x00-\x1f\x7f]/.test(value.login) || + !["web", "api"].includes(value.via) + ) + invalid(); + return value; +} +function keyValue(value: unknown): string { + if (typeof value !== "string" || /[^\x20-\x7e]/.test(value)) invalid(); + const key = value.trim(); + if (!/^[\x21-\x7e]{8,4096}$/.test(key)) invalid(); + return key; +} +function modelValue(value: unknown, provider: "llm" | "jev"): string { + if (typeof value !== "string") invalid(); + const model = value.trim(); + if ( + !model.length || + model.length > 200 || + /[\x00-\x1f\x7f]/.test(model) || + (provider === "jev" && !/^typesafe\/jev-1\.13(?:-\d{8})?$/.test(model)) + ) + invalid(); + return model; +} +function encode(bytes: Uint8Array): string { + return btoa(String.fromCharCode(...bytes)) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); +} +function decode(value: string): Uint8Array { + if (!/^[a-zA-Z0-9_-]+$/.test(value)) throw new Error(); + return Uint8Array.from( + atob(value.replace(/-/g, "+").replace(/_/g, "/")), + (char) => char.charCodeAt(0), + ); +} +function encryptionBytes(env: Env): Uint8Array | null { + try { + const setting = env.BYOK_ENCRYPTION_KEY; + if (typeof setting !== "string" || !/^[a-zA-Z0-9_-]{43}=?$/.test(setting)) + return null; + const bytes = decode(setting.replace(/=$/, "")); + return bytes.length === 32 && encode(bytes) === setting.replace(/=$/, "") + ? bytes + : null; + } catch { + return null; + } +} +async function encryptionKey(env: Env): Promise { + const bytes = encryptionBytes(env); + if (!bytes) throw new AIProviderError("storage_unavailable", 503); + return crypto.subtle.importKey("raw", bytes, "AES-GCM", false, [ + "encrypt", + "decrypt", + ]); +} +function aad( + row: Pick, +) { + return encoder.encode( + JSON.stringify([ + "ghfind-byok-v1", + row.repository, + row.owner, + row.provider, + row.base_url, + ]), + ); +} +async function encrypt( + env: Env, + row: ProviderRow, + key: string, +): Promise { + try { + const iv = crypto.getRandomValues(new Uint8Array(12)); + const ciphertext = await crypto.subtle.encrypt( + { name: "AES-GCM", iv, additionalData: aad(row), tagLength: 128 }, + await encryptionKey(env), + encoder.encode(key), + ); + return `v1.${encode(iv)}.${encode(new Uint8Array(ciphertext))}`; + } catch { + throw new AIProviderError("storage_unavailable", 503); + } +} +async function decrypt(env: Env, row: ProviderRow): Promise { + try { + const parts = row.encrypted_key?.split("."); + if ( + !parts || + parts.length !== 3 || + parts[0] !== "v1" || + parts[1].length !== 16 || + parts[2].length > 6000 + ) + return null; + const iv = decode(parts[1]); + if (iv.length !== 12) return null; + const plaintext = await crypto.subtle.decrypt( + { name: "AES-GCM", iv, additionalData: aad(row), tagLength: 128 }, + await encryptionKey(env), + decode(parts[2]), + ); + return keyValue( + new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode( + plaintext, + ), + ); + } catch { + return null; + } +} + +async function readRow( + env: Env, + repository: number, +): Promise<{ row: ProviderRow | null; available: boolean }> { + try { + const row = await env.DB.prepare( + "SELECT repository,owner,mode,provider,base_url,model,encrypted_key,updated FROM ai_providers WHERE repository=?", + ) + .bind(repository) + .first(); + return { row, available: true }; + } catch { + return { row: null, available: false }; + } +} +function platformMetadata( + env: Env, + available: boolean, + updatedAt: number | null = null, +): AIProviderMetadata { + const provider = env.TRIAGE_PROVIDER?.trim() === "jev" ? "jev" : "llm"; + const hasKey = !!(provider === "jev" + ? env.OPENROUTER_API_KEY?.trim() + : env.LLM_API_KEY?.trim()); + return { + mode: "platform", + provider, + baseUrl: + provider === "jev" + ? env.JEV_BASE_URL?.trim() || JEV_BASE_URL + : env.LLM_BASE_URL?.trim() || LLM_BASE_URL, + model: + provider === "jev" + ? env.JEV_MODEL?.trim() || JEV_MODEL + : env.LLM_MODEL?.trim() || LLM_MODEL, + hasKey, + storageAvailable: available && !!encryptionBytes(env), + ready: + available && + (provider === "jev" + ? jevConfigured(env) + : hasKey && + (!env.TRIAGE_PROVIDER?.trim() || + env.TRIAGE_PROVIDER.trim() === "llm")), + updatedAt, + }; +} +function disabledMetadata(available: boolean, env: Env): AIProviderMetadata { + return { + mode: "byok", + provider: "llm", + baseUrl: "", + model: "", + hasKey: false, + storageAvailable: available && !!encryptionBytes(env), + ready: false, + updatedAt: null, + }; +} +function validRow(row: ProviderRow) { + if ( + !["platform", "byok"].includes(row.mode) || + !["llm", "jev"].includes(row.provider) || + !Number.isSafeInteger(row.updated) || + row.updated < 0 + ) + return false; + try { + return ( + canonicalProviderBaseUrl(row.base_url) === row.base_url && + modelValue(row.model, row.provider) === row.model + ); + } catch { + return false; + } +} + +export async function getAIProvider( + env: Env, + repository: number, + fullName: string, +): Promise { + const owner = context(repository, fullName); + const { row, available } = await readRow(env, repository); + if (!available) return platformMetadata(env, false); + if (!row) return platformMetadata(env, true); + if (row.owner !== owner || row.repository !== repository) + return disabledMetadata(true, env); + if (row.mode === "platform") return platformMetadata(env, true, row.updated); + if (!validRow(row)) return disabledMetadata(true, env); + return { + mode: "byok", + provider: row.provider, + baseUrl: row.base_url, + model: row.model, + hasKey: !!row.encrypted_key, + storageAvailable: !!encryptionBytes(env), + ready: !!(await decrypt(env, row)), + updatedAt: row.updated, + }; +} + +async function store( + env: Env, + row: ProviderRow, + actor: AIProviderActor, + action: string, +) { + const who = actorValue(actor); + try { + await env.DB.batch([ + env.DB.prepare( + `INSERT INTO ai_providers(repository,owner,mode,provider,base_url,model,encrypted_key,updated,updated_by) + VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(repository) DO UPDATE SET owner=excluded.owner,mode=excluded.mode,provider=excluded.provider, + base_url=excluded.base_url,model=excluded.model,encrypted_key=excluded.encrypted_key,updated=excluded.updated,updated_by=excluded.updated_by`, + ).bind( + row.repository, + row.owner, + row.mode, + row.provider, + row.base_url, + row.model, + row.encrypted_key, + row.updated, + who.login, + ), + env.DB.prepare( + "INSERT INTO audit_log(repository,actor,via,action,detail,created) VALUES(?,?,?,?,?,?)", + ).bind( + row.repository, + who.login, + who.via, + action, + JSON.stringify({ + mode: row.mode, + provider: row.provider, + has_key: !!row.encrypted_key, + }), + row.updated, + ), + ]); + } catch { + throw new AIProviderError("storage_unavailable", 503); + } +} + +export async function putAIProvider( + env: Env, + repository: number, + fullName: string, + input: Record, + actor: AIProviderActor, + via: "web" | "api" = "web", +): Promise { + const owner = context(repository, fullName); + const who = actorValue(actor, via); + if ( + !input || + Object.keys(input).some( + (key) => + !["mode", "provider", "base_url", "model", "api_key"].includes(key), + ) || + (input.mode !== "platform" && input.mode !== "byok") + ) + invalid(); + const { row: previous, available } = await readRow(env, repository); + if (!available) throw new AIProviderError("storage_unavailable", 503); + const current = + previous?.owner === owner && + previous.repository === repository && + validRow(previous) + ? previous + : null; + let next: ProviderRow; + if (input.mode === "platform") { + if (input.api_key !== undefined && input.api_key !== "") invalid(); + next = current + ? { ...current, mode: "platform", updated: Date.now() } + : { + repository, + owner, + mode: "platform", + provider: "llm", + base_url: LLM_BASE_URL, + model: LLM_MODEL, + encrypted_key: null, + updated: Date.now(), + }; + } else { + if (input.provider !== "llm" && input.provider !== "jev") invalid(); + if (typeof input.base_url !== "string") invalid(); + const base = canonicalProviderBaseUrl(input.base_url); + const model = modelValue(input.model, input.provider); + next = { + repository, + owner, + mode: "byok", + provider: input.provider, + base_url: base, + model, + encrypted_key: null, + updated: Date.now(), + }; + if ( + input.api_key !== undefined && + (typeof input.api_key !== "string" || /[^\x20-\x7e]/.test(input.api_key)) + ) + invalid(); + const supplied = + typeof input.api_key === "string" && input.api_key.trim().length > 0; + if (supplied) + next.encrypted_key = await encrypt(env, next, keyValue(input.api_key)); + else { + if ( + typeof input.api_key === "string" && + /[\x00-\x1f\x7f]/.test(input.api_key) + ) + invalid(); + if ( + !current?.encrypted_key || + current.provider !== next.provider || + current.base_url !== base || + !(await decrypt(env, current)) + ) + throw new AIProviderError("key_required"); + next.encrypted_key = current.encrypted_key; + } + } + await store(env, next, who, "ai_provider.update"); + return getAIProvider(env, repository, fullName); +} + +export async function removeAIProviderKey( + env: Env, + repository: number, + fullName: string, + actor: AIProviderActor, + via: "web" | "api" = "web", +): Promise { + const owner = context(repository, fullName); + const who = actorValue(actor, via); + const { row, available } = await readRow(env, repository); + if (!available) throw new AIProviderError("storage_unavailable", 503); + const next: ProviderRow = + row?.owner === owner && validRow(row) + ? { ...row, mode: "byok", encrypted_key: null, updated: Date.now() } + : { + repository, + owner, + mode: "byok", + provider: "llm", + base_url: LLM_BASE_URL, + model: LLM_MODEL, + encrypted_key: null, + updated: Date.now(), + }; + await store(env, next, who, "ai_provider.key_remove"); + return getAIProvider(env, repository, fullName); +} + +function disabledEnv(env: Env): Env { + return { + ...env, + LLM_API_KEY: undefined, + OPENROUTER_API_KEY: undefined, + BYOK_REQUIRE_PUBLIC_ENDPOINT: true, + }; +} +export async function resolveAIEnv( + env: Env, + repository: number, + fullName: string, +): Promise { + let owner: string; + try { + owner = context(repository, fullName); + } catch { + return disabledEnv(env); + } + const { row, available } = await readRow(env, repository); + if (!available) return disabledEnv(env); + if (!row) return env; + if (row.repository !== repository || row.owner !== owner) + return disabledEnv(env); + if (row.mode === "platform") return env; + const scoped = disabledEnv(env); + if (!validRow(row)) return scoped; + scoped.TRIAGE_PROVIDER = row.provider; + const key = await decrypt(env, row); + if (!key) return scoped; + if (row.provider === "jev") { + scoped.OPENROUTER_API_KEY = key; + scoped.JEV_BASE_URL = row.base_url; + scoped.JEV_MODEL = row.model; + } else { + scoped.LLM_API_KEY = key; + scoped.LLM_BASE_URL = row.base_url; + scoped.LLM_MODEL = row.model; + } + return scoped; +} diff --git a/platform/github-app/src/intent-preview.ts b/platform/github-app/src/intent-preview.ts index c0bb1bcb..76989a37 100644 --- a/platform/github-app/src/intent-preview.ts +++ b/platform/github-app/src/intent-preview.ts @@ -1,4 +1,5 @@ import { github } from "./github"; +import { resolveAIEnv } from "./byok"; import { repoLabels } from "./repo-labels"; import { getSettings, triageConfigured } from "./settings"; import { classifyIntent, type IntentResult } from "./triage"; @@ -32,7 +33,8 @@ export async function runIntentPreview( if ((kind !== "issue" && kind !== "pull_request") || !title || title.length > 256 || body.length > 8000 || ["preview_kind", "preview_title", "preview_body"].some((key) => form.getAll(key).length > 1)) throw new IntentPreviewError("invalid_input", 400); - if (!triageConfigured(env)) throw new IntentPreviewError("not_configured", 503); + const aiEnv = await resolveAIEnv(env, repository, fullName); + if (!triageConfigured(aiEnv)) throw new IntentPreviewError("not_configured", 503); const settings = await getSettings(env, repository, fullName); const labels = new Map((await repoLabels(api, fullName)).map((label) => [label.name, label])); const allowed = [...new Set(settings.allowedLabels)].filter((name) => labels.has(name) && name !== "." && name !== ".." && !name.toLowerCase().startsWith("review:")); @@ -41,7 +43,7 @@ export async function runIntentPreview( .bind(`intent-preview:${repository}`, Math.floor(Date.now() / 60000) * 60000).first<{count:number}>(); if (!rate || rate.count > 1) throw new IntentPreviewError("rate_limited", 429); try { - const classification = await classifyIntent(env, { title, body, ...(kind === "pull_request" ? { pull_request: {} } : {}) }, allowed, labels, Date.now() + 60_000); + const classification = await classifyIntent(aiEnv, { title, body, ...(kind === "pull_request" ? { pull_request: {} } : {}) }, allowed, labels, Date.now() + 60_000); return { kind, title, body, classification, candidateCount: allowed.length }; } catch { // Never expose provider response details, credentials or issue text in errors. diff --git a/platform/github-app/src/jev.ts b/platform/github-app/src/jev.ts index bf72d2d9..eea88dcd 100644 --- a/platform/github-app/src/jev.ts +++ b/platform/github-app/src/jev.ts @@ -1,4 +1,5 @@ -import { jsonRequest, record } from "./github"; +import { record } from "./github"; +import { aiJsonRequest } from "./provider-http"; // Optional secret: `wrangler types` only emits required secrets. declare global { @@ -30,7 +31,8 @@ export function jevConfigured(env: Env): boolean { } } -// Trusted operator configuration, never repository settings or request input. +// Operator and resolved repository configuration share the endpoint format. +// BYOK URLs additionally pass the public endpoint guard at request time. export function jevEndpoint(env: Env): string { const setting = env.JEV_BASE_URL?.trim() || JEV_BASE_URL; try { @@ -184,7 +186,8 @@ export async function classifyJev( if (!supportedModel(model)) throw new Error("Unsupported Jev model"); const threshold = jevThreshold(env); const endpoint = jevEndpoint(env); - const response = await jsonRequest( + const response = await aiJsonRequest( + env, endpoint, { method: "POST", diff --git a/platform/github-app/src/jobs.ts b/platform/github-app/src/jobs.ts index 05e3c2cd..a36e1311 100644 --- a/platform/github-app/src/jobs.ts +++ b/platform/github-app/src/jobs.ts @@ -1,4 +1,5 @@ import { enqueueAuthorEmail, scoreContext } from "./author-email"; +import { resolveAIEnv } from "./byok"; import { ApiError, appJWT, @@ -476,14 +477,17 @@ async function processJob(env: Env, job: Job) { // Rescore and mention jobs follow a first job that already had its chance. const followUp = rescoreGeneration(job.id) > 0 || job.id.startsWith("mention-"); + const aiEnv = !followUp && (settings.triageEnabled || settings.commentsEnabled) + ? await resolveAIEnv(env, job.repository!, fullName) + : env; if ( settings.triageEnabled && settings.allowedLabels.length && !followUp && - triageConfigured(env) + triageConfigured(aiEnv) ) await triage( - env, + aiEnv, api, job.repository, fullName, @@ -527,9 +531,9 @@ async function processJob(env: Env, job: Job) { )) ) return null; - return llmConfigured(env) + return llmConfigured(aiEnv) ? introFor( - env, + aiEnv, settings.commentPrompt, login, score, diff --git a/platform/github-app/src/llm.ts b/platform/github-app/src/llm.ts index 6f8091c4..27952ee6 100644 --- a/platform/github-app/src/llm.ts +++ b/platform/github-app/src/llm.ts @@ -1,4 +1,5 @@ -import { jsonRequest, record } from "./github"; +import { record } from "./github"; +import { aiJsonRequest } from "./provider-http"; // Optional secret: `wrangler types` only emits required secrets, so declare it here. declare global { @@ -24,7 +25,8 @@ export async function complete( // reasoning_effort is StepFun-scoped; other providers may reject it. const stepfun = host === "stepfun.com" || host.endsWith(".stepfun.com"); const body = record( - await jsonRequest( + await aiJsonRequest( + env, `${base}/chat/completions`, { method: "POST", @@ -41,6 +43,7 @@ export async function complete( ], temperature: 0.2, stream: false, + ...(env.BYOK_REQUIRE_PUBLIC_ENDPOINT ? { max_tokens: 512 } : {}), ...(stepfun ? { reasoning_effort: "low" } : {}), }), }, @@ -54,5 +57,7 @@ export async function complete( : undefined; if (typeof content !== "string" || !content.trim()) throw new Error("Empty LLM response"); - return content.trim(); + // An untrusted provider must not publish the credential it received in an + // issue greeting, even if it reflects Authorization into its response. + return content.replaceAll(key, "[redacted]").trim(); } diff --git a/platform/github-app/src/provider-http.ts b/platform/github-app/src/provider-http.ts new file mode 100644 index 00000000..82cc7827 --- /dev/null +++ b/platform/github-app/src/provider-http.ts @@ -0,0 +1,266 @@ +import { ApiError, jsonRequest, readText, record } from "./github"; + +declare global { + interface Env { + BYOK_REQUIRE_PUBLIC_ENDPOINT?: boolean; + } +} + +export type AIProviderErrorCode = + | "invalid_config" + | "key_required" + | "storage_unavailable" + | "unavailable" + | "rate_limited"; +export class AIProviderError extends Error { + constructor( + public code: AIProviderErrorCode, + public status = 400, + ) { + super(`AI provider ${code}`); + this.name = "AIProviderError"; + } +} + +function invalid(): never { + throw new AIProviderError("invalid_config"); +} +function unavailable(): never { + throw new AIProviderError("unavailable", 503); +} +const DOH_ENDPOINT = "https://cloudflare-dns.com/dns-query"; +const MAX_DNS_BYTES = 32 * 1024; +const MAX_DNS_HOSTS = 8; + +function publicHostname(value: string): string { + const hostname = value.toLowerCase().replace(/\.$/, ""); + const labels = hostname.split("."); + if ( + hostname.length > 253 || + labels.length < 2 || + labels.some( + (label) => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label), + ) || + !/^[a-z][a-z0-9-]*$/.test(labels.at(-1)!) || + /(?:^|\.)(?:localhost|local|localdomain|internal|intranet|lan|home|corp|test|invalid|example|onion|arpa)$/.test( + hostname, + ) + ) + invalid(); + return hostname; +} + +// This validator accepts only public DNS names. URL parsing also canonicalizes +// alternate integer/hexadecimal IPv4 spellings, which the DNS grammar rejects. +export function canonicalProviderBaseUrl(value: string): string { + if (typeof value !== "string" || value.length > 2000) invalid(); + const setting = value.trim(); + if (!/^https:\/\//i.test(setting) || /[?#\\\s\x00-\x1f\x7f]/.test(setting)) + invalid(); + try { + const url = new URL(setting); + if ( + url.protocol !== "https:" || + url.username || + url.password || + setting.split("/")[2].includes("@") + ) + invalid(); + url.hostname = publicHostname(url.hostname); + return url.href.replace(/\/+$/, ""); + } catch { + return invalid(); + } +} + +function publicIPv4(value: string): boolean { + if (!/^(?:\d{1,3}\.){3}\d{1,3}$/.test(value)) return false; + const parts = value.split(".").map(Number); + if ( + parts.some((part, i) => part > 255 || String(part) !== value.split(".")[i]) + ) + return false; + const [a, b, c] = parts; + // Conservative exclusions include the IANA special-purpose registries, + // multicast and reserved ranges, even special-purpose globally routed blocks. + return !( + a === 0 || + a === 10 || + a === 127 || + a >= 224 || + (a === 100 && b >= 64 && b <= 127) || + (a === 169 && b === 254) || + (a === 172 && b >= 16 && b <= 31) || + (a === 192 && + ((b === 0 && (c === 0 || c === 2)) || + (b === 31 && c === 196) || + (b === 52 && c === 193) || + b === 88 || + b === 168 || + (b === 175 && c === 48))) || + (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) || + (a === 203 && b === 0 && c === 113) + ); +} + +function publicIPv6(value: string): boolean { + if (!/^[0-9a-f:]+$/i.test(value)) return false; + const halves = value.toLowerCase().split("::"); + if (halves.length > 2) return false; + const left = halves[0] ? halves[0].split(":") : []; + const right = halves.length === 2 && halves[1] ? halves[1].split(":") : []; + if ([...left, ...right].some((part) => !/^[0-9a-f]{1,4}$/.test(part))) + return false; + const missing = 8 - left.length - right.length; + if ( + (halves.length === 1 && missing !== 0) || + (halves.length === 2 && missing < 1) + ) + return false; + const words = [ + ...left, + ...Array.from({ length: missing }, () => "0"), + ...right, + ].map((part) => parseInt(part, 16)); + // Only global-unicast 2000::/3. Deny IANA special-purpose protocol, + // benchmarking/documentation, 6to4, and documentation 3fff::/20 blocks. + return ( + (words[0] & 0xe000) === 0x2000 && + !( + (words[0] === 0x2001 && words[1] < 0x200) || + (words[0] === 0x2001 && words[1] === 0xdb8) || + words[0] === 0x2002 || + (words[0] === 0x3fff && words[1] < 0x1000) || + (words[0] === 0x2620 && words[1] === 0x004f && words[2] === 0x8000) + ) + ); +} + +async function dnsQuery(hostname: string, type: 1 | 28, signal: AbortSignal) { + const query = new URL(DOH_ENDPOINT); + query.searchParams.set("name", hostname); + query.searchParams.set("type", String(type)); + const response = await fetch(query.href, { + headers: { Accept: "application/dns-json" }, + redirect: "manual", + signal, + }); + if (!response.ok) { + void response.body?.cancel().catch(() => {}); + if (response.status === 429) throw new AIProviderError("rate_limited", 429); + unavailable(); + } + return record(JSON.parse(await readText(response, signal, MAX_DNS_BYTES))); +} + +async function verifyPublicDNS(hostname: string, deadline: number) { + const controller = new AbortController(); + let timer: ReturnType | undefined; + const timeout = new Promise((_, reject) => { + timer = setTimeout( + () => { + controller.abort(); + reject(new AIProviderError("unavailable", 503)); + }, + Math.max(1, Math.min(5000, deadline - Date.now())), + ); + }); + try { + if (deadline <= Date.now()) unavailable(); + await Promise.race([ + timeout, + (async () => { + const pending = [hostname], + seen = new Set(); + const edges = new Map>(); + let addresses = 0; + while (pending.length) { + const host = pending.shift()!; + if (seen.has(host)) continue; + if (seen.size >= MAX_DNS_HOSTS) unavailable(); + seen.add(host); + const responses = await Promise.all([ + dnsQuery(host, 1, controller.signal), + dnsQuery(host, 28, controller.signal), + ]); + let hostAddresses = 0, + aliases = 0; + for (const response of responses) { + if (response.Status !== 0 || response.TC === true) unavailable(); + const answers = + response.Answer === undefined ? [] : response.Answer; + if (!Array.isArray(answers) || answers.length > 64) unavailable(); + for (const value of answers) { + const answer = record(value); + if ( + typeof answer.name !== "string" || + typeof answer.data !== "string" + ) + unavailable(); + const name = publicHostname(answer.name); + if (answer.type === 1 || answer.type === 28) { + if ( + !(answer.type === 1 + ? publicIPv4(answer.data) + : publicIPv6(answer.data)) + ) + unavailable(); + hostAddresses++; + addresses++; + } else if (answer.type === 5) { + const target = publicHostname(answer.data); + const targets = edges.get(name) ?? new Set(); + targets.add(target); + edges.set(name, targets); + if (targets.size > 1) unavailable(); + aliases++; + if (!seen.has(target)) pending.push(target); + } else unavailable(); + } + } + if (!hostAddresses && !aliases) unavailable(); + } + const visiting = new Set(), + visited = new Set(); + const checkCycle = (host: string) => { + if (visiting.has(host)) unavailable(); + if (visited.has(host)) return; + visiting.add(host); + for (const target of edges.get(host) ?? []) checkCycle(target); + visiting.delete(host); + visited.add(host); + }; + for (const host of seen) checkCycle(host); + if (!addresses) unavailable(); + })(), + ]); + } catch (error) { + if (error instanceof AIProviderError) throw error; + unavailable(); + } finally { + controller.abort(); + if (timer !== undefined) clearTimeout(timer); + } +} + +// DNS is checked for every request, never cached here. Workers fetch resolves +// again and cannot pin these addresses: this mitigates SSRF, not DNS rebinding +// races. No private/VPC bindings are used; redirects never forward credentials. +export async function aiJsonRequest( + env: Env, + url: string, + init: RequestInit, + deadline: number, +): Promise { + if (env.BYOK_REQUIRE_PUBLIC_ENDPOINT) { + const endpoint = canonicalProviderBaseUrl(url); + await verifyPublicDNS(new URL(endpoint).hostname, deadline); + } + // Keep existing provider HTTP/quota retry semantics; errors contain no body/key. + try { + return await jsonRequest(url, init, deadline); + } catch (error) { + if (error instanceof ApiError) throw error; + throw new AIProviderError("unavailable", 503); + } +} diff --git a/platform/github-app/src/provider-test.ts b/platform/github-app/src/provider-test.ts new file mode 100644 index 00000000..5473fda1 --- /dev/null +++ b/platform/github-app/src/provider-test.ts @@ -0,0 +1,46 @@ +import { AIProviderError, getAIProvider, resolveAIEnv } from "./byok"; +import { triageConfigured } from "./settings"; +import { classifyIntent, firstObject } from "./triage"; +import { complete } from "./llm"; + +// Both callers enforce fresh repository-admin authorization. Testing is an +// explicit model request using saved settings and a synthetic example only. +// No GitHub reads/writes, user sample storage or automatic tests on save. +export async function testAIProvider( + env: Env, + repository: number, + fullName: string, +): Promise<{ provider: "llm" | "jev"; model: string }> { + const config = await getAIProvider(env, repository, fullName); + const aiEnv = await resolveAIEnv(env, repository, fullName); + if (!config.ready || !triageConfigured(aiEnv)) + throw new AIProviderError("unavailable", 503); + const now = Date.now(); + const rate = await env.DB.prepare( + "INSERT INTO api_rate(key,slot,count) VALUES(?,?,1) ON CONFLICT(key,slot) DO UPDATE SET count=count+1 RETURNING count", + ).bind(`ai-provider-test:${repository}`, Math.floor(now / 60_000) * 60_000) + .first<{ count: number }>(); + if (!rate || rate.count > 1) throw new AIProviderError("rate_limited", 429); + try { + if (config.provider === "llm") { + const answer = firstObject(await complete( + aiEnv, + 'Classify a synthetic GitHub issue. Allowed label: bug (a reproducible defect). Answer with JSON only: {"labels":["bug"]} or {"labels":[]}.', + 'The application exits with an exception on startup. Expected: it starts successfully.', + now + 30_000, + )); + if (!answer || typeof answer !== "object" || !Array.isArray((answer as {labels?:unknown}).labels) || + (answer as {labels:unknown[]}).labels.some(label => label !== "bug")) + throw new Error("Invalid classifier response"); + } else await classifyIntent( + aiEnv, + { title: "Application crashes on startup", body: "The application exits with an exception when opened. Expected: it starts successfully." }, + ["bug"], + new Map([["bug", { name: "bug", color: "d73a4a", description: "A reproducible defect or unexpected failure in existing behavior." }]]), + now + 30_000, + ); + return { provider: config.provider, model: config.model }; + } catch { + throw new AIProviderError("unavailable", 503); + } +} diff --git a/platform/github-app/src/ui.ts b/platform/github-app/src/ui.ts index 88fa36b9..12f2a646 100644 --- a/platform/github-app/src/ui.ts +++ b/platform/github-app/src/ui.ts @@ -1,11 +1,13 @@ import { ADMIN_STYLE } from "./admin-style"; import { ADMIN_SCRIPT } from "./admin-script"; -import { ADMIN_MESSAGES } from "./admin-i18n"; +import { ADMIN_MESSAGES, aiAuditLabel } from "./admin-i18n"; import { loadAdminData, parseAdminFilters } from "./admin-data"; import { loadGlobalAdminData, GLOBAL_ACCOUNT_PAGE_SIZE, type GlobalRepositoryScope } from "./admin-global-data"; import { JOINED_JOB_ITEM_ORDER_SQL, compareJobsByItem } from "./job-display-order"; import { adminShell, adminLink, pageHead, installationPage, dashboardPage, globalDashboardPage, repositoriesPage, tasksPage, activityPage, type AdminContext } from "./admin-ui"; import { runIntentPreview, IntentPreviewError, type IntentPreviewResult } from "./intent-preview"; +import { getAIProvider, putAIProvider, removeAIProviderKey, resolveAIEnv, AIProviderError } from "./byok"; +import { testAIProvider } from "./provider-test"; import { seal, unseal } from "./secrets"; import { audit, recentAudit } from "./audit"; import { @@ -524,10 +526,10 @@ function activityDetail(a: Messages["admin"], x: AuditEntry) { : null; } } -function activityCard(a: Messages["admin"], log: AuditEntry[]) { +function activityCard(a: Messages["admin"], log: AuditEntry[], locale: Locale) { const items = log .map((x) => { - const label = a.activityActions[x.action as keyof typeof a.activityActions] ?? x.action; + const label = aiAuditLabel(locale, x.action) ?? a.activityActions[x.action as keyof typeof a.activityActions] ?? x.action; const detail = activityDetail(a, x); const via = a.activityVia[x.via as keyof typeof a.activityVia] ?? x.via; return `
  • ${escape(label)}${detail ? ` · ${escape(detail)}` : ""}${escape(x.actor)}${escape(via)}
  • `; @@ -766,6 +768,9 @@ async function renderUi(request: Request, env: Env): Promise { path === "/admin/tasks" || path === "/admin/activity" || path === "/admin/toggle" || + path === "/admin/ai-provider" || + path === "/admin/ai-provider/test" || + path === "/admin/ai-provider/remove" || path === "/admin/intent-preview" || path === "/admin/repo" || path === "/admin/backfill" || @@ -804,6 +809,9 @@ async function renderUi(request: Request, env: Env): Promise { request.method !== "GET" || path === "/admin/backfill" || path === "/admin/toggle" || + path === "/admin/ai-provider" || + path === "/admin/ai-provider/test" || + path === "/admin/ai-provider/remove" || path === "/admin/intent-preview" || path.startsWith("/admin/cleanup") ) @@ -898,7 +906,8 @@ async function renderUi(request: Request, env: Env): Promise { const query = new URL(target, url).searchParams.toString(); const operationTab = path === "/admin/backfill" ? "backfill" : path.startsWith("/admin/cleanup") ? "cleanup" - : path === "/admin/intent-preview" ? "preview" : "settings"; + : path === "/admin/intent-preview" ? "preview" + : path.startsWith("/admin/ai-provider") ? "ai" : "settings"; const backTarget = operationTab === "settings" ? target : `${target}&tab=${operationTab}`; const invalid = (title = a.invalidTitle, body = a.invalidBody, status = 400) => withStatus( @@ -915,6 +924,48 @@ async function renderUi(request: Request, env: Env): Promise { ? user.login : null; }; + const aiAction = ["/admin/ai-provider", "/admin/ai-provider/test", "/admin/ai-provider/remove"].includes(path); + let aiError: AIProviderError["code"] | undefined; + let aiStatus = 200; + let aiPermissions: Awaited> | undefined; + if (request.method === "POST" && aiAction) { + aiPermissions = await repoPermissions(api, fullName, Number(repository)); + if (!aiPermissions.admin) return new Response("Repository admin required", { status: 403 }); + if (!form || ["mode", "provider", "base_url", "model", "api_key", "confirm_remove"].some(key => form!.getAll(key).length > 1)) return invalid(); + if (path === "/admin/ai-provider/remove" && form.get("confirm_remove") !== "yes") return invalid(); + try { + let result = "saved"; + if (path === "/admin/ai-provider/test") { + const user = await login(); + if (!user) return new Response("Invalid user", { status: 400 }); + // Connection tests always use saved configuration, never the form's key. + const tested = await testAIProvider(env, Number(repository), fullName); + await audit(env, Number(repository), user, "web", "ai_provider.test", { provider: tested.provider, model: tested.model }); + result = "tested"; + } else { + const user = await login(); + if (!user) return new Response("Invalid user", { status: 400 }); + if (path === "/admin/ai-provider/remove") { + await removeAIProviderKey(env, Number(repository), fullName, user); + result = "removed"; + } else { + const input: Record = { mode: form.get("mode") }; + if (input.mode !== "platform") { + for (const key of ["provider", "base_url", "model"]) input[key] = form.get(key); + const key = form.get("api_key"); + if (key) input.api_key = key; + } + await putAIProvider(env, Number(repository), fullName, input, user); + } + } + return redirect(`${target}&tab=ai&ai=${result}`); + } catch (error) { + if (!(error instanceof AIProviderError)) throw error; + aiError = error.code; aiStatus = error.status; + // Never retain a submitted key or credential form values in the response. + form = undefined; + } + } if (request.method === "POST" && path === "/admin/toggle") { if (!(await repoAdmin(api, fullName, Number(repository)))) return new Response("Repository admin required", { status: 403 }); if (!form || !["on", "off"].includes(form.get("enabled") ?? "")) return invalid(); @@ -1026,7 +1077,7 @@ async function renderUi(request: Request, env: Env): Promise { } return new Response("Not found", { status: 404 }); } - if (request.method === "POST" && path !== "/admin/intent-preview") { + if (request.method === "POST" && path !== "/admin/intent-preview" && !aiAction) { if (!(await repoAdmin(api, fullName, Number(repository)))) return new Response("Repository admin required", { status: 403 }); if (!form) return invalid(); @@ -1056,10 +1107,14 @@ async function renderUi(request: Request, env: Env): Promise { await audit(env, Number(repository), user, "web", "settings.update", { changed }); return redirect(`${target}&saved=1`); } - const permissions = previewPermissions ?? await repoPermissions(api, fullName, Number(repository)); + const permissions = aiPermissions ?? previewPermissions ?? await repoPermissions(api, fullName, Number(repository)); if (!permissions.write) return withStatus(simple(view, a.title, `

    ${escape(a.writeRequired)}

    ${escape(a.allRepositories)}`), 404); const admin = permissions.admin; + const [aiProvider, scopedAIEnv] = await Promise.all([ + getAIProvider(env, Number(repository), fullName), + resolveAIEnv(env, Number(repository), fullName), + ]); const [settings, labels, last, cleanup, log] = await Promise.all([ getSettings(env, Number(repository), fullName), repoLabels(api, fullName), @@ -1099,27 +1154,39 @@ async function renderUi(request: Request, env: Env): Promise { ? `

    ${escape(a.backfillQueued)}

    ` : ""; const d = ADMIN_MESSAGES[locale]; - const selectedTab = path === "/admin/intent-preview" ? "preview" : url.searchParams.get("tab") ?? (url.searchParams.get("backfill") === "queued" ? "backfill" : "settings"); - if (!["settings", "backfill", "cleanup", "activity", "preview"].includes(selectedTab)) return new Response("Invalid tab", { status: 400 }); - const tabNames = { settings: d.settings, preview: d.preview, backfill: a.backfill, cleanup: a.cleanup, activity: a.activity }; + const selectedTab = aiAction ? "ai" : path === "/admin/intent-preview" ? "preview" : url.searchParams.get("tab") ?? (url.searchParams.get("backfill") === "queued" ? "backfill" : "settings"); + if (!["settings", "backfill", "cleanup", "activity", "preview", "ai"].includes(selectedTab)) return new Response("Invalid tab", { status: 400 }); + const tabNames = { settings: d.settings, ai: d.aiService, preview: d.preview, backfill: a.backfill, cleanup: a.cleanup, activity: a.activity }; const tabs = ``; const settingsPanel = `

    ${escape(a.processing)}

    ${escape(d.processingHint)}

    ${box("issues_enabled", settings.issuesEnabled, a.issues)}${box("prs_enabled", settings.prsEnabled, a.prs)}
    -

    ${escape(a.comments)}

    ${escape(a.promptHint)}

    ${llmConfigured(env)?"":`

    ${escape(a.llmMissing)}

    `}${box("comments_enabled", settings.commentsEnabled, a.commentsEnabled)}
    -

    ${escape(a.triage)}

    ${escape(a.labelsHint)}

    ${escape(a.editLabels)} ↗
    ${triageConfigured(env)?"":`

    ${escape(d.previewNotConfigured)}

    `}${box("triage_enabled", settings.triageEnabled, a.triageEnabled)}
    ${escape(a.labels)}${items ? `
      ${items}
    ` : `

    ${escape(a.noLabels)}

    `}
    +

    ${escape(a.comments)}

    ${escape(a.promptHint)}

    ${llmConfigured(scopedAIEnv)?"":`

    ${escape(d.aiGreetingsUnavailable)}

    `}${box("comments_enabled", settings.commentsEnabled, a.commentsEnabled)}
    +

    ${escape(a.triage)}

    ${escape(a.labelsHint)}

    ${escape(a.editLabels)} ↗
    ${triageConfigured(scopedAIEnv)?"":`

    ${escape(d.previewNotConfigured)}

    `}${box("triage_enabled", settings.triageEnabled, a.triageEnabled)}
    ${escape(a.labels)}${items ? `
      ${items}
    ` : `

    ${escape(a.noLabels)}

    `}
    ${admin?`

    ${escape(d.saveHint)}

    `:""}
    `; const backfillPanel = `
    ${backfillNotice}${processingPaused ? `

    ${escape(a.backfillPaused)}

    ` : ""}

    ${escape(a.backfill)}

    ${escape(a.backfillHint)}

    ${escape(a.backfillStatusHint)}

    ${escape(a.backfillLast)} ${last ? `${escape(t.setup.states[last.state as keyof typeof t.setup.states] ?? last.state)} ${last.result ? ` · ${escape(last.result)}` : ""}` : escape(a.backfillNever)}

    ${admin ? `

    ` : ""}
    `; const cleanupPanel = `
    ${cleanupCard(a, query, current.id, admin, cleanup, viewer)}
    `; - const activityPanel = `
    ${activityCard(a,log)}
    `; + const activityPanel = `
    ${activityCard(a,log,locale)}
    `; const previewErrors = { invalid_input: d.previewInvalid, no_candidates: d.previewNoCandidates, not_configured: d.previewNotConfigured, rate_limited: d.previewRateLimited, classifier_unavailable: d.previewUnavailable }; const previewTitle = previewResult?.title ?? (form?.get("preview_title") ?? "").slice(0,256); const previewBody = previewResult?.body ?? (form?.get("preview_body") ?? "").slice(0,8000); const previewKind = previewResult?.kind ?? (form?.get("preview_kind") === "pull_request" ? "pull_request" : "issue"); const classification = previewResult?.classification; const previewOutput = previewError ? `` : classification ? `

    ${escape(d.previewSelected)}

    ${classification.labels.length?classification.labels.map(name=>`${escape(name)}`).join(" "):escape(d.previewNoMatch)}

    ${escape(d.previewCandidates)}: ${previewResult!.candidateCount} · ${escape(classification.provider)}${classification.model?` · ${escape(classification.model)}`:""}${classification.threshold!==undefined?` · ${escape(d.previewThreshold)}: ${Math.round(classification.threshold*100)}%`:""}

    ${classification.probabilities?.length?`
    ${classification.probabilities.map(x=>`
    ${escape(x.name)}${(x.probability*100).toFixed(1)}%
    `).join("")}
    `:""}
    ` : ""; - const previewPanel = `

    ${escape(d.preview)}

    ${escape(d.previewLead)}

    ${admin?``:""}

    ${escape(d.previewOnly)}

    ${previewOutput}
    `; - const panels = { settings: settingsPanel, backfill: backfillPanel, cleanup: cleanupPanel, activity: activityPanel, preview: previewPanel }; - return withStatus(html(view,fullName,`${pageHead(fullName,selectedTab==="settings"?d.settingsHint:tabNames[selectedTab as keyof typeof tabNames])}${notices?`
    ${notices}
    `:""}${tabs}${panels[selectedTab as keyof typeof panels]}`),previewStatus); + const previewPanel = `

    ${escape(d.preview)}

    ${escape(d.previewLead)}

    ${admin?``:""}

    ${escape(d.previewOnly)}

    ${previewOutput}
    `; + const aiErrors: Record = { invalid_config: d.aiInvalid, key_required: d.aiKeyRequired, storage_unavailable: d.aiStorageUnavailable, unavailable: d.aiUnavailable, rate_limited: d.aiRateLimited }; + const aiMessages = { saved: d.aiSaved, tested: d.aiTested, removed: d.aiRemoved }; + const aiResult = url.searchParams.get("ai") ?? ""; + const aiFeedback = aiError ? `` : ["saved", "tested", "removed"].includes(aiResult) ? aiMessages[aiResult as keyof typeof aiMessages] : ""; + const aiTarget = (path: string) => adminLink(view.admin!, path, { repository: Number(repository) }); + const aiPanel = `
    ${aiFeedback ? (aiError ? aiFeedback : `

    ${escape(aiFeedback)}

    `) : ""} +
    +

    ${escape(d.aiMode)}

    ${escape(d.aiLead)}

    ${escape(d.aiPrivacy)}

    ${escape(d.aiNoFallback)}

    ${escape(d.aiPlatformHint)}

    ${escape(d.aiSavedConfiguration)}: ${escape(aiProvider.mode === "platform" ? d.aiPlatform : d.aiByok)} · ${escape(aiProvider.ready ? d.aiReady : d.aiNotReady)}

    ${aiProvider.storageAvailable ? "" : `

    ${escape(d.aiStorageUnavailable)}

    `}
    +

    ${escape(d.aiByok)}

    ${escape(d.aiCapabilities)}

    ${escape(d.aiModelHint)}

    ${escape(aiProvider.mode === "byok" && aiProvider.hasKey ? d.aiKeySaved : d.aiKeyMissing)}

    ${escape(d.aiKeyHint)}

    +
    ${admin ? `

    ${escape(d.saveHint)}

    ` : ""} +

    ${escape(d.aiTest)}

    ${escape(d.aiTestHint)}

    +${aiProvider.mode === "byok" && aiProvider.hasKey ? `

    ${escape(d.aiRemove)}

    ${escape(d.aiKeySaved)}

    ` : ""}
    `; + const panels = { settings: settingsPanel, backfill: backfillPanel, cleanup: cleanupPanel, activity: activityPanel, preview: previewPanel, ai: aiPanel }; + return withStatus(html(view,fullName,`${pageHead(fullName,selectedTab==="settings"?d.settingsHint:selectedTab==="ai"?d.aiLead:tabNames[selectedTab as keyof typeof tabNames],selectedTab==="settings"?`${escape(d.aiService)}`:"")}${notices?`
    ${notices}
    `:""}${tabs}${panels[selectedTab as keyof typeof panels]}`),aiAction ? aiStatus : previewStatus); } if (path === "/setup" || path === "/retry") { diff --git a/platform/github-app/tests/admin-byok.test.ts b/platform/github-app/tests/admin-byok.test.ts new file mode 100644 index 00000000..424c1345 --- /dev/null +++ b/platform/github-app/tests/admin-byok.test.ts @@ -0,0 +1,175 @@ +import { env } from "cloudflare:test"; +import { beforeAll, beforeEach, afterEach, describe, expect, it, vi } from "vitest"; +import { ui } from "../src/ui"; +import { seal } from "../src/secrets"; +import { DEFAULT_SETTINGS, putSettings } from "../src/settings"; +import { AIProviderError, getAIProvider, putAIProvider } from "../src/byok"; +import { testAIProvider } from "../src/provider-test"; +import { ADMIN_MESSAGES } from "../src/admin-i18n"; +import { audit } from "../src/audit"; + +// The provider helper has separate model/network tests. These tests exercise +// actual UI authorization, encrypted persistence, and the explicit test boundary. +vi.mock("../src/provider-test", () => ({ testAIProvider: vi.fn() })); +declare const TEST_SQL: string[]; +const origin = "https://bot.example"; +const repository = "owner/repo"; +const key = "PRIVATE_SYNTHETIC_BYOK_KEY"; +const e: Env = { ...(env as Env), BYOK_ENCRYPTION_KEY: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", LLM_API_KEY: "PRIVATE_PLATFORM_KEY", TRIAGE_PROVIDER: "llm" }; +let csrf: string, cookie: string, administrator: boolean, accessible: boolean, liveId: number, liveName: string, viewerLogin: string; +const requests: string[] = []; +const paths = ["/admin/ai-provider", "/admin/ai-provider/test", "/admin/ai-provider/remove"]; +const target = (path = "/admin/ai-provider", extra = "") => `${origin}${path}?installation_id=10&repository=100&lang=zh&repo_page=2&return_q=repo&return_processing=paused${extra}`; +const form = (extra: Record = {}) => new URLSearchParams({ csrf, mode: "byok", provider: "llm", base_url: "https://provider.vendor.dev/v1", model: "synthetic-model", api_key: key, ...extra }); +const post = (path = paths[0], body = form(), headers: Record = { origin }, authenticated = true, url = target(path)) => ui(new Request(url, { method: "POST", headers: { ...(authenticated ? { cookie } : {}), "content-type": "application/x-www-form-urlencoded", ...headers }, body }), e); +const get = (tab = "ai") => ui(new Request(target("/admin/repo", `&tab=${tab}`), { headers: { cookie } }), e); +const stored = () => e.DB.prepare("SELECT * FROM ai_providers WHERE repository=100").first(); +const saveFixture = (provider = "llm") => putAIProvider(e, 100, repository, { mode: "byok", provider, base_url: "https://provider.vendor.dev/v1", model: provider === "jev" ? "typesafe/jev-1.13" : "synthetic-model", api_key: key }, "admin"); + +beforeAll(async () => { for (const sql of TEST_SQL) await e.DB.prepare(sql).run(); }); +beforeEach(async () => { + await e.DB.exec("DELETE FROM sessions; DELETE FROM repo_settings; DELETE FROM ai_providers; DELETE FROM audit_log; DELETE FROM jobs; DELETE FROM cleanups; DELETE FROM cleanup_items; DELETE FROM api_rate;"); + await putSettings(e, 10, 100, repository, { ...DEFAULT_SETTINGS, allowedLabels: ["bug"] }, "admin"); + csrf = crypto.randomUUID(); cookie = `ghfind_bot_session=${csrf}`; + await e.DB.prepare("INSERT INTO sessions(id,value,expires) VALUES(?,?,?)").bind(`session:${csrf}`, await seal(e, "synthetic-user-token"), Date.now() + 3600000).run(); + administrator = true; accessible = true; liveId = 100; liveName = repository; viewerLogin = "admin"; requests.splice(0); + vi.mocked(testAIProvider).mockReset().mockResolvedValue({ provider: "llm", model: "synthetic-model" }); + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, init: RequestInit = {}) => { + const url = String(input); requests.push(url); + if (init.method && init.method !== "GET") throw new Error("Unexpected external write or model call"); + if (url === "https://api.github.com/user/installations?per_page=100&page=1") return Response.json({ installations: [{ id: 10, account: { login: "owner" } }] }); + if (url === "https://api.github.com/user/installations/10/repositories?per_page=100&page=1") return Response.json({ repositories: accessible ? [{ id: 100, full_name: repository }] : [] }); + if (url === `https://api.github.com/repos/${repository}`) return Response.json({ id: liveId, full_name: liveName, permissions: { admin: administrator, push: true } }); + if (url === `https://api.github.com/repos/${repository}/labels?per_page=100&page=1`) return Response.json([{ name: "bug", color: "112233" }]); + if (url === "https://api.github.com/user") return Response.json({ login: viewerLogin }); + throw new Error(`Unexpected request ${url}`); + })); +}); +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); + +describe("repository AI service UI", () => { + it("renders saved metadata, an empty password, confirmation and scoped links without testing", async () => { + await saveFixture(); + const response = await get(), html = await response.text(); + expect(response.status).toBe(200); + expect(html).toContain(ADMIN_MESSAGES.zh.aiKeySaved); + expect(html).toContain('id="ai-api-key" type="password"'); + expect(html.match(/]+>/)?.[0]).not.toContain("value="); + expect(html).not.toContain(key); + expect(html).not.toContain("encrypted_key"); + expect(html).toContain('name="confirm_remove" value="yes" required'); + expect(html).toContain('/admin/ai-provider/test?installation_id=10&lang=zh&repo_page=2&return_q=repo&return_processing=paused&repository=100'); + expect(testAIProvider).not.toHaveBeenCalled(); + }); + it("does not mistake the platform key for the repository's saved key", async () => { + const html = await (await get()).text(); + expect(html).not.toContain('name="confirm_remove"'); + expect(html).not.toContain(ADMIN_MESSAGES.zh.aiKeySaved); + expect(html).not.toContain("PRIVATE_PLATFORM_KEY"); + expect(html).toContain('name="api_key"'); + expect(testAIProvider).not.toHaveBeenCalled(); + }); + it("renders read-only metadata but rejects every write or test without live admin", async () => { + await saveFixture(); administrator = false; + const html = await (await get()).text(); + expect(html).toContain('action="/admin/ai-provider?'); + expect(html).toContain("
    "); + for (const path of paths) expect((await post(path, form({ confirm_remove: "yes" }))).status).toBe(403); + expect(testAIProvider).not.toHaveBeenCalled(); + expect((await getAIProvider(e, 100, repository)).hasKey).toBe(true); + }); + it.each(paths)("rejects anonymous, CSRF, Origin and wrong method on %s before side effects", async path => { + for (const [body, headers, auth] of [[form(), { origin }, false], [form(), { origin: "https://evil.example" }, true], [form(), {}, true], [form({ csrf: "wrong" }), { origin }, true]] as const) { + expect((await post(path, body, headers, auth)).status).toBe(403); + } + expect((await ui(new Request(target(path), { headers: { cookie } }), e)).status).toBe(405); + expect(requests).toEqual([]); + expect(await stored()).toBeNull(); + expect(testAIProvider).not.toHaveBeenCalled(); + }); + it.each([{ id: 200, name: repository }, { id: 100, name: "new-owner/repo" }])("denies stale live repository identity $name/$id on every action", async ({ id, name }) => { + await saveFixture(); const before = await stored(); liveId = id; liveName = name; + for (const path of paths) expect((await post(path, form({ confirm_remove: "yes" }))).status).toBe(403); + expect(await stored()).toEqual(before); + expect(testAIProvider).not.toHaveBeenCalled(); + }); + it("rejects wrong installation and inaccessible repositories without storage changes", async () => { + expect((await post(paths[0], form(), { origin }, true, target().replace("installation_id=10", "installation_id=20"))).status).toBe(404); + accessible = false; + for (const path of paths) expect((await post(path)).status).toBe(404); + expect(await stored()).toBeNull(); expect(testAIProvider).not.toHaveBeenCalled(); + }); + it("saves encrypted configuration, retains navigation and leaves feature opt-ins unchanged", async () => { + const before = await e.DB.prepare("SELECT * FROM repo_settings WHERE repository=100").first(); + const response = await post(); + expect(response.status).toBe(303); + expect(response.headers.get("location")).toBe("/admin/repo?installation_id=10&lang=zh&repo_page=2&return_q=repo&return_processing=paused&repository=100&tab=ai&ai=saved"); + expect(JSON.stringify(await stored())).not.toContain(key); + expect((await getAIProvider(e, 100, repository)).ready).toBe(true); + expect(await e.DB.prepare("SELECT * FROM repo_settings WHERE repository=100").first()).toEqual(before); + expect(testAIProvider).not.toHaveBeenCalled(); + expect((await post(paths[1], new URLSearchParams({ csrf }))).status).toBe(303); + expect(testAIProvider).toHaveBeenCalledExactlyOnceWith(e, 100, repository); + expect(await e.DB.prepare("SELECT actor,via,detail FROM audit_log WHERE action='ai_provider.test'").first()).toEqual({ actor: "admin", via: "web", detail: JSON.stringify({ provider: "llm", model: "synthetic-model" }) }); + }); + it("keeps a blank unchanged key, but never echoes a rejected replacement key", async () => { + await saveFixture(); const original = await stored() as { encrypted_key: string }; + expect((await post(paths[0], form({ api_key: "", model: "updated-model" }))).status).toBe(303); + expect((await stored() as { encrypted_key: string }).encrypted_key).toBe(original.encrypted_key); + const response = await post(paths[0], form({ base_url: "http://localhost/private", api_key: `${key}-REJECTED` })); + const html = await response.text(); + expect(response.status).toBe(400); expect(html).toContain(ADMIN_MESSAGES.zh.aiInvalid); + expect(html).not.toContain(key); expect(html).not.toContain("http://localhost/private"); + expect(html.match(/]+>/)?.[0]).not.toContain("value="); + expect((await stored() as { encrypted_key: string }).encrypted_key).toBe(original.encrypted_key); + const changed = await post(paths[0], form({ base_url: "https://other.vendor.dev/v1", api_key: "" })); + expect(changed.status).toBe(400); expect(await changed.text()).toContain(ADMIN_MESSAGES.zh.aiKeyRequired); + }); + it("rejects duplicate fields and requires an explicit deletion confirmation", async () => { + await saveFixture(); const before = await stored(); + for (const name of ["mode", "provider", "base_url", "model", "api_key"]) { + const duplicate = form(); duplicate.append(name, "tampered"); + expect((await post(paths[0], duplicate)).status).toBe(400); + } + expect((await post(paths[2], new URLSearchParams({ csrf }))).status).toBe(400); + const duplicate = new URLSearchParams({ csrf, confirm_remove: "yes" }); duplicate.append("confirm_remove", "no"); + expect((await post(paths[2], duplicate)).status).toBe(400); + expect(await stored()).toEqual(before); + expect((await post(paths[2], new URLSearchParams({ csrf, confirm_remove: "yes" }))).status).toBe(303); + const metadata = await getAIProvider(e, 100, repository); + expect(metadata.mode).toBe("byok"); expect(metadata.hasKey).toBe(false); expect(metadata.ready).toBe(false); + }); + it("shows a safe test failure on the AI tab without retaining submitted credentials", async () => { + await saveFixture(); vi.mocked(testAIProvider).mockRejectedValueOnce(new AIProviderError("unavailable", 503)); + const response = await post(paths[1], form({ api_key: `${key}-UNSAVED` })), html = await response.text(); + expect(response.status).toBe(503); expect(html).toContain(ADMIN_MESSAGES.zh.aiUnavailable); + expect(html).toContain('tab=ai" aria-current="page"'); expect(html).not.toContain(key); + }); + it("resolves the audit actor before permitting a connection test", async () => { + viewerLogin = "invalid_login"; + expect((await post(paths[1], new URLSearchParams({ csrf }))).status).toBe(400); + expect(testAIProvider).not.toHaveBeenCalled(); + expect(await e.DB.prepare("SELECT count(*) n FROM audit_log WHERE action='ai_provider.test'").first()).toEqual({ n: 0 }); + }); + it("uses repository-scoped Jev capability for the greeting warning", async () => { + await saveFixture("jev"); + const html = await (await get("settings")).text(); + expect(html).toContain("AI"); + expect(html).toContain('tab=ai'); + // A platform LLM key must not make a Jev-only repository claim greetings work. + expect(html).toContain(ADMIN_MESSAGES.zh.aiGreetingsUnavailable); + }); + it("renders friendly AI audit actions in repository, account and global activity without raw details", async () => { + await saveFixture(); + await audit(e, 100, "admin", "web", "ai_provider.key_remove", { api_key: key }); + await audit(e, 100, "admin", "api", "ai_provider.test", { api_key: key }); + const responses = [await get("activity"), await ui(new Request(`${origin}/admin/activity?installation_id=10&lang=zh`, { headers: { cookie } }), e), await ui(new Request(`${origin}/admin?lang=zh`, { headers: { cookie } }), e)]; + for (const response of responses) { + expect(response.status).toBe(200); + const html = await response.text(); + for (const label of [ADMIN_MESSAGES.zh.aiSaved, ADMIN_MESSAGES.zh.aiRemoved, ADMIN_MESSAGES.zh.aiTested]) expect(html).toContain(label); + for (const action of ["ai_provider.update", "ai_provider.key_remove", "ai_provider.test"]) expect(html).not.toContain(action); + expect(html).not.toContain(key); + } + }); +}); diff --git a/platform/github-app/tests/admin.test.ts b/platform/github-app/tests/admin.test.ts index 3d39d424..3e71379e 100644 --- a/platform/github-app/tests/admin.test.ts +++ b/platform/github-app/tests/admin.test.ts @@ -3,6 +3,7 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vite import { ui } from "../src/ui"; import { seal } from "../src/secrets"; import { getSettings } from "../src/settings"; +import { ADMIN_MESSAGES } from "../src/admin-i18n"; declare const TEST_SQL: string[]; const testEnv = env as Env; @@ -206,7 +207,7 @@ describe("admin pages", () => { expect(text).toContain("Reply in Chinese <b>briefly</b>"); expect(text).toContain("tab=backfill"); expect(text).toContain('class="settings-flow"'); - expect(text).toContain("LLM key"); + expect(text).toContain(ADMIN_MESSAGES.en.aiGreetingsUnavailable); }); it("hides settings from users without write access, matching the API", async () => { const { cookie } = await signIn(); diff --git a/platform/github-app/tests/api.test.ts b/platform/github-app/tests/api.test.ts index 5fa8d5a2..99e47884 100644 --- a/platform/github-app/tests/api.test.ts +++ b/platform/github-app/tests/api.test.ts @@ -4,6 +4,7 @@ import { api as handle } from "../src/api"; import { runCleanup } from "../src/cleanup"; import { COMMENT_MARKER, LABELS } from "../src/review"; import { getSettings } from "../src/settings"; +import { resolveAIEnv } from "../src/byok"; declare const TEST_SQL: string[]; const testEnv = env as Env; @@ -15,6 +16,7 @@ const sent: unknown[] = []; let whoami: () => Response; const e = { ...testEnv, + BYOK_ENCRYPTION_KEY: "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", SCORE: { fetch: async (input: RequestInfo | URL, init?: RequestInit) => { const request = new Request(input, init); @@ -63,7 +65,7 @@ beforeAll(async () => { }); beforeEach(async () => { await testEnv.DB.exec( - "DELETE FROM jobs; DELETE FROM repo_settings; DELETE FROM audit_log; DELETE FROM cleanups; DELETE FROM cleanup_items; DELETE FROM triage_labels; DELETE FROM api_auth; DELETE FROM api_rate;", + "DELETE FROM jobs; DELETE FROM repo_settings; DELETE FROM audit_log; DELETE FROM cleanups; DELETE FROM cleanup_items; DELETE FROM triage_labels; DELETE FROM api_auth; DELETE FROM api_rate; DELETE FROM ai_providers;", ); sent.splice(0); whoami = () => Response.json({ github_id: 7, scopes: ["scan", "bot"] }); @@ -486,3 +488,99 @@ describe("API limits", () => { expect(await rows("SELECT state,lease FROM cleanups")).toEqual([{ state: "planning", lease: 0 }]); }); }); + +describe("repository BYOK API", () => { + const own = { mode: "byok", provider: "llm", base_url: "https://api.openai.com/v1", model: "gpt-4o-mini", api_key: "user-private-test-key" }; + const save = async (input: unknown = own) => { + authorized(); + return call("/ai-provider", "PATCH", input); + }; + it("stores encrypted credentials and exposes safe metadata to writable users", async () => { + const saved = await save(); + expect(saved.status).toBe(200); + expect(saved.headers.get("cache-control")).toBe("no-store"); + const metadata = await saved.json(); + expect(metadata).toMatchObject({ ai_provider: { mode: "byok", provider: "llm", base_url: own.base_url, model: own.model, has_key: true, ready: true, storage_available: true, updated_at: expect.any(String) } }); + expect(JSON.stringify(metadata)).not.toContain(own.api_key); + const stored = await rows("SELECT * FROM ai_providers"); + expect(stored).toHaveLength(1); + expect(JSON.stringify(stored)).not.toContain(own.api_key); + expect(stored[0].encrypted_key).toMatch(/^v1\./); + expect(await rows("SELECT via,action,detail FROM audit_log")).toEqual([{ via: "api", action: "ai_provider.update", detail: '{"mode":"byok","provider":"llm","has_key":true}' }]); + authorized("write"); + const read = await call("/ai-provider"); + expect(read.status).toBe(200); + expect(JSON.stringify(await read.json())).not.toContain("encrypted_key"); + const scoped = await resolveAIEnv(e, 100, repo); + expect(scoped.LLM_API_KEY).toBe(own.api_key); + expect(scoped.OPENROUTER_API_KEY).toBeUndefined(); + }); + it("requires fresh administrator permission for save, connection test and key removal", async () => { + expect((await save()).status).toBe(200); + for (const [path, method, input] of [["/ai-provider", "PATCH", own], ["/ai-provider/test", "POST", {}], ["/ai-provider/key", "DELETE", {}]] as const) { + authorized("write"); + const denied = await call(path, method, input); + expect(denied.status).toBe(403); + expect(await denied.json()).toEqual({ error: "admin_required" }); + } + expect(await rows("SELECT count(*) AS n FROM audit_log")).toEqual([{ n: 1 }]); + expect((await resolveAIEnv(e, 100, repo)).LLM_API_KEY).toBe(own.api_key); + expect(sent).toEqual([]); + }); + it("does not redirect a retained key to another endpoint and rejects internal URLs", async () => { + expect((await save()).status).toBe(200); + const { api_key: _key, ...retained } = own; + expect((await save(retained)).status).toBe(200); + expect(await (await save({ ...retained, base_url: "https://other-provider.com/v1" })).json()).toEqual({ error: "key_required" }); + for (const base_url of ["http://api.openai.com/v1", "https://127.0.0.1/v1", "https://[::1]/v1", "https://localhost/v1", "https://api.openai.com/v1?secret=x"]) { + const failed = await save({ ...own, base_url }); + expect(failed.status).toBe(400); + expect(await failed.json()).toEqual({ error: "invalid_config" }); + } + expect((await resolveAIEnv(e, 100, repo)).LLM_BASE_URL).toBe(own.base_url); + expect((await resolveAIEnv(e, 100, repo)).LLM_API_KEY).toBe(own.api_key); + }); + it("uses the saved own key for explicit model tests and rate limits without GitHub writes", async () => { + expect((await save()).status).toBe(200); + for (const type of [1, 28]) pending.push({ url: `https://cloudflare-dns.com/dns-query?name=api.openai.com&type=${type}`, method: "GET", status: 200, body: JSON.stringify({ Status: 0, Answer: type === 1 ? [{ name: "api.openai.com", type: 1, data: "104.18.32.7" }] : [] }) }); + pending.push({ url: own.base_url + "/chat/completions", method: "POST", status: 200, body: JSON.stringify({ choices: [{ message: { content: '{"labels":["bug"]}' } }] }) }); + authorized(); + const connected = await call("/ai-provider/test", "POST", {}); + expect(connected.status).toBe(200); + expect(await connected.json()).toEqual({ connected: true, provider: "llm", model: own.model }); + const modelCall = vi.mocked(fetch).mock.calls.find(([url]) => String(url).endsWith("/chat/completions")); + expect(new Headers(modelCall?.[1]?.headers).get("authorization")).toBe(`Bearer ${own.api_key}`); + expect(modelCall?.[1]?.redirect).toBe("manual"); + const dnsCalls = vi.mocked(fetch).mock.calls.filter(([url]) => String(url).startsWith("https://cloudflare-dns.com")); + expect(dnsCalls.every(([, init]) => !new Headers(init?.headers).has("authorization"))).toBe(true); + authorized(); + const second = await call("/ai-provider/test", "POST", {}); + expect(second.status).toBe(429); + expect(second.headers.get("retry-after")).toBe("60"); + expect(sent).toEqual([]); + expect(await rows("SELECT * FROM jobs")).toEqual([]); + expect(await rows("SELECT * FROM repo_settings")).toEqual([]); + }); + it("removing the user key disables AI and requires explicit platform selection", async () => { + expect((await save()).status).toBe(200); + authorized(); + const removed = await call("/ai-provider/key", "DELETE", {}); + expect(removed.status).toBe(200); + expect(await removed.json()).toMatchObject({ ai_provider: { mode: "byok", has_key: false, ready: false } }); + expect((await resolveAIEnv({ ...e, LLM_API_KEY: "platform-key" }, 100, repo)).LLM_API_KEY).toBeUndefined(); + authorized(); + expect((await call("/ai-provider/test", "POST", {})).status).toBe(503); + expect((await save({ mode: "platform" })).status).toBe(200); + expect((await resolveAIEnv({ ...e, LLM_API_KEY: "platform-key" }, 100, repo)).LLM_API_KEY).toBe("platform-key"); + }); + it("fails safely on unavailable encryption storage without admitting model requests", async () => { + const secret = e.BYOK_ENCRYPTION_KEY; + e.BYOK_ENCRYPTION_KEY = undefined; + try { + const response = await save(); + expect(response.status).toBe(503); + expect(await response.json()).toEqual({ error: "storage_unavailable" }); + expect(await rows("SELECT * FROM ai_providers")).toEqual([]); + } finally { e.BYOK_ENCRYPTION_KEY = secret; } + }); +}); diff --git a/platform/github-app/tests/byok.test.ts b/platform/github-app/tests/byok.test.ts new file mode 100644 index 00000000..038c7f35 --- /dev/null +++ b/platform/github-app/tests/byok.test.ts @@ -0,0 +1,394 @@ +import { env } from "cloudflare:test"; +import { + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { + AIProviderError, + getAIProvider, + putAIProvider, + removeAIProviderKey, + resolveAIEnv, +} from "../src/byok"; + +declare const TEST_SQL: string[]; +const e: Env = { + ...(env as Env), + BYOK_ENCRYPTION_KEY: btoa("0123456789abcdef0123456789abcdef").replace( + /=+$/, + "", + ), + TRIAGE_PROVIDER: "jev", + JEV_MODEL: "typesafe/jev-1.13", + JEV_BASE_URL: "https://openrouter.ai/api", + OPENROUTER_API_KEY: "platform-openrouter-test", + LLM_API_KEY: "platform-llm-test", +}; +const input = { + mode: "byok", + provider: "llm", + base_url: "https://api.vendor.com/v1", + model: "vendor-model", + api_key: "repository-test-key", +}; +const save = ( + value: Record = input, + repository = 100, + fullName = "owner/repo", +) => + putAIProvider(e, repository, fullName, value, { login: "admin", via: "web" }); +async function row(repository = 100) { + return e.DB.prepare("SELECT * FROM ai_providers WHERE repository=?") + .bind(repository) + .first>(); +} +beforeAll(async () => { + for (const sql of TEST_SQL) await e.DB.prepare(sql).run(); +}); +beforeEach(async () => { + await e.DB.exec("DELETE FROM ai_providers; DELETE FROM audit_log;"); +}); +afterEach(() => vi.restoreAllMocks()); + +describe("encrypted repository-owned AI providers", () => { + it("keeps platform behavior unchanged without a profile and explicitly restores it while retaining ciphertext", async () => { + expect(await resolveAIEnv(e, 100, "owner/repo")).toBe(e); + expect(await getAIProvider(e, 100, "owner/repo")).toMatchObject({ + mode: "platform", + provider: "jev", + hasKey: true, + ready: true, + storageAvailable: true, + updatedAt: null, + }); + await save(); + const ciphertext = (await row())?.encrypted_key; + const metadata = await save({ mode: "platform" }); + expect(metadata).toMatchObject({ + mode: "platform", + provider: "jev", + baseUrl: "https://openrouter.ai/api", + ready: true, + }); + expect((await row())?.encrypted_key).toBe(ciphertext); + expect(await resolveAIEnv(e, 100, "owner/repo")).toBe(e); + expect((await save({ ...input, api_key: "" })).mode).toBe("byok"); + }); + + it("stores random AES-GCM ciphertext only and never returns or audits either stored or platform keys", async () => { + const metadata = await save(); + const first = await row(); + expect(metadata).toMatchObject({ + mode: "byok", + provider: "llm", + hasKey: true, + ready: true, + storageAvailable: true, + }); + expect(first?.encrypted_key).toMatch( + /^v1\.[a-zA-Z0-9_-]{16}\.[a-zA-Z0-9_-]+$/, + ); + expect(Object.keys(first!)).not.toContain("api_key"); + expect(JSON.stringify(first)).not.toContain(input.api_key); + const audit = (await e.DB.prepare("SELECT * FROM audit_log").all()).results; + const exposed = JSON.stringify([ + metadata, + await getAIProvider(e, 100, "owner/repo"), + audit, + ]); + for (const secret of [ + input.api_key, + String(first?.encrypted_key), + e.OPENROUTER_API_KEY!, + e.LLM_API_KEY!, + ]) + expect(exposed).not.toContain(secret); + expect(audit[0]).toMatchObject({ + actor: "admin", + via: "web", + action: "ai_provider.update", + }); + await save(); + expect((await row())?.encrypted_key).not.toBe(first?.encrypted_key); + }); + + it("resolves only the repository key and suppresses platform keys and greetings for Jev BYOK", async () => { + await save({ ...input, api_key: ` ${input.api_key} ` }); + const llm = await resolveAIEnv(e, 100, "owner/repo"); + expect(llm).toMatchObject({ + TRIAGE_PROVIDER: "llm", + LLM_API_KEY: input.api_key, + LLM_BASE_URL: input.base_url, + LLM_MODEL: input.model, + BYOK_REQUIRE_PUBLIC_ENDPOINT: true, + }); + expect(llm.OPENROUTER_API_KEY).toBeUndefined(); + expect(llm.DB).toBe(e.DB); + expect(llm.SCORE).toBe(e.SCORE); + await save({ + ...input, + provider: "jev", + base_url: "https://openrouter.ai/api", + model: "typesafe/jev-1.13", + api_key: "repository-jev-test", + }); + const jev = await resolveAIEnv(e, 100, "owner/repo"); + expect(jev).toMatchObject({ + TRIAGE_PROVIDER: "jev", + OPENROUTER_API_KEY: "repository-jev-test", + JEV_BASE_URL: "https://openrouter.ai/api", + JEV_MODEL: "typesafe/jev-1.13", + BYOK_REQUIRE_PUBLIC_ENDPOINT: true, + }); + expect(jev.LLM_API_KEY).toBeUndefined(); + expect(e.LLM_API_KEY).toBe("platform-llm-test"); + expect((await resolveAIEnv(e, 200, "other/repo")).OPENROUTER_API_KEY).toBe( + e.OPENROUTER_API_KEY, + ); + }); + + it("retains blank/omitted keys only for an unchanged canonical URL, provider and owner", async () => { + await save(); + const ciphertext = (await row())?.encrypted_key; + const { api_key: _, ...withoutKey } = input; + await save({ + ...withoutKey, + base_url: " HTTPS://API.VENDOR.COM:443/v1/// ", + model: "next-model", + }); + expect((await row())?.encrypted_key).toBe(ciphertext); + expect((await resolveAIEnv(e, 100, "owner/renamed")).LLM_API_KEY).toBe( + input.api_key, + ); + const before = await row(); + for (const value of [ + { ...withoutKey, base_url: "https://other.vendor.com/v1" }, + { ...withoutKey, base_url: "https://api.vendor.com/v2" }, + { ...withoutKey, provider: "jev", model: "typesafe/jev-1.13" }, + ]) + await expect(save(value)).rejects.toMatchObject({ + code: "key_required", + status: 400, + }); + await expect(save(withoutKey, 100, "new-owner/repo")).rejects.toMatchObject( + { code: "key_required" }, + ); + await expect(save(withoutKey, 200, "owner/other")).rejects.toMatchObject({ + code: "key_required", + }); + expect(await row()).toEqual(before); + }); + + it("survives same-owner rename but invalidates transfers and binds ciphertext against cross-repo and endpoint tampering", async () => { + await save(); + expect((await resolveAIEnv(e, 100, "OWNER/new-name")).LLM_API_KEY).toBe( + input.api_key, + ); + const transferred = await getAIProvider(e, 100, "new-owner/repo"); + expect(transferred).toMatchObject({ + mode: "byok", + ready: false, + hasKey: false, + baseUrl: "", + model: "", + }); + expect( + (await resolveAIEnv(e, 100, "new-owner/repo")).LLM_API_KEY, + ).toBeUndefined(); + expect( + (await resolveAIEnv(e, 100, "new-owner/repo")).OPENROUTER_API_KEY, + ).toBeUndefined(); + await e.DB.prepare( + "INSERT INTO ai_providers SELECT 200,owner,mode,provider,base_url,model,encrypted_key,updated,updated_by FROM ai_providers WHERE repository=100", + ).run(); + expect((await getAIProvider(e, 200, "owner/copy")).ready).toBe(false); + expect( + (await resolveAIEnv(e, 200, "owner/copy")).LLM_API_KEY, + ).toBeUndefined(); + await e.DB.prepare( + "UPDATE ai_providers SET base_url='https://other.vendor.com/v1' WHERE repository=100", + ).run(); + expect((await getAIProvider(e, 100, "owner/repo")).ready).toBe(false); + expect( + (await resolveAIEnv(e, 100, "owner/repo")).LLM_API_KEY, + ).toBeUndefined(); + await e.DB.prepare( + "UPDATE ai_providers SET base_url=?,owner='new-owner' WHERE repository=100", + ) + .bind(input.base_url) + .run(); + expect( + (await resolveAIEnv(e, 100, "new-owner/repo")).LLM_API_KEY, + ).toBeUndefined(); + await save({ ...input, api_key: "new-owner-key" }, 100, "new-owner/repo"); + expect((await resolveAIEnv(e, 100, "new-owner/repo")).LLM_API_KEY).toBe( + "new-owner-key", + ); + }); + + it("key removal retains BYOK without fallback and requires a fresh key to resume", async () => { + await save(); + await save({ mode: "platform" }); + const metadata = await removeAIProviderKey(e, 100, "owner/repo", { + login: "api-admin", + via: "api", + }); + expect(metadata).toMatchObject({ + mode: "byok", + provider: "llm", + hasKey: false, + ready: false, + baseUrl: input.base_url, + }); + expect((await row())?.encrypted_key).toBeNull(); + const disabled = await resolveAIEnv(e, 100, "owner/repo"); + expect(disabled.OPENROUTER_API_KEY).toBeUndefined(); + expect(disabled.LLM_API_KEY).toBeUndefined(); + await expect(save({ ...input, api_key: "" })).rejects.toMatchObject({ + code: "key_required", + }); + expect( + await e.DB.prepare( + "SELECT via,action FROM audit_log ORDER BY id DESC LIMIT 1", + ).first(), + ).toEqual({ via: "api", action: "ai_provider.key_remove" }); + }); + + it("fails closed for missing/bad encryption secrets and corrupted ciphertext without breaking score bindings", async () => { + await save(); + for (const setting of [ + undefined, + "", + "not-base64", + btoa("short"), + btoa("fedcba9876543210fedcba9876543210").replace(/=+$/, ""), + ]) { + const broken = { ...e, BYOK_ENCRYPTION_KEY: setting }; + expect((await getAIProvider(broken, 100, "owner/repo")).ready).toBe( + false, + ); + const disabled = await resolveAIEnv(broken, 100, "owner/repo"); + expect(disabled.LLM_API_KEY).toBeUndefined(); + expect(disabled.OPENROUTER_API_KEY).toBeUndefined(); + expect(disabled.SCORE).toBe(e.SCORE); + } + const stored = String((await row())?.encrypted_key); + const parts = stored.split("."); + parts[2] = (parts[2][0] === "A" ? "B" : "A") + parts[2].slice(1); + await e.DB.prepare( + "UPDATE ai_providers SET encrypted_key=? WHERE repository=100", + ) + .bind(parts.join(".")) + .run(); + expect( + (await resolveAIEnv(e, 100, "owner/repo")).LLM_API_KEY, + ).toBeUndefined(); + await e.DB.prepare( + "UPDATE ai_providers SET encrypted_key='v1.bad.corrupted' WHERE repository=100", + ).run(); + expect((await getAIProvider(e, 100, "owner/repo")).ready).toBe(false); + await expect(save({ ...input, api_key: "" })).rejects.toMatchObject({ + code: "key_required", + }); + await expect( + putAIProvider( + { ...e, BYOK_ENCRYPTION_KEY: undefined }, + 100, + "owner/repo", + input, + "admin", + ), + ).rejects.toMatchObject({ code: "storage_unavailable", status: 503 }); + }); + + it("disables AI when migration/storage is unavailable and never echoes database errors", async () => { + await e.DB.exec("ALTER TABLE ai_providers RENAME TO ai_providers_offline;"); + try { + expect(await getAIProvider(e, 100, "owner/repo")).toMatchObject({ + storageAvailable: false, + ready: false, + }); + const disabled = await resolveAIEnv(e, 100, "owner/repo"); + expect(disabled.OPENROUTER_API_KEY).toBeUndefined(); + expect(disabled.LLM_API_KEY).toBeUndefined(); + expect(disabled.SCORE).toBe(e.SCORE); + await expect(save()).rejects.toMatchObject({ + code: "storage_unavailable", + status: 503, + message: "AI provider storage_unavailable", + }); + } finally { + await e.DB.exec( + "ALTER TABLE ai_providers_offline RENAME TO ai_providers;", + ); + } + await e.DB.exec("ALTER TABLE audit_log RENAME TO audit_log_offline;"); + try { + await expect(save()).rejects.toMatchObject({ + code: "storage_unavailable", + }); + expect(await row()).toBeNull(); + } finally { + await e.DB.exec("ALTER TABLE audit_log_offline RENAME TO audit_log;"); + } + const spy = vi + .spyOn(e.DB, "batch") + .mockRejectedValue(new Error("private database error")); + await expect(save()).rejects.toMatchObject({ + code: "storage_unavailable", + message: "AI provider storage_unavailable", + }); + expect(await row()).toBeNull(); + spy.mockRestore(); + }); + + it("rejects invalid inputs before writes and never saves plaintext in error details", async () => { + for (const value of [ + { ...input, mode: "unknown" }, + { ...input, provider: "other" }, + { ...input, extra: "unknown" }, + { ...input, api_key: "short" }, + { ...input, api_key: "test key with spaces" }, + { ...input, api_key: "latin1-key-\u00e9" }, + { ...input, api_key: "unicode-key-密钥" }, + { ...input, api_key: "\u00a0" }, + { ...input, api_key: "key\r\nsecret" }, + { ...input, api_key: "k".repeat(4097) }, + { ...input, api_key: 123 }, + { ...input, model: "" }, + { ...input, model: "x".repeat(201) }, + { ...input, model: "model\nprivate" }, + { ...input, provider: "jev", model: "other/model" }, + { ...input, base_url: "http://localhost/private" }, + { ...input, base_url: "https://127.0.0.1/api" }, + { ...input, base_url: "https://api.vendor.com?key=secret" }, + ]) + await expect(save(value)).rejects.toMatchObject({ + code: "invalid_config", + message: "AI provider invalid_config", + }); + for (const repository of [0, -1, 1.5, NaN]) + await expect(save(input, repository)).rejects.toBeInstanceOf( + AIProviderError, + ); + await expect(save(input, 100, "invalid-name")).rejects.toMatchObject({ + code: "invalid_config", + }); + await expect( + putAIProvider(e, 100, "owner/repo", input, "invalid\nactor"), + ).rejects.toMatchObject({ code: "invalid_config" }); + expect( + (await e.DB.prepare("SELECT count(*) AS count FROM ai_providers").first()) + ?.count, + ).toBe(0); + expect( + (await e.DB.prepare("SELECT count(*) AS count FROM audit_log").first()) + ?.count, + ).toBe(0); + }); +}); diff --git a/platform/github-app/tests/llm.test.ts b/platform/github-app/tests/llm.test.ts index 87eda0e2..f259115c 100644 --- a/platform/github-app/tests/llm.test.ts +++ b/platform/github-app/tests/llm.test.ts @@ -44,6 +44,12 @@ afterEach(() => { }); describe("llm complete", () => { + it("redacts an API key reflected by an untrusted model response", async () => { + reply(200, ok(`Welcome. ${KEY} ${KEY}`)); + const content = await complete(llmEnv(), "sys", PROMPT, Date.now() + 5000); + expect(content).toBe("Welcome. [redacted] [redacted]"); + expect(content).not.toContain(KEY); + }); it("posts to StepFun by default and returns trimmed content", async () => { reply(200, ok(" hello \n")); expect(await complete(llmEnv(), "sys", PROMPT, Date.now() + 5000)).toBe( diff --git a/platform/github-app/tests/provider-http.test.ts b/platform/github-app/tests/provider-http.test.ts new file mode 100644 index 00000000..cd3e3b98 --- /dev/null +++ b/platform/github-app/tests/provider-http.test.ts @@ -0,0 +1,357 @@ +import { env } from "cloudflare:test"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { ApiError } from "../src/github"; +import { + AIProviderError, + aiJsonRequest, + canonicalProviderBaseUrl, +} from "../src/provider-http"; + +const e: Env = { ...(env as Env), BYOK_REQUIRE_PUBLIC_ENDPOINT: true }; +const ENDPOINT = "https://api.vendor.com/v1/chat/completions"; +const init = { + method: "POST", + headers: { Authorization: "Bearer synthetic-owned-key" }, + body: '{"messages":[]}', +}; +const call = (settings = e, deadline = Date.now() + 3000) => + aiJsonRequest(settings, ENDPOINT, init, deadline); +type Answer = { name: string; type: number; data: string }; +const answer = ( + type: number, + data: string, + name = "api.vendor.com.", +): Answer => ({ name, type, data }); +function mockDNS( + resolve: (host: string, type: number) => unknown, + modelStatus = 200, +) { + const model = vi.fn(async () => + Response.json({ ok: true }, { status: modelStatus }), + ); + const dns = vi.fn(async (url: URL) => + Response.json( + resolve( + url.searchParams.get("name")!, + Number(url.searchParams.get("type")), + ), + ), + ); + const fetcher = vi.fn( + async (url: RequestInfo | URL, request?: RequestInit) => { + const parsed = new URL(String(url)); + if (parsed.hostname === "cloudflare-dns.com") { + expect(parsed.origin + parsed.pathname).toBe( + "https://cloudflare-dns.com/dns-query", + ); + expect(new Headers(request?.headers).has("authorization")).toBe(false); + expect(request?.body).toBeUndefined(); + expect(request?.redirect).toBe("manual"); + return dns(parsed); + } + expect(String(url)).toBe(ENDPOINT); + expect(request?.redirect).toBe("manual"); + expect(new Headers(request?.headers).get("authorization")).toBe( + "Bearer synthetic-owned-key", + ); + return model(); + }, + ); + vi.stubGlobal("fetch", fetcher); + return { dns, model, fetcher }; +} +afterEach(() => vi.unstubAllGlobals()); + +describe("untrusted BYOK endpoint requests", () => { + it("canonicalizes public HTTPS roots and rejects IP, local, credential and delimiter bypasses without network", () => { + expect(canonicalProviderBaseUrl(" HTTPS://API.VENDOR.COM:443/v1/// ")).toBe( + "https://api.vendor.com/v1", + ); + expect(canonicalProviderBaseUrl("https://api.vendor.com./v1")).toBe( + "https://api.vendor.com/v1", + ); + expect(canonicalProviderBaseUrl("https://api.vendor.com:8443/v1")).toBe( + "https://api.vendor.com:8443/v1", + ); + for (const value of [ + "http://api.vendor.com/v1", + "https:api.vendor.com/v1", + "//api.vendor.com/v1", + "not-a-url", + "https://127.0.0.1/v1", + "https://8.8.8.8/v1", + "https://2130706433/v1", + "https://0x7f000001/v1", + "https://0177.0.0.1/v1", + "https://[::1]/v1", + "https://[2606:4700::1111]/v1", + "https://localhost/v1", + "https://metadata/v1", + "https://api.local/v1", + "https://api.internal/v1", + "https://api.localhost/v1", + "https://api.test/v1", + "https://api.invalid/v1", + "https://api.corp/v1", + "https://api.onion/v1", + "https://api.arpa/v1", + "https://user:secret@api.vendor.com/v1", + "https://@api.vendor.com/v1", + "https://api.vendor.com/v1?key=secret", + "https://api.vendor.com/v1?", + "https://api.vendor.com/v1#secret", + "https://api.vendor.com/v1#", + "https://api.vendor.com/a\\b", + "https://api.vendor.com/a\nb", + "https://api.vendor.com/a\0b", + "https://api.vendor.com/a b", + "https://api.vendor.com/" + "x".repeat(2000), + ]) + expect(() => canonicalProviderBaseUrl(value)).toThrow( + "AI provider invalid_config", + ); + }); + + it("checks both address families on every request before sending the model key", async () => { + const mocks = mockDNS((_, type) => ({ + Status: 0, + Answer: [answer(type, type === 1 ? "8.8.8.8" : "2606:4700::1111")], + })); + expect(await call()).toEqual({ ok: true }); + expect(await call()).toEqual({ ok: true }); + expect(mocks.dns).toHaveBeenCalledTimes(4); + expect(mocks.model).toHaveBeenCalledTimes(2); + expect( + mocks.fetcher.mock.calls.map(([url]) => new URL(String(url)).hostname), + ).toEqual([ + "cloudflare-dns.com", + "cloudflare-dns.com", + "api.vendor.com", + "cloudflare-dns.com", + "cloudflare-dns.com", + "api.vendor.com", + ]); + }); + + it("blocks private/special IPv4, non-public IPv6 and mixed public/private answers before model calls", async () => { + for (const [type, data] of [ + ...[ + "0.0.0.0", + "10.0.0.1", + "100.64.0.1", + "127.0.0.1", + "169.254.169.254", + "172.16.0.1", + "172.31.255.255", + "192.0.0.1", + "192.0.2.1", + "192.168.1.1", + "192.88.99.1", + "198.18.0.1", + "198.51.100.1", + "203.0.113.1", + "224.0.0.1", + "255.255.255.255", + "999.1.1.1", + "01.2.3.4", + ].map((ip) => [1, ip] as const), + ...[ + "::", + "::1", + "fc00::1", + "fe80::1", + "ff02::1", + "::ffff:127.0.0.1", + "64:ff9b::a00:1", + "2001:db8::1", + "2001:2::1", + "2002:a00::1", + "3fff::1", + "2620:4f:8000::1", + "2001:::1", + ].map((ip) => [28, ip] as const), + ]) { + const mocks = mockDNS((_, queryType) => ({ + Status: 0, + Answer: + queryType === type + ? [answer(type, data)] + : [ + answer( + queryType, + queryType === 1 ? "8.8.8.8" : "2001:4860::8888", + ), + ], + })); + await expect(call()).rejects.toMatchObject({ + code: "unavailable", + status: 503, + }); + expect(mocks.model).not.toHaveBeenCalled(); + } + }); + + it("validates and resolves public CNAME chains and rejects local aliases, private targets and alias cycles", async () => { + const publicChain = mockDNS((host, type) => ({ + Status: 0, + Answer: + host === "api.vendor.com" + ? [ + answer(5, "edge.vendor.net."), + ...(type === 1 ? [answer(1, "8.8.8.8", "edge.vendor.net.")] : []), + ] + : type === 1 + ? [answer(1, "8.8.8.8", "edge.vendor.net.")] + : [], + })); + expect(await call()).toEqual({ ok: true }); + expect(publicChain.dns).toHaveBeenCalledTimes(4); + const local = mockDNS(() => ({ + Status: 0, + Answer: [answer(5, "metadata.internal.")], + })); + await expect(call()).rejects.toBeInstanceOf(AIProviderError); + expect(local.model).not.toHaveBeenCalled(); + const privateTarget = mockDNS((host, type) => ({ + Status: 0, + Answer: + host === "api.vendor.com" + ? [answer(5, "edge.vendor.net.")] + : type === 1 + ? [answer(1, "10.0.0.1", "edge.vendor.net.")] + : [], + })); + await expect(call()).rejects.toMatchObject({ code: "unavailable" }); + expect(privateTarget.model).not.toHaveBeenCalled(); + const cycle = mockDNS((host) => ({ + Status: 0, + Answer: [ + answer( + 5, + host === "api.vendor.com" ? "edge.vendor.net." : "api.vendor.com.", + `${host}.`, + ), + ], + })); + await expect(call()).rejects.toMatchObject({ code: "unavailable" }); + expect(cycle.model).not.toHaveBeenCalled(); + }); + + it("fails closed for no DNS data, error/truncation, malformed answers and alias bounds", async () => { + for (const response of [ + { Status: 3 }, + { Status: 2 }, + {}, + { Status: 0 }, + { Status: 0, Answer: [] }, + { Status: 0, TC: true, Answer: [answer(1, "8.8.8.8")] }, + { Status: 0, Answer: "not-an-array" }, + { Status: 0, Answer: [{ type: 1, data: "8.8.8.8" }] }, + { Status: 0, Answer: [answer(16, "unexpected")] }, + { + Status: 0, + Answer: Array.from({ length: 65 }, () => answer(1, "8.8.8.8")), + }, + ]) { + const mocks = mockDNS(() => response); + await expect(call()).rejects.toMatchObject({ code: "unavailable" }); + expect(mocks.model).not.toHaveBeenCalled(); + } + const aliases = mockDNS((host) => ({ + Status: 0, + Answer: [ + answer( + 5, + `hop${host.startsWith("hop") ? Number(host.match(/^hop(\d+)/)![1]) + 1 : 1}.vendor.net.`, + `${host}.`, + ), + ], + })); + await expect(call()).rejects.toMatchObject({ code: "unavailable" }); + expect(aliases.dns).toHaveBeenCalledTimes(16); + expect(aliases.model).not.toHaveBeenCalled(); + }); + + it("bounds DNS response bodies, stalled streams and expired deadlines without sending credentials", async () => { + const huge = vi.fn(async () => new Response(" ".repeat(33 * 1024))); + vi.stubGlobal("fetch", huge); + await expect(call()).rejects.toMatchObject({ code: "unavailable" }); + expect(huge.mock.calls).toHaveLength(2); + const stalled = vi.fn( + async () => new Response(new ReadableStream({ start() {} })), + ); + vi.stubGlobal("fetch", stalled); + await expect(call(e, Date.now() + 25)).rejects.toMatchObject({ + code: "unavailable", + }); + expect(stalled.mock.calls).toHaveLength(2); + stalled.mockClear(); + await expect(call(e, Date.now() - 1)).rejects.toMatchObject({ + code: "unavailable", + }); + expect(stalled).not.toHaveBeenCalled(); + }); + + it("never follows DoH/model redirects and preserves provider rate-limit semantics", async () => { + const redirectedDNS = vi.fn( + async () => + new Response(null, { + status: 302, + headers: { Location: "https://collect.vendor.net" }, + }), + ); + vi.stubGlobal("fetch", redirectedDNS); + await expect(call()).rejects.toMatchObject({ code: "unavailable" }); + expect(redirectedDNS.mock.calls).toHaveLength(2); + const mocks = mockDNS( + (_, type) => ({ + Status: 0, + Answer: type === 1 ? [answer(1, "8.8.8.8")] : [], + }), + 307, + ); + await expect(call()).rejects.toMatchObject({ status: 307 }); + expect(mocks.model).toHaveBeenCalledTimes(1); + const quota = mockDNS( + (_, type) => ({ + Status: 0, + Answer: type === 1 ? [answer(1, "8.8.8.8")] : [], + }), + 429, + ); + await expect(call()).rejects.toMatchObject({ + status: 429, + quota: false, + retry: true, + }); + expect(quota.model).toHaveBeenCalledTimes(1); + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response(null, { status: 429 })), + ); + await expect(call()).rejects.toMatchObject({ + code: "rate_limited", + status: 429, + }); + }); + + it("does not change trusted platform requests or swallow their HTTP failures", async () => { + const fetcher = vi.fn(async () => Response.json({ platform: true })); + vi.stubGlobal("fetch", fetcher); + expect(await call({ ...e, BYOK_REQUIRE_PUBLIC_ENDPOINT: false })).toEqual({ + platform: true, + }); + expect(fetcher).toHaveBeenCalledTimes(1); + expect(fetcher.mock.calls[0]).toEqual([ + ENDPOINT, + expect.objectContaining({ redirect: "manual" }), + ]); + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response(null, { status: 401 })), + ); + await expect( + call({ ...e, BYOK_REQUIRE_PUBLIC_ENDPOINT: false }), + ).rejects.toBeInstanceOf(ApiError); + }); +}); diff --git a/platform/github-app/tests/provider-test.test.ts b/platform/github-app/tests/provider-test.test.ts new file mode 100644 index 00000000..32be9a20 --- /dev/null +++ b/platform/github-app/tests/provider-test.test.ts @@ -0,0 +1,72 @@ +import { env } from "cloudflare:test"; +import { beforeAll, beforeEach, afterEach, expect, it, vi } from "vitest"; +import { putAIProvider, removeAIProviderKey } from "../src/byok"; +import { testAIProvider } from "../src/provider-test"; +import { JEV_MODEL } from "../src/jev"; + +declare const TEST_SQL: string[]; +const e: Env = { ...(env as Env), BYOK_ENCRYPTION_KEY: "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", TRIAGE_PROVIDER: "llm", LLM_API_KEY: "platform-secret-must-not-be-used", OPENROUTER_API_KEY: "platform-jev-secret-must-not-be-used" }; +const key = "user-private-provider-key"; +const fullName = "owner/repository"; +let answer: unknown; +let status = 200; +let privateAddress = false; +const calls: {url: string; init: RequestInit}[] = []; +const save = (provider: "llm" | "jev" = "llm") => putAIProvider(e, 100, fullName, { mode: "byok", provider, base_url: "https://openrouter.ai/api", model: provider === "jev" ? JEV_MODEL : "openai/gpt-4o-mini", api_key: key }, "admin"); +beforeAll(async () => { for (const sql of TEST_SQL) await e.DB.prepare(sql).run(); }); +beforeEach(async () => { + await e.DB.exec("DELETE FROM ai_providers; DELETE FROM api_rate; DELETE FROM audit_log;"); + calls.splice(0); status = 200; privateAddress = false; + answer = {choices:[{message:{content:'{"labels":["bug"]}'}}]}; + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, init: RequestInit = {}) => { + const url = String(input); calls.push({url,init}); + if (url.startsWith("https://cloudflare-dns.com/dns-query?name=openrouter.ai&")) + return Response.json({Status:0,Answer:url.endsWith("type=1")?[{name:"openrouter.ai",type:1,data:privateAddress?"10.0.0.1":"104.18.3.115"}]:[]}); + return Response.json(answer,{status}); + })); +}); +afterEach(() => vi.unstubAllGlobals()); +it("tests the saved user OpenAI service with synthetic content only and a capped output budget", async () => { + await save(); + expect(await testAIProvider(e, 100, fullName)).toEqual({provider:"llm",model:"openai/gpt-4o-mini"}); + const model = calls.filter(call=>!call.url.startsWith("https://cloudflare-dns.com")); + expect(model).toHaveLength(1); + expect(model[0].url).toBe("https://openrouter.ai/api/chat/completions"); + expect(new Headers(model[0].init.headers).get("authorization")).toBe(`Bearer ${key}`); + expect(JSON.parse(String(model[0].init.body)).max_tokens).toBe(512); + expect(calls.every(call=>!call.url.startsWith("https://api.github.com"))).toBe(true); + await expect(testAIProvider(e,100,fullName)).rejects.toMatchObject({code:"rate_limited",status:429}); + expect(await e.DB.prepare("SELECT count(*) n FROM ai_providers").first()).toEqual({n:1}); + expect(await e.DB.prepare("SELECT count(*) n FROM jobs").first()).toEqual({n:0}); +}); +it("tests saved Jev credentials through the typed Decisions endpoint", async () => { + await save("jev"); + answer = {model:JEV_MODEL,answers:{label_0:{type:"noul",noul:0.98}}}; + expect(await testAIProvider(e,100,fullName)).toEqual({provider:"jev",model:JEV_MODEL}); + const model = calls.find(call=>call.url.endsWith("/alpha/decisions"))!; + expect(new Headers(model.init.headers).get("authorization")).toBe(`Bearer ${key}`); + const payload = JSON.parse(String(model.init.body)); + expect(Object.keys(payload.questions)).toEqual(["label_0"]); + expect(payload.state.title).toBe("Application crashes on startup"); + expect(calls.some(call=>call.url.endsWith("/chat/completions"))).toBe(false); +}); +it("rejects malformed classifier output rather than declaring a working connection", async () => { + await save(); answer={choices:[{message:{content:"private unusable content"}}]}; + await expect(testAIProvider(e,100,fullName)).rejects.toMatchObject({code:"unavailable",status:503,message:"AI provider unavailable"}); +}); +it("never sends a user key when the provider resolves to a private network", async () => { + await save(); privateAddress=true; + await expect(testAIProvider(e,100,fullName)).rejects.toMatchObject({code:"unavailable",status:503}); + expect(calls).toHaveLength(2); + expect(calls.every(call=>!new Headers(call.init.headers).has("authorization"))).toBe(true); +}); +it("does not use platform credentials after removing BYOK or provider authentication failure", async () => { + await save(); await removeAIProviderKey(e,100,fullName,"admin"); + await expect(testAIProvider(e,100,fullName)).rejects.toMatchObject({code:"unavailable"}); + expect(calls).toEqual([]); + await save(); status=401; answer={error:key}; + await expect(testAIProvider(e,100,fullName)).rejects.toMatchObject({code:"unavailable",message:"AI provider unavailable"}); + const model=calls.find(call=>call.url.endsWith("/chat/completions"))!; + expect(new Headers(model.init.headers).get("authorization")).toBe(`Bearer ${key}`); + expect(calls.filter(call=>call.url.endsWith("/chat/completions"))).toHaveLength(1); +}); diff --git a/platform/github-app/tests/triage.test.ts b/platform/github-app/tests/triage.test.ts index 6fb73c86..ebdc7fa1 100644 --- a/platform/github-app/tests/triage.test.ts +++ b/platform/github-app/tests/triage.test.ts @@ -17,12 +17,14 @@ import { } from "../src/review"; import { DEFAULT_SETTINGS, putSettings, RepoSettings } from "../src/settings"; import { pickLabels, sanitizeIntro } from "../src/triage"; +import { putAIProvider, removeAIProviderKey } from "../src/byok"; declare const TEST_SQL: string[]; const testEnv = env as Env; -const llmEnv: Env = { ...testEnv, LLM_API_KEY: "sk-test" }; +const llmEnv: Env = { ...testEnv, LLM_API_KEY: "sk-test", BYOK_ENCRYPTION_KEY: "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE" }; const api = "https://api.github.com"; const LLM = "https://api.stepfun.com/v1/chat/completions"; +const OWN_LLM = "https://api.openai.com/v1/chat/completions"; const repo = "AsperforMias/test-bot"; const slug = "ghfind-review-test"; const issuePath = `/repos/${repo}/issues/1`; @@ -106,7 +108,7 @@ beforeAll(async () => { }); beforeEach(async () => { await testEnv.DB.exec( - "DELETE FROM jobs; DELETE FROM author_comment_once; DELETE FROM noscore_comment_budget; DELETE FROM repo_settings; DELETE FROM triage_labels;", + "DELETE FROM jobs; DELETE FROM author_comment_once; DELETE FROM noscore_comment_budget; DELETE FROM repo_settings; DELETE FROM triage_labels; DELETE FROM ai_providers;", ); llm = () => reply('{"labels":[]}'); vi.stubGlobal( @@ -116,7 +118,9 @@ beforeEach(async () => { const method = init.method ?? "GET"; const body = typeof init.body === "string" ? init.body : ""; calls.push({ url, method, body }); - if (url === LLM) return llm(JSON.parse(body)); + if (url === LLM || url === OWN_LLM) return llm(JSON.parse(body)); + if (url.startsWith("https://cloudflare-dns.com/dns-query?name=api.openai.com&")) + return Response.json({ Status: 0, Answer: url.endsWith("type=1") ? [{ name: "api.openai.com", type: 1, data: "104.18.32.7" }] : [] }); const at = routes.findIndex( (x) => x.url === url && @@ -502,3 +506,53 @@ describe("comments", () => { expect(Array.from(out).length).toBeLessThanOrEqual(600); }); }); + +describe("BYOK job execution", () => { + const userKey = "repository-owned-test-key"; + const configureOwn = () => putAIProvider(llmEnv, 100, repo, { mode: "byok", provider: "llm", base_url: "https://api.openai.com/v1", model: "gpt-4o-mini", api_key: userKey }, "admin"); + it("uses the repository provider for both semantic labels and AI greetings", async () => { + await configureOwn(); + await configure({ triageEnabled: true, allowedLabels: ["bug"], commentsEnabled: true, commentPrompt: "Welcome the contributor." }); + await add("byok-own-both"); + labelJob(); + llm = (request) => reply(request.messages[0].content.includes("classify") ? '{"labels":["bug"]}' : `Welcome! ${userKey}`); + route(`${issuePath}/labels`, {}, "POST", 200, { labels: ["bug"] }); + route(`${issuePath}/comments?per_page=100&page=1`, []); + route(`${issuePath}/comments`, { id: 1 }, "POST"); + await runJob(llmEnv, "byok-own-both"); + expect(await job("byok-own-both")).toMatchObject({ state: "done", result: LABELS[2] }); + const modelRequests = vi.mocked(fetch).mock.calls.filter(([url]) => String(url) === OWN_LLM); + expect(modelRequests).toHaveLength(2); + expect(modelRequests.every(([, init]) => new Headers(init?.headers).get("authorization") === `Bearer ${userKey}`)).toBe(true); + expect(modelRequests.every(([, init]) => JSON.parse(String(init?.body)).model === "gpt-4o-mini")).toBe(true); + expect(llmCalls()).toEqual([]); + expect(await recorded()).toEqual([{ number: 1, label: "bug" }]); + const comment = commentCalls().find(x => x.method === "POST"); + expect(comment?.body).not.toContain(userKey); + expect(comment?.body).toContain("redacted"); + expect(comment?.body).toContain("82.7 / 100"); + }); + it("removed BYOK credentials disable AI while keeping ordinary score labels", async () => { + await configureOwn(); + await removeAIProviderKey(llmEnv, 100, repo, "admin"); + await configure({ triageEnabled: true, allowedLabels: ["bug"] }); + await add("byok-removed"); + labelJob(); + await runJob(llmEnv, "byok-removed"); + expect(await job("byok-removed")).toMatchObject({ state: "done", result: LABELS[2] }); + expect(calls.filter(x => x.url === OWN_LLM || x.url === LLM)).toEqual([]); + expect(await recorded()).toEqual([]); + }); + it("a BYOK provider failure never falls back to a platform credential", async () => { + await configureOwn(); + await configure({ triageEnabled: true, allowedLabels: ["bug"] }); + await add("byok-failed"); + labelJob(); + llm = () => new Response("private provider failure", { status: 401 }); + await runJob(llmEnv, "byok-failed"); + expect(await job("byok-failed")).toMatchObject({ state: "done", result: LABELS[2] }); + expect(calls.filter(x => x.url === OWN_LLM)).toHaveLength(1); + expect(llmCalls()).toEqual([]); + expect(await recorded()).toEqual([]); + }); +}); diff --git a/platform/github-app/vitest.config.ts b/platform/github-app/vitest.config.ts index 8408f10a..d893b930 100644 --- a/platform/github-app/vitest.config.ts +++ b/platform/github-app/vitest.config.ts @@ -41,6 +41,7 @@ export default defineConfig({ "0005_comment_and_email_limits.sql", "0006_repo_settings.sql", "0007_bot_operations.sql", + "0008_byok.sql", ] .map((f) => readFileSync(`migrations/${f}`, "utf8")) .join("\n"), diff --git a/src/app/[locale]/github-bot/github-bot.module.css b/src/app/[locale]/github-bot/github-bot.module.css index 1937399b..9ae6392a 100644 --- a/src/app/[locale]/github-bot/github-bot.module.css +++ b/src/app/[locale]/github-bot/github-bot.module.css @@ -41,6 +41,15 @@ .classification h3 { font-size: 18px; font-weight: 600; margin-bottom: 10px; } .classification article > p:not(.featureMode) { font-size: 14px; line-height: 1.85; color: var(--muted-foreground); } .classification article > .featureExample { margin-top: 16px; padding-inline-start: 14px; border-inline-start: 2px solid var(--border); font-size: 13px; } +.byok { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.2fr); gap: 48px; align-items: start; } +.byok .sectionHeading { min-width: 0; margin-bottom: 0; } +.byok .byokNote { margin-top: 16px; font-size: 13px; } +.byokDetails { min-width: 0; margin: 0; } +.byokDetails > div { padding: 16px 0; border-top: 1px solid var(--border); } +.byokDetails > div:first-child { padding-top: 0; border-top: 0; } +.byokDetails dt { font-size: 15px; font-weight: 600; line-height: 1.5; } +.byokDetails dd { margin: 6px 0 0; color: var(--muted-foreground); font-size: 14px; line-height: 1.8; overflow-wrap: anywhere; } +.byokBilling { margin-top: 24px; padding-top: 16px; border-top: 1px solid var(--border); color: var(--muted-foreground); font-size: 13px; line-height: 1.8; } .operations { margin: 0; } .operations > div { display: grid; grid-template-columns: minmax(180px, .8fr) minmax(0, 1.6fr); gap: 20px; padding: 18px 0; border-top: 1px solid var(--border); align-items: baseline; } .index { flex-shrink: 0; font-size: 12px; font-variant-numeric: tabular-nums; font-weight: 400; color: var(--gb-accent); } @@ -82,6 +91,7 @@ .sectionHeading { display: block; } .sectionHeading > p { margin-top: 10px; } .cli { grid-template-columns: 1fr; gap: 24px; } + .byok { grid-template-columns: 1fr; gap: 28px; } .notes { grid-template-columns: 1fr; gap: 24px; } } @media (max-width: 640px) { @@ -93,6 +103,7 @@ .classification { grid-template-columns: 1fr; gap: 28px; } .sectionHeading h2, .cli h2 { font-size: 21px; } .sectionHeading > p, .classification article > p:not(.featureMode), .operations dd, .cli p, .notes p { font-size: 16px; } + .byokDetails dd { font-size: 16px; } .operations > div { grid-template-columns: 1fr; gap: 8px; } .operations dd { padding-inline-start: 34px; } .cli { padding: 24px 20px; } diff --git a/src/components/pages/GithubBotView.tsx b/src/components/pages/GithubBotView.tsx index 35ff9c00..590cac20 100644 --- a/src/components/pages/GithubBotView.tsx +++ b/src/components/pages/GithubBotView.tsx @@ -21,6 +21,7 @@ const ADMIN_PAGES = [ { id: "activity", path: "/admin/activity", icon: History }, ] as const; const OPERATIONS = ["preview", "backfill", "cleanup"] as const; +const AI_OPTIONS = ["provider", "protocol", "key", "test"] as const; const QUEUES = [ { id: "high", filter: 'is:open is:issue label:"review: high"' }, { id: "top", filter: 'is:open is:issue label:"review: top"' }, @@ -86,6 +87,29 @@ export function GithubBotView({ locale, t }: { locale: string; t: Translator }) ))} +
    +
    +
    +

    {t("byok.heading")}

    +

    {t("byok.lead")}

    + +

    {t("byok.setup")}

    +
    +
    + {AI_OPTIONS.map(id => ( +
    +
    {t(`byok.items.${id}.title`)}
    +
    {t(`byok.items.${id}.body`)}
    +
    + ))} +
    +
    +

    {t("byok.billing")}

    +

    {t("operations.heading")}

    {t("operations.lead")}

    diff --git a/src/messages/ar.json b/src/messages/ar.json index 306ee8c7..471837c3 100644 --- a/src/messages/ar.json +++ b/src/messages/ar.json @@ -1401,7 +1401,7 @@ }, "githubBot": { "metaTitle": "ghfind Review | بوت GitHub لتصنيف Issues وPRs", - "metaDescription": "أدِر تسميات درجة المؤلف وتصنيف المحتوى الاختياري والمعاينات ومعالجة العناصر السابقة والتنظيف من لوحة تحكم بوت ghfind Review أو CLI.", + "metaDescription": "أدِر تسميات درجة المؤلف وتصنيف المحتوى والمعاينات والتنظيف في ghfind Review، واربط خدمة الذكاء الاصطناعي الخاصة بك (BYOK) لكل مستودع.", "topline": { "section": "التكاملات", "current": "GitHub Bot" @@ -1451,9 +1451,34 @@ "mode": "اختياري · معطّل افتراضيًا", "title": "تصنيف المحتوى", "body": "قارن عنوان Issue أو PR ونصه بأوصاف التسميات الموجودة التي تختارها. عند التفعيل، يمكن للمصنّف إضافة ما يصل إلى ثلاث تسميات مطابقة، دون إنشاء تسميات أو تغيير أسمائها.", - "example": "يلزم إعداد خدمة التصنيف مسبقًا. جرّب اقتراحًا في اللوحة قبل التفعيل. تصنيف الذكاء الاصطناعي مستقل عن درجة المؤلف وقد يحتاج إلى تصحيح." + "example": "يلزم إعداد خدمة التصنيف مسبقًا. جرّب اقتراحًا في اللوحة قبل التفعيل. تصنيف الذكاء الاصطناعي مستقل عن درجة المؤلف وقد يحتاج إلى تصحيح. اربط خدمة الذكاء الاصطناعي الخاصة بك من إعدادات المستودع." } }, + "byok": { + "heading": "اربط خدمة الذكاء الاصطناعي الخاصة بك", + "lead": "استخدم عنوان API ومفتاحك ونموذجك. اضبط كل مستودع على حدة، ثم اختر خدمتك أو خدمة المنصة.", + "cta": "إعداد خدمة الذكاء الاصطناعي", + "setup": "افتح مستودعًا ثم اختر خدمة الذكاء الاصطناعي. يتطلب حفظ الإعدادات صلاحية مسؤول المستودع.", + "items": { + "provider": { + "title": "اختر الخدمة لكل مستودع", + "body": "بدّل بين خدمة المنصة وعنوان API الأساسي العام الخاص بك عبر HTTPS. يحتفظ كل مستودع بإعداداته المستقلة." + }, + "protocol": { + "title": "اختر البروتوكول والنموذج", + "body": "يدعم Chat Completions المتوافق مع OpenAI تصنيف المحتوى وإنشاء التحيات. أما Jev Decisions فيصنّف المحتوى فقط." + }, + "key": { + "title": "احفظ مفتاحك بأمان", + "body": "تُحفظ مفاتيح API مشفّرة ولا تُعرض مرة أخرى. يمكنك استبدال المفتاح المحفوظ أو إزالته من اللوحة." + }, + "test": { + "title": "اختبر قبل التفعيل", + "body": "اختبر الاتصال المحفوظ بشكل صريح. لا يغيّر الاختبار شيئًا على GitHub ولا يحفظ نصوص عينات. يبقى تصنيف المحتوى معطّلًا افتراضيًا." + } + }, + "billing": "يحاسبك مزوّدك على الطلبات باستخدام مفتاحك. إذا أخفقت خدمتك، فلن ينتقل البوت إلى خدمة المنصة بصمت." + }, "operations": { "heading": "عاين أولًا. ثم قرّر.", "lead": "تحكّم في كل مستودع على حدة، مع تسجيل التغييرات في سجل النشاط.", diff --git a/src/messages/en.json b/src/messages/en.json index 5342b9a9..d403e0ab 100644 --- a/src/messages/en.json +++ b/src/messages/en.json @@ -1401,7 +1401,7 @@ }, "githubBot": { "metaTitle": "ghfind Review | GitHub Bot for Issue and PR triage", - "metaDescription": "Manage author-score labels, optional content classification, previews, backfills and cleanup from the ghfind Review Bot console or CLI.", + "metaDescription": "ghfind Review combines author-score labels and content classification with previews, cleanup and your own AI service (BYOK), managed per repository.", "topline": { "section": "Integrations", "current": "GitHub Bot" @@ -1451,9 +1451,34 @@ "mode": "Optional · Off by default", "title": "Content classification", "body": "Compare the Issue or PR title and body with descriptions of existing labels you select. When enabled, the classifier can add up to three matching labels without creating or renaming any labels.", - "example": "Requires a configured classification service. Try a suggestion in the console before enabling it. AI classification is separate from the author score and may need correction." + "example": "Requires a configured classification service. Try a suggestion in the console before enabling it. AI classification is separate from the author score and may need correction. Connect your own AI service in repository settings." } }, + "byok": { + "heading": "Use your own AI service", + "lead": "Bring your endpoint, API key and model. Configure each repository separately, then choose your service or the platform service.", + "cta": "Configure your AI service", + "setup": "Open a repository, then choose AI service. Saving requires repository admin access.", + "items": { + "provider": { + "title": "Choose the service per repository", + "body": "Switch between the platform service and your own public HTTPS API base URL. Each repository keeps its own configuration." + }, + "protocol": { + "title": "Choose the protocol and model", + "body": "OpenAI-compatible Chat Completions can classify content and generate greetings. Jev Decisions classifies content only." + }, + "key": { + "title": "Keep your key private", + "body": "API keys are encrypted at rest and never shown again. Replace or remove a saved key from the console." + }, + "test": { + "title": "Test before enabling", + "body": "Explicitly test the saved connection. The test makes no GitHub changes and stores no sample text. Content classification remains off by default." + } + }, + "billing": "Your provider bills requests to your key. If your own service fails, the Bot does not silently switch to the platform service." + }, "operations": { "heading": "Preview first. Then decide.", "lead": "Control each repository individually, with changes recorded in the activity log.", diff --git a/src/messages/es.json b/src/messages/es.json index d2fa547d..2ac510d9 100644 --- a/src/messages/es.json +++ b/src/messages/es.json @@ -1401,7 +1401,7 @@ }, "githubBot": { "metaTitle": "ghfind Review | Bot de GitHub para clasificar Issues y PRs", - "metaDescription": "Gestiona las etiquetas de puntuación del autor, la clasificación opcional del contenido, las vistas previas, el procesamiento de envíos existentes y la limpieza desde la consola del Bot ghfind Review o la CLI.", + "metaDescription": "ghfind Review combina etiquetas de puntuación y clasificación de contenido con vistas previas, limpieza y tu propio servicio de IA (BYOK), por repositorio.", "topline": { "section": "Integraciones", "current": "GitHub Bot" @@ -1451,9 +1451,34 @@ "mode": "Opcional · Desactivada por defecto", "title": "Clasificación del contenido", "body": "Compara el título y el cuerpo del Issue o PR con las descripciones de las etiquetas existentes que selecciones. Al activarse, el clasificador puede añadir hasta tres etiquetas coincidentes sin crear ni renombrar ninguna.", - "example": "Requiere un servicio de clasificación configurado. Prueba una sugerencia en la consola antes de activarla. La clasificación por IA es independiente de la puntuación del autor y puede necesitar correcciones." + "example": "Requiere un servicio de clasificación configurado. Prueba una sugerencia en la consola antes de activarla. La clasificación por IA es independiente de la puntuación del autor y puede necesitar correcciones. Conecta tu propio servicio de IA en los ajustes del repositorio." } }, + "byok": { + "heading": "Usa tu propio servicio de IA", + "lead": "Usa tu URL de API, clave y modelo. Configura cada repositorio y elige tu servicio o el de la plataforma.", + "cta": "Configurar tu servicio de IA", + "setup": "Abre un repositorio y entra en Servicio de IA. Guardar requiere permisos de administrador del repositorio.", + "items": { + "provider": { + "title": "Elige el servicio por repositorio", + "body": "Alterna entre el servicio de la plataforma y tu propia URL base de API HTTPS pública. Cada repositorio conserva su configuración." + }, + "protocol": { + "title": "Elige protocolo y modelo", + "body": "Chat Completions compatible con OpenAI permite clasificar contenido y generar saludos. Jev Decisions solo clasifica contenido." + }, + "key": { + "title": "Protege tu clave", + "body": "Las claves de API se almacenan cifradas y nunca vuelven a mostrarse. Puedes sustituir o eliminar una clave guardada desde la consola." + }, + "test": { + "title": "Prueba antes de activar", + "body": "Prueba explícitamente la conexión guardada. La prueba no modifica GitHub ni guarda textos de ejemplo. La clasificación de contenido sigue desactivada por defecto." + } + }, + "billing": "Tu proveedor factura las solicitudes a tu clave. Si tu servicio falla, el Bot no cambia al servicio de la plataforma sin avisar." + }, "operations": { "heading": "Primero revisa. Después decide.", "lead": "Controla cada repositorio por separado; los cambios quedan registrados en el historial de actividad.", diff --git a/src/messages/id.json b/src/messages/id.json index 44c0a01f..d1fa5829 100644 --- a/src/messages/id.json +++ b/src/messages/id.json @@ -1401,7 +1401,7 @@ }, "githubBot": { "metaTitle": "ghfind Review | Bot GitHub untuk klasifikasi Issue dan PR", - "metaDescription": "Kelola label skor penulis, klasifikasi konten opsional, pratinjau, pemrosesan kiriman lama, dan pembersihan melalui konsol Bot ghfind Review atau CLI.", + "metaDescription": "ghfind Review memadukan label skor penulis dan klasifikasi konten dengan pratinjau, pembersihan, serta layanan AI milik Anda (BYOK), per repositori.", "topline": { "section": "Integrasi", "current": "GitHub Bot" @@ -1451,9 +1451,34 @@ "mode": "Opsional · Nonaktif secara bawaan", "title": "Klasifikasi konten", "body": "Bandingkan judul dan isi Issue atau PR dengan deskripsi label yang sudah ada dan Anda pilih. Saat diaktifkan, pengklasifikasi dapat menambahkan hingga tiga label yang cocok tanpa membuat atau mengganti nama label.", - "example": "Memerlukan layanan klasifikasi yang sudah dikonfigurasi. Coba saran di konsol sebelum mengaktifkannya. Klasifikasi AI terpisah dari skor penulis dan mungkin perlu dikoreksi." + "example": "Memerlukan layanan klasifikasi yang sudah dikonfigurasi. Coba saran di konsol sebelum mengaktifkannya. Klasifikasi AI terpisah dari skor penulis dan mungkin perlu dikoreksi. Hubungkan layanan AI milik Anda melalui pengaturan repositori." } }, + "byok": { + "heading": "Gunakan layanan AI milik Anda", + "lead": "Gunakan alamat API, kunci, dan model Anda. Atur tiap repositori, lalu pilih layanan Anda atau layanan platform.", + "cta": "Atur layanan AI Anda", + "setup": "Buka repositori, lalu pilih Layanan AI. Menyimpan pengaturan memerlukan akses admin repositori.", + "items": { + "provider": { + "title": "Pilih layanan per repositori", + "body": "Beralih antara layanan platform dan URL dasar API HTTPS publik milik Anda. Setiap repositori menyimpan konfigurasi sendiri." + }, + "protocol": { + "title": "Pilih protokol dan model", + "body": "Chat Completions yang kompatibel dengan OpenAI dapat mengklasifikasikan konten dan membuat sapaan. Jev Decisions hanya mengklasifikasikan konten." + }, + "key": { + "title": "Jaga kerahasiaan kunci", + "body": "Kunci API disimpan dalam bentuk terenkripsi dan tidak pernah ditampilkan kembali. Ganti atau hapus kunci tersimpan melalui konsol." + }, + "test": { + "title": "Uji sebelum mengaktifkan", + "body": "Jalankan pengujian koneksi tersimpan secara eksplisit. Pengujian tidak mengubah GitHub dan tidak menyimpan teks contoh. Klasifikasi konten tetap nonaktif secara bawaan." + } + }, + "billing": "Penyedia Anda menagih permintaan melalui kunci Anda. Jika layanan Anda gagal, Bot tidak diam-diam beralih ke layanan platform." + }, "operations": { "heading": "Lihat pratinjau. Lalu putuskan.", "lead": "Kendalikan setiap repositori secara terpisah, dengan perubahan tercatat dalam log aktivitas.", diff --git a/src/messages/ja.json b/src/messages/ja.json index 8a7d517f..557dc611 100644 --- a/src/messages/ja.json +++ b/src/messages/ja.json @@ -1401,7 +1401,7 @@ }, "githubBot": { "metaTitle": "ghfind Review | Issue・PR の分類と管理を行う GitHub Bot", - "metaDescription": "ghfind Review Bot のコンソールや CLI から、投稿者スコアのラベル、任意の内容分類、プレビュー、既存投稿の処理、クリーンアップを管理できます。", + "metaDescription": "ghfind Review で投稿者スコアのラベル、内容分類、プレビュー、クリーンアップを管理。自分の AI サービス(BYOK)をリポジトリごとに接続できます。", "topline": { "section": "連携", "current": "GitHub Bot" @@ -1451,9 +1451,34 @@ "mode": "任意機能 · 初期設定では無効", "title": "内容の分類", "body": "Issue や PR のタイトル・本文を、選択した既存ラベルの説明と比較します。有効にすると、分類器が一致するラベルを最大 3 個付けます。ラベルの新規作成や名前変更は行いません。", - "example": "設定済みの分類サービスが必要です。有効にする前にコンソールで候補を試せます。AI による分類は投稿者スコアとは別の機能で、結果の修正が必要な場合があります。" + "example": "設定済みの分類サービスが必要です。有効にする前にコンソールで候補を試せます。AI による分類は投稿者スコアとは別の機能で、結果の修正が必要な場合があります。 リポジトリ設定から自分の AI サービスを接続できます。" } }, + "byok": { + "heading": "自分の AI サービスを接続", + "lead": "独自の API URL・キー・モデルを使えます。リポジトリごとに設定し、独自サービスかプラットフォームのサービスを選択します。", + "cta": "AI サービスを設定", + "setup": "リポジトリを開き、「AI サービス」を選択します。保存にはリポジトリの管理者権限が必要です。", + "items": { + "provider": { + "title": "リポジトリごとにサービスを選択", + "body": "プラットフォームのサービスと、独自の公開 HTTPS API ベース URL を切り替えられます。設定はリポジトリごとに保存されます。" + }, + "protocol": { + "title": "プロトコルとモデルを選択", + "body": "OpenAI 互換の Chat Completions は内容分類と挨拶文の生成に対応します。Jev Decisions は内容分類のみ対応します。" + }, + "key": { + "title": "キーを安全に保存", + "body": "API キーは暗号化して保存され、保存後は再表示されません。コンソールで保存済みのキーを交換・削除できます。" + }, + "test": { + "title": "有効にする前に接続テスト", + "body": "保存済みの接続を明示的にテストできます。GitHub の変更やサンプルテキストの保存は行いません。内容分類は初期設定では無効のままです。" + } + }, + "billing": "利用料金はご自身のキーに対してサービス提供者が請求します。独自サービスで失敗しても、Bot が黙ってプラットフォームのサービスへ切り替えることはありません。" + }, "operations": { "heading": "まずプレビュー。実行はその後に。", "lead": "リポジトリごとに管理でき、変更はアクティビティログに記録されます。", diff --git a/src/messages/ko.json b/src/messages/ko.json index 7a6261b3..d4e6785d 100644 --- a/src/messages/ko.json +++ b/src/messages/ko.json @@ -1401,7 +1401,7 @@ }, "githubBot": { "metaTitle": "ghfind Review | Issue와 PR을 분류하는 GitHub Bot", - "metaDescription": "ghfind Review Bot 콘솔이나 CLI에서 작성자 점수 라벨, 선택적 콘텐츠 분류, 미리보기, 기존 항목 처리, 정리를 관리하세요.", + "metaDescription": "ghfind Review에서 작성자 점수 라벨, 콘텐츠 분류, 미리보기, 정리를 관리하고 저장소별로 자신의 AI 서비스(BYOK)를 연결하세요.", "topline": { "section": "연동", "current": "GitHub Bot" @@ -1451,9 +1451,34 @@ "mode": "선택 기능 · 기본값은 꺼짐", "title": "콘텐츠 분류", "body": "Issue나 PR의 제목과 본문을 선택한 기존 라벨의 설명과 비교합니다. 활성화하면 분류기가 일치하는 라벨을 최대 3개까지 추가하며, 라벨을 새로 만들거나 이름을 바꾸지 않습니다.", - "example": "분류 서비스가 설정되어 있어야 합니다. 활성화하기 전에 콘솔에서 추천을 시험해 보세요. AI 분류는 작성자 점수와 별개이며 결과를 수정해야 할 수 있습니다." + "example": "분류 서비스가 설정되어 있어야 합니다. 활성화하기 전에 콘솔에서 추천을 시험해 보세요. AI 분류는 작성자 점수와 별개이며 결과를 수정해야 할 수 있습니다. 저장소 설정에서 자신의 AI 서비스를 연결하세요." } }, + "byok": { + "heading": "자신의 AI 서비스 연결", + "lead": "자신의 API 주소, 키, 모델을 사용하세요. 저장소별로 설정한 뒤 자체 서비스나 플랫폼 서비스를 선택할 수 있습니다.", + "cta": "AI 서비스 설정", + "setup": "저장소를 열고 AI 서비스를 선택하세요. 설정을 저장하려면 저장소 관리자 권한이 필요합니다.", + "items": { + "provider": { + "title": "저장소별 서비스 선택", + "body": "플랫폼 서비스와 자신의 공개 HTTPS API 기본 URL 사이에서 전환하세요. 저장소마다 설정을 따로 보관합니다." + }, + "protocol": { + "title": "프로토콜과 모델 선택", + "body": "OpenAI 호환 Chat Completions는 콘텐츠 분류와 인사말 생성을 지원합니다. Jev Decisions는 콘텐츠 분류만 지원합니다." + }, + "key": { + "title": "키를 안전하게 보관", + "body": "API 키는 암호화하여 저장되며 다시 표시되지 않습니다. 콘솔에서 저장한 키를 교체하거나 삭제할 수 있습니다." + }, + "test": { + "title": "활성화 전에 테스트", + "body": "저장된 연결을 명시적으로 테스트하세요. GitHub를 변경하거나 샘플 텍스트를 저장하지 않습니다. 콘텐츠 분류는 기본적으로 꺼진 상태를 유지합니다." + } + }, + "billing": "자체 공급자가 자신의 키로 수행한 요청에 요금을 청구합니다. 자체 서비스가 실패해도 Bot이 플랫폼 서비스로 조용히 전환하지 않습니다." + }, "operations": { "heading": "먼저 미리 보고, 그다음 결정하세요.", "lead": "저장소마다 개별적으로 제어하며, 변경 사항은 활동 로그에 기록됩니다.", diff --git a/src/messages/pt.json b/src/messages/pt.json index acc88236..89ba85be 100644 --- a/src/messages/pt.json +++ b/src/messages/pt.json @@ -1401,7 +1401,7 @@ }, "githubBot": { "metaTitle": "ghfind Review | Bot do GitHub para classificar Issues e PRs", - "metaDescription": "Gerencie etiquetas de pontuação do autor, classificação opcional de conteúdo, prévias, processamento de envios existentes e limpeza pelo console do Bot ghfind Review ou pela CLI.", + "metaDescription": "O ghfind Review reúne etiquetas de pontuação, classificação de conteúdo, prévias, limpeza e seu próprio serviço de IA (BYOK), por repositório.", "topline": { "section": "Integrações", "current": "GitHub Bot" @@ -1451,9 +1451,34 @@ "mode": "Opcional · Desativada por padrão", "title": "Classificação de conteúdo", "body": "Compare o título e o corpo do Issue ou PR com as descrições das etiquetas existentes que você selecionar. Quando ativado, o classificador pode adicionar até três etiquetas correspondentes, sem criar nem renomear etiquetas.", - "example": "Requer um serviço de classificação configurado. Teste uma sugestão no console antes de ativar. A classificação por IA é independente da pontuação do autor e pode precisar de correção." + "example": "Requer um serviço de classificação configurado. Teste uma sugestão no console antes de ativar. A classificação por IA é independente da pontuação do autor e pode precisar de correção. Conecte seu próprio serviço de IA nas configurações do repositório." } }, + "byok": { + "heading": "Use seu próprio serviço de IA", + "lead": "Use sua URL de API, chave e modelo. Configure cada repositório e escolha seu serviço ou o da plataforma.", + "cta": "Configurar seu serviço de IA", + "setup": "Abra um repositório e selecione Serviço de IA. Salvar exige acesso de administrador ao repositório.", + "items": { + "provider": { + "title": "Escolha o serviço por repositório", + "body": "Alterne entre o serviço da plataforma e sua própria URL base de API HTTPS pública. Cada repositório mantém sua configuração." + }, + "protocol": { + "title": "Escolha o protocolo e o modelo", + "body": "Chat Completions compatível com OpenAI permite classificar conteúdo e gerar saudações. Jev Decisions apenas classifica conteúdo." + }, + "key": { + "title": "Proteja sua chave", + "body": "As chaves de API são armazenadas criptografadas e nunca são exibidas novamente. Substitua ou remova uma chave salva pelo console." + }, + "test": { + "title": "Teste antes de ativar", + "body": "Teste explicitamente a conexão salva. O teste não altera o GitHub nem salva textos de exemplo. A classificação de conteúdo continua desativada por padrão." + } + }, + "billing": "Seu provedor cobra as solicitações feitas com sua chave. Se seu serviço falhar, o Bot não muda silenciosamente para o serviço da plataforma." + }, "operations": { "heading": "Veja a prévia. Depois decida.", "lead": "Controle cada repositório separadamente, com alterações registradas no histórico de atividade.", diff --git a/src/messages/vi.json b/src/messages/vi.json index 51074596..c301ca0b 100644 --- a/src/messages/vi.json +++ b/src/messages/vi.json @@ -1401,7 +1401,7 @@ }, "githubBot": { "metaTitle": "ghfind Review | Bot GitHub để phân loại Issue và PR", - "metaDescription": "Quản lý nhãn điểm tác giả, phân loại nội dung tùy chọn, xem trước, xử lý các mục có sẵn và dọn dẹp qua bảng điều khiển Bot ghfind Review hoặc CLI.", + "metaDescription": "ghfind Review quản lý nhãn điểm tác giả, phân loại nội dung, xem trước, dọn dẹp và kết nối dịch vụ AI của bạn (BYOK) theo từng kho mã.", "topline": { "section": "Tích hợp", "current": "GitHub Bot" @@ -1451,9 +1451,34 @@ "mode": "Tùy chọn · Mặc định tắt", "title": "Phân loại nội dung", "body": "So sánh tiêu đề và nội dung Issue hoặc PR với mô tả của các nhãn có sẵn mà bạn chọn. Khi được bật, bộ phân loại có thể thêm tối đa ba nhãn phù hợp mà không tạo mới hoặc đổi tên nhãn.", - "example": "Cần có dịch vụ phân loại đã được cấu hình. Thử gợi ý trong bảng điều khiển trước khi bật. Phân loại bằng AI độc lập với điểm tác giả và có thể cần chỉnh sửa." + "example": "Cần có dịch vụ phân loại đã được cấu hình. Thử gợi ý trong bảng điều khiển trước khi bật. Phân loại bằng AI độc lập với điểm tác giả và có thể cần chỉnh sửa. Kết nối dịch vụ AI của bạn trong cài đặt kho mã." } }, + "byok": { + "heading": "Kết nối dịch vụ AI của bạn", + "lead": "Dùng địa chỉ API, khóa và mô hình của bạn. Cấu hình riêng từng kho mã, rồi chọn dịch vụ của bạn hoặc của nền tảng.", + "cta": "Cấu hình dịch vụ AI", + "setup": "Mở kho mã, rồi chọn Dịch vụ AI. Cần quyền quản trị kho mã để lưu cấu hình.", + "items": { + "provider": { + "title": "Chọn dịch vụ cho từng kho mã", + "body": "Chuyển giữa dịch vụ nền tảng và URL cơ sở API HTTPS công khai của bạn. Mỗi kho mã lưu cấu hình riêng." + }, + "protocol": { + "title": "Chọn giao thức và mô hình", + "body": "Chat Completions tương thích OpenAI hỗ trợ phân loại nội dung và tạo lời chào. Jev Decisions chỉ phân loại nội dung." + }, + "key": { + "title": "Bảo vệ khóa của bạn", + "body": "Khóa API được lưu dưới dạng mã hóa và không bao giờ hiển thị lại. Bạn có thể thay thế hoặc xóa khóa đã lưu trong bảng điều khiển." + }, + "test": { + "title": "Kiểm tra trước khi bật", + "body": "Chủ động kiểm tra kết nối đã lưu. Kiểm tra không thay đổi GitHub và không lưu văn bản mẫu. Phân loại nội dung vẫn mặc định tắt." + } + }, + "billing": "Nhà cung cấp tính phí các yêu cầu bằng khóa của bạn. Nếu dịch vụ của bạn gặp lỗi, Bot không âm thầm chuyển sang dịch vụ nền tảng." + }, "operations": { "heading": "Xem trước. Sau đó quyết định.", "lead": "Kiểm soát từng kho mã riêng biệt, với các thay đổi được ghi vào nhật ký hoạt động.", diff --git a/src/messages/zh.json b/src/messages/zh.json index a543b5b4..204373d1 100644 --- a/src/messages/zh.json +++ b/src/messages/zh.json @@ -1408,7 +1408,7 @@ }, "githubBot": { "metaTitle": "ghfind Review | Issue 和 PR 分类与管理 Bot", - "metaDescription": "通过 ghfind Review Bot 后台或 CLI 管理作者评分标签、可选内容语义打标、建议预览、手动回填和 Bot 清理。", + "metaDescription": "ghfind Review 提供作者评分、内容语义打标、预览与清理,并支持按仓库接入自己的 AI 服务(BYOK)。", "topline": { "section": "集成", "current": "GitHub Bot" @@ -1458,9 +1458,34 @@ "mode": "可选功能 · 默认关闭", "title": "内容语义打标", "body": "将 Issue 或 PR 的标题、正文与管理员选择的现有 label description 比较。开启后,分类器最多添加三个匹配标签,不创建或重命名标签。", - "example": "需要已配置分类服务。先在后台试跑打标建议,再决定是否启用。AI 分类与作者评分独立,结果可能需要人工修正。" + "example": "需要已配置分类服务。先在后台试跑打标建议,再决定是否启用。AI 分类与作者评分独立,结果可能需要人工修正。 在仓库设置中接入自己的 AI 服务。" } }, + "byok": { + "heading": "接入自己的 AI 服务", + "lead": "使用自己的 API 地址、密钥和模型。按仓库独立配置,自行选择平台服务或自有服务。", + "cta": "配置自己的 AI 服务", + "setup": "先打开仓库,再进入 AI 服务。保存配置需要仓库管理员权限。", + "items": { + "provider": { + "title": "按仓库选择服务", + "body": "在平台服务与自己的公开 HTTPS API 地址之间切换,每个仓库分别保存配置。" + }, + "protocol": { + "title": "选择协议与模型", + "body": "OpenAI 兼容的 Chat Completions 支持内容分类和开场白生成;Jev Decisions 仅用于内容分类。" + }, + "key": { + "title": "安全保存密钥", + "body": "API Key 加密存储,保存后不会再次显示。可在后台替换或移除已保存的密钥。" + }, + "test": { + "title": "开启前先测试", + "body": "主动测试已保存的连接,不修改 GitHub,也不保存样本文本。内容分类仍默认关闭。" + } + }, + "billing": "调用费用由自己的服务商按密钥计费。自有服务失败时,Bot 不会悄悄切换到平台服务。" + }, "operations": { "heading": "先看建议,再决定如何执行", "lead": "按仓库分别控制,操作变化有记录可查。",