Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
d72f495
feat(bot): validate public endpoints for user AI services
AsperforMias Oct 7, 2026
542f187
feat(bot): encrypt repository AI credentials
AsperforMias Oct 7, 2026
2ffc277
feat(bot): guard BYOK requests and redact reflected credentials
AsperforMias Oct 7, 2026
09206b0
feat(bot): use repository AI services in queued jobs
AsperforMias Oct 7, 2026
167d0a1
feat(bot): use repository AI services in intent previews
AsperforMias Oct 7, 2026
06bdc9e
feat(bot): test saved AI providers with synthetic content
AsperforMias Oct 7, 2026
147af21
feat(bot): expose repository BYOK configuration API
AsperforMias Oct 7, 2026
6941bfb
feat(bot): add repository AI service settings
AsperforMias Oct 7, 2026
d90f23e
test(bot): cover BYOK admin access and safe audit rendering
AsperforMias Oct 7, 2026
45c1838
chore(bot): support BYOK in isolated dashboard previews
AsperforMias Oct 7, 2026
f82f1a5
feat(i18n): explain bot BYOK in Chinese
AsperforMias Oct 7, 2026
e0eff1e
feat(i18n): explain bot BYOK in English
AsperforMias Oct 7, 2026
3d309ed
feat(i18n): explain bot BYOK in Spanish
AsperforMias Oct 7, 2026
a0b6a1d
feat(i18n): explain bot BYOK in Indonesian
AsperforMias Oct 7, 2026
3167bd3
feat(i18n): explain bot BYOK in Japanese
AsperforMias Oct 7, 2026
33a924e
feat(i18n): explain bot BYOK in Korean
AsperforMias Oct 7, 2026
ff3f1a6
feat(i18n): explain bot BYOK in Portuguese
AsperforMias Oct 7, 2026
cf1db8b
feat(i18n): explain bot BYOK in Vietnamese
AsperforMias Oct 7, 2026
8060b55
feat(i18n): explain bot BYOK in Arabic
AsperforMias Oct 7, 2026
f42ee26
feat(web): introduce BYOK setup and backend entry
AsperforMias Oct 7, 2026
c0666f4
docs(bot): document user providers and encrypted key setup
AsperforMias Oct 7, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 103 additions & 1 deletion platform/github-app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<https://bot.ghfind.com/admin/repositories>, 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,
Expand Down Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions platform/github-app/migrations/0008_byok.sql
Original file line number Diff line number Diff line change
@@ -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
);
15 changes: 11 additions & 4 deletions platform/github-app/scripts/dev-dashboard.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "";
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -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",
Expand All @@ -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);
Expand Down Expand Up @@ -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") }]; }));
};
Expand Down
Loading
Loading