fix(github-chat): handle 404 removed installations, centralize URL validation, and extract initial import helper

This commit is contained in:
cryppadotta committed 2026-12-04 23:49:33 +00:00
1 parent b4c4c58000
commit 28cbb10cfa
10 files changed
+804 -160

No files matched your search

+11 -1
View File
@@ -3105,7 +3105,17 @@ export { isAppAggregator, aggregatorManagementUrl, aggregatorAppsSyncSchema, agg
export * from "./connection-instructions.js";
export * from "./customer-success.js";
export type { GitHubAppOwner, GitHubAppRegistrationInput, GitHubAppCloudState, GitHubAppWizardState, GitHubVerificationCheck, GitHubVerificationCheckCode } from "./types/github-app-setup.js";
export {
safeGitHubAppInstallUrl,
safeGitHubAppUrl,
safeGitHubInstallationManagementUrl,
type GitHubAppOwner,
type GitHubAppRegistrationInput,
type GitHubAppCloudState,
type GitHubAppWizardState,
type GitHubVerificationCheck,
type GitHubVerificationCheckCode,
} from "./types/github-app-setup.js";
export * from "./decision-models.js";
export { updatePrimaryAgentSchema, type UpdatePrimaryAgent, type PrimaryAgentPreference } from "./primary-agent.js";
@@ -63,3 +63,43 @@ export type GitHubAppWizardState = {
runtimeChecks?: GitHubVerificationCheck[];
message?: string;
};
const GITHUB_INSTALLATION_MANAGEMENT_PATH =
/^\/(?:settings|organizations\/[A-Za-z0-9-]+?\/settings)\/installations\/[1-9][0-9]*$/;
const GITHUB_APP_INSTALL_PATH = /^\/apps\/[a-z0-9-]+\/installations\/new$/;
function safeGitHubPathUrl(value: unknown, pattern: RegExp): string | undefined {
if (typeof value !== "string" || !value.trim()) return undefined;
try {
const url = new URL(value);
if (
url.origin !== "https://github.com" ||
url.username ||
url.password ||
url.search ||
url.hash ||
!pattern.test(url.pathname)
) {
return undefined;
}
return url.toString();
} catch {
return undefined;
}
}
export function safeGitHubInstallationManagementUrl(
value: unknown,
): string | undefined {
return safeGitHubPathUrl(value, GITHUB_INSTALLATION_MANAGEMENT_PATH);
}
export function safeGitHubAppInstallUrl(value: unknown): string | undefined {
return safeGitHubPathUrl(value, GITHUB_APP_INSTALL_PATH);
}
export function safeGitHubAppUrl(value: unknown): string | undefined {
return (
safeGitHubInstallationManagementUrl(value) ?? safeGitHubAppInstallUrl(value)
);
}
@@ -3461,6 +3461,12 @@ describeEmbeddedPostgres("chat channels: github setup and access", () => {
expect(afterFirst.setup.github?.initialRepositoryImportPending).toBe(true);
expect(afterFirst.setup.github?.repositorySelectionSaved).not.toBe(true);
// A direct empty initialGitHubImport call must not prematurely close initial import.
await service.replaceResources(endpoint.id, [], "owner-user", { initialGitHubImport: true });
const afterEmptyImport = await service.get(endpoint.id);
expect(afterEmptyImport.setup.github?.initialRepositoryImportPending).toBe(true);
expect(afterEmptyImport.setup.github?.repositorySelectionSaved).not.toBe(true);
// User grants one repository on GitHub and clicks Try again (advance).
repositories = [{
id: 97531,
@@ -3757,6 +3763,123 @@ describeEmbeddedPostgres("chat channels: github setup and access", () => {
await service.shutdown();
});
it("returns installation_missing with sanitized URLs when a verifying installation was removed on GitHub (HTTP 404)", async () => {
const fixture = await seedCompany();
const appRegistrationId = Number.parseInt(
fixture.companyId.replaceAll("-", "").slice(0, 8),
16,
);
const privateKey = generateKeyPairSync("rsa", { modulusLength: 2048 })
.privateKey.export({ type: "pkcs8", format: "pem" })
.toString();
const installationId = 78901;
let installationRemoved = false;
const providerFetch = (async (input: string | URL | Request) => {
const url = String(input);
if (url === "https://api.github.com/app") {
return Response.json({
id: appRegistrationId,
slug: `maya-404-${fixture.companyId.slice(0, 8)}`,
name: "Maya Removed Install",
owner: { login: "paperclipai", type: "Organization" },
permissions: { contents: "read", checks: "write", issues: "write", metadata: "read", pull_requests: "write" },
events: ["pull_request", "github_app_authorization", "installation", "installation_repositories", "issue_comment", "pull_request_review_comment"],
});
}
if (url === "https://api.github.com/app/installations?per_page=100") {
return Response.json(
installationRemoved
? []
: [{
id: installationId,
html_url: `https://github.com/organizations/paperclipai/settings/installations/${installationId}`,
account: { id: 1357, login: "paperclipai", type: "Organization" },
permissions: { contents: "read", checks: "write", issues: "write", metadata: "read", pull_requests: "write" },
suspended_at: null,
}],
);
}
if (url === `https://api.github.com/app/installations/${installationId}`) {
if (installationRemoved) {
return Response.json({ message: "Not Found" }, { status: 404 });
}
return Response.json({
id: installationId,
html_url: `https://github.com/organizations/paperclipai/settings/installations/${installationId}`,
account: { id: 1357, login: "paperclipai", type: "Organization" },
permissions: { contents: "read", checks: "write", issues: "write", metadata: "read", pull_requests: "write" },
suspended_at: null,
});
}
if (url === `https://api.github.com/app/installations/${installationId}/access_tokens`) {
if (installationRemoved) {
return Response.json({ message: "Not Found" }, { status: 404 });
}
return Response.json({ token: "installation-token" }, { status: 201 });
}
if (url === "https://api.github.com/installation/repositories?per_page=100&page=1") {
return Response.json({ repositories: [] });
}
if (url === "https://api.github.com/app/hook/deliveries?per_page=20") {
return Response.json([]);
}
throw new Error(`Unexpected provider request: ${url}`);
}) as typeof globalThis.fetch;
const { service } = createService(new FakeChatSdkRuntime(), providerFetch);
const endpoint = await service.create(
fixture.companyId,
{ provider: "github", assignedAgentId: fixture.assignedAgentId, name: "Maya Removed Install" },
"owner-user",
);
const { webhookSecret } = await service.generateSetupSecret(endpoint.id, "owner-user");
await service.storeGitHubApp(
endpoint.id,
"owner-user",
{ appId: String(appRegistrationId), privateKey, webhookSecret },
"existing_app",
);
await recordGitHubWebhookVerification(service, endpoint.publicId, webhookSecret);
const management = (await import("../../services/chat-github-management.js")).githubChatManagementService(db, providerFetch);
await management.linkObservedIdentity(endpoint.id, "owner-user", {
githubUserId: "42",
login: "octocat",
avatarUrl: null,
});
// Complete initial refresh and move to verifying (0 repositories).
const beforeRemove = await service.githubWizard.advance(endpoint.id, "owner-user");
expect(beforeRemove.state).toBe("verify");
// Simulate an unsafe stored managementUrl alongside a removed installation on GitHub.
installationRemoved = true;
await db
.update(chatEndpoints)
.set({
setup: sql`jsonb_set(${chatEndpoints.setup}, '{github}', coalesce(${chatEndpoints.setup}->'github', '{}'::jsonb) || '{"managementUrl":"https://evil.example/settings/installations/78901"}'::jsonb)`,
})
.where(eq(chatEndpoints.id, endpoint.id));
const result = await service.githubWizard.advance(endpoint.id, "owner-user");
expect(result.state).toBe("verify");
expect(result.installationUrl).toBe(
`https://github.com/apps/maya-404-${fixture.companyId.slice(0, 8)}/installations/new`,
);
// Unsafe stored managementUrl is rejected server-side; derived GitHub URL is returned instead.
expect(result.managementUrl).toBe(
`https://github.com/settings/installations/${installationId}`,
);
expect(result.verification?.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: false,
code: "installation_missing",
});
expect(result.verification?.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "permissions_required",
});
await service.shutdown();
});
it("strips workspace overrides from GitHub execution defaults on read, write, and task creation while preserving project defaults", async () => {
const previousExperimental = await instanceSettingsService(db).getExperimental();
onTestFinished(async () => {
@@ -0,0 +1,202 @@
import { describe, expect, it } from "vitest";
import {
deriveGitHubInitialRepositoryImport,
isGitHubInitialInstallRequired,
isGitHubInitialRepositoryImportPending,
planGitHubAdvanceRepositoryRefresh,
type GitHubInitialImportEndpoint,
} from "./chat-github-initial-import.js";
function makeBot(
overrides: Partial<GitHubInitialImportEndpoint> = {},
): GitHubInitialImportEndpoint {
return {
status: "attention",
providerAccountId: "acct-1",
setup: {
github: {
stage: "repositories",
initialSetupPending: true,
initialRepositoriesImported: false,
initialRepositoryImportPending: true,
repositorySelectionSaved: false,
},
},
...overrides,
};
}
describe("chat-github-initial-import", () => {
it("requires initial install when providerAccountId is missing or stage is install", () => {
expect(isGitHubInitialInstallRequired(makeBot({ providerAccountId: null }))).toBe(true);
expect(
isGitHubInitialInstallRequired(makeBot({ setup: { github: { stage: "install" } } })),
).toBe(true);
expect(isGitHubInitialInstallRequired(makeBot())).toBe(false);
});
it("plans repository refresh based on install/import state and active status", () => {
expect(planGitHubAdvanceRepositoryRefresh(makeBot())).toBe("refresh");
expect(
planGitHubAdvanceRepositoryRefresh(
makeBot({
status: "verifying",
setup: {
github: {
stage: "repositories",
initialSetupPending: false,
initialRepositoriesImported: true,
initialRepositoryImportPending: false,
repositorySelectionSaved: true,
},
},
}),
),
).toBe("refresh_if_no_enabled_available");
expect(
planGitHubAdvanceRepositoryRefresh(
makeBot({
status: "active",
setup: {
github: {
stage: "repositories",
initialSetupPending: false,
initialRepositoriesImported: true,
initialRepositoryImportPending: false,
repositorySelectionSaved: true,
},
},
}),
),
).toBe("skip");
});
it("imports all available repositories on fresh install even without a registration session", () => {
const decision = deriveGitHubInitialRepositoryImport(
makeBot(),
[
{ id: "r1", enabled: false, availability: "available" },
{ id: "r2", enabled: false, availability: "removed" },
{ id: "r3", enabled: false, availability: "available" },
],
{ hasRegistrationSession: false },
);
expect(decision).toEqual({
mode: "import_and_complete",
resourceIdsToEnable: ["r1", "r3"],
initializeDefaultConfig: true,
});
});
it("keeps initial import open when GitHub returns zero available repositories", () => {
expect(
deriveGitHubInitialRepositoryImport(makeBot(), [], { hasRegistrationSession: true }),
).toEqual({ mode: "await_repositories" });
expect(
deriveGitHubInitialRepositoryImport(
makeBot(),
[{ id: "r1", enabled: false, availability: "removed" }],
{ hasRegistrationSession: true },
),
).toEqual({ mode: "await_repositories" });
});
it("recovers verifying endpoints stuck with initialRepositoriesImported=true and pending import", () => {
const stuckBot = makeBot({
status: "verifying",
setup: {
github: {
stage: "repositories",
initialSetupPending: false,
initialRepositoriesImported: true,
initialRepositoryImportPending: true,
repositorySelectionSaved: false,
},
},
});
expect(isGitHubInitialRepositoryImportPending(stuckBot)).toBe(true);
expect(
deriveGitHubInitialRepositoryImport(
stuckBot,
[{ id: "r1", enabled: false, availability: "available" }],
{ hasRegistrationSession: false },
),
).toEqual({
mode: "import_and_complete",
resourceIdsToEnable: ["r1"],
initializeDefaultConfig: true,
});
});
it("skips import when the user already saved an explicit repository selection (even all disabled)", () => {
const bot = makeBot({
status: "verifying",
setup: {
github: {
stage: "repositories",
initialSetupPending: false,
initialRepositoriesImported: true,
initialRepositoryImportPending: false,
repositorySelectionSaved: true,
},
},
});
expect(isGitHubInitialRepositoryImportPending(bot)).toBe(false);
expect(
deriveGitHubInitialRepositoryImport(
bot,
[{ id: "r1", enabled: false, availability: "available" }],
{ hasRegistrationSession: false },
),
).toEqual({ mode: "skip" });
});
it("completes without auto-enabling repositories for legacy drafts without initialRepositoryImportPending", () => {
const legacyBot = makeBot({
status: "attention",
setup: {
github: {
stage: "repositories",
initialSetupPending: false,
initialRepositoriesImported: false,
repositorySelectionSaved: false,
},
},
});
expect(
deriveGitHubInitialRepositoryImport(
legacyBot,
[{ id: "r1", enabled: false, availability: "available" }],
{ hasRegistrationSession: false },
),
).toEqual({
mode: "complete_without_import",
initializeDefaultConfig: false,
});
});
it("never initializes default config for already-active bots", () => {
const activeBot = makeBot({
status: "active",
setup: {
github: {
stage: "repositories",
initialSetupPending: true,
initialRepositoriesImported: false,
initialRepositoryImportPending: true,
repositorySelectionSaved: false,
},
},
});
expect(
deriveGitHubInitialRepositoryImport(
activeBot,
[{ id: "r1", enabled: false, availability: "available" }],
{ hasRegistrationSession: true },
),
).toEqual({
mode: "complete_without_import",
initializeDefaultConfig: false,
});
});
});
@@ -0,0 +1,111 @@
export type GitHubInitialImportEndpoint = {
status: string;
providerAccountId: string | null;
setup: {
github?: {
stage?: string;
initialSetupPending?: boolean;
initialRepositoriesImported?: boolean;
initialRepositoryImportPending?: boolean;
repositorySelectionSaved?: boolean;
};
};
};
export type GitHubInitialImportResource = {
id: string;
enabled: boolean;
availability: string;
};
export type GitHubInitialImportDecision =
| { mode: "skip" }
| { mode: "await_repositories" }
| {
mode: "import_and_complete";
resourceIdsToEnable: string[];
initializeDefaultConfig: boolean;
}
| {
mode: "complete_without_import";
initializeDefaultConfig: boolean;
};
export function isGitHubInitialInstallRequired(
bot: GitHubInitialImportEndpoint,
): boolean {
return !bot.providerAccountId || bot.setup.github?.stage === "install";
}
export function isGitHubInitialRepositoryImportPending(
bot: GitHubInitialImportEndpoint,
): boolean {
return (
bot.status !== "active" &&
bot.setup.github?.initialRepositoryImportPending === true &&
!bot.setup.github?.repositorySelectionSaved
);
}
export function planGitHubAdvanceRepositoryRefresh(
bot: GitHubInitialImportEndpoint,
): "refresh" | "refresh_if_no_enabled_available" | "skip" {
const needsInitialImport =
bot.status !== "active" &&
(!bot.setup.github?.initialRepositoriesImported ||
isGitHubInitialRepositoryImportPending(bot));
if (
isGitHubInitialInstallRequired(bot) ||
needsInitialImport ||
bot.setup.github?.initialSetupPending === true
) {
return "refresh";
}
return bot.status !== "active" ? "refresh_if_no_enabled_available" : "skip";
}
export function deriveGitHubInitialRepositoryImport(
bot: GitHubInitialImportEndpoint,
resources: GitHubInitialImportResource[],
options: { hasRegistrationSession: boolean },
): GitHubInitialImportDecision {
const importPending = isGitHubInitialRepositoryImportPending(bot);
if (bot.setup.github?.initialRepositoriesImported && !importPending) {
return { mode: "skip" };
}
// Fresh manifest and manual Apps import GitHub's initial choices. Saved
// repository selections and review configuration still belong to the user
// on recovery, while pre-saved review configuration before App install
// must not block importing the App installation's repositories.
const initializeApp =
options.hasRegistrationSession ||
bot.setup.github?.initialSetupPending === true ||
importPending;
const initializeDefaultConfig = initializeApp && bot.status !== "active";
const awaitingInitialRepositories =
initializeApp &&
importPending &&
!resources.some((resource) => resource.enabled);
if (awaitingInitialRepositories) {
const resourceIdsToEnable = resources
.filter((resource) => resource.availability === "available")
.map((resource) => resource.id);
if (resourceIdsToEnable.length === 0) {
// Keep initial import pending when GitHub returns zero repositories so
// granting a repository on GitHub and retrying still imports it cleanly.
return { mode: "await_repositories" };
}
return {
mode: "import_and_complete",
resourceIdsToEnable,
initializeDefaultConfig,
};
}
return {
mode: "complete_without_import",
initializeDefaultConfig,
};
}
@@ -191,6 +191,10 @@ describe("GitHub verification check diagnostics and installation links", () => {
suspended_at?: string | null;
html_url?: string;
};
installationStatus?: number;
installationError?: Error;
savedManagementUrl?: string;
installationId?: string;
tokenStatus?: number;
}) {
const endpointRow = {
@@ -202,10 +206,20 @@ describe("GitHub verification check diagnostics and installation links", () => {
webhookVerifiedAt: "2026-10-10T00:00:00Z",
github: {
installationUrl: "https://github.com/apps/maya-reviews/installations/new",
managementUrl: "https://github.com/organizations/acme/settings/installations/12345",
managementUrl:
options.savedManagementUrl ??
"https://github.com/organizations/acme/settings/installations/12345",
},
},
};
if (options.installationId !== undefined) {
vi.mocked(githubBotCredentials).mockResolvedValue({
...credentials,
endpoint: endpointRow,
credentials: { installationId: options.installationId },
connection: { enabled: true, status: "active", applicationId: "app-1" },
} as never);
}
const selectResults = [
[endpointRow],
options.resources,
@@ -230,7 +244,16 @@ describe("GitHub verification check diagnostics and installation links", () => {
events: ["pull_request"],
});
}
if (url === "https://api.github.com/app/installations/12345") {
if (url === `https://api.github.com/app/installations/${options.installationId ?? "12345"}`) {
if (options.installationError) {
throw options.installationError;
}
if ((options.installationStatus ?? 200) >= 400) {
return Response.json(
{ message: "Installation lookup failed" },
{ status: options.installationStatus },
);
}
return Response.json(
options.installation ?? {
permissions: { contents: "read", pull_requests: "write", checks: "write" },
@@ -239,7 +262,7 @@ describe("GitHub verification check diagnostics and installation links", () => {
},
);
}
if (url === "https://api.github.com/app/installations/12345/access_tokens") {
if (url === `https://api.github.com/app/installations/${options.installationId ?? "12345"}/access_tokens`) {
if ((options.tokenStatus ?? 201) >= 400) {
return Response.json({ message: "Forbidden" }, { status: options.tokenStatus });
}
@@ -328,4 +351,158 @@ describe("GitHub verification check diagnostics and installation links", () => {
const result = await service.verification(endpoint.id);
expect(result.managementUrl).toBe("https://github.com/organizations/acme/settings/installations/12345");
});
it("maps a removed GitHub installation (HTTP 404) to installation_missing with managementUrl instead of throwing", async () => {
const { service } = verificationFixture({
resources: [],
installationStatus: 404,
});
const result = await service.verification(endpoint.id);
expect(result.ready).toBe(false);
expect(result.connectionReady).toBe(false);
expect(result.managementUrl).toBe("https://github.com/organizations/acme/settings/installations/12345");
expect(result.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: false,
code: "installation_missing",
});
expect(result.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "permissions_required",
});
expect(result.checks.find((check) => check.key === "repositories")?.detail).toContain(
"Install the GitHub App",
);
});
it.each([401, 403, 500])(
"keeps non-404 installation lookup failures (HTTP %s) separate from installation_missing",
async (status) => {
vi.useFakeTimers();
try {
const { service } = verificationFixture({
resources: [],
installationStatus: status,
});
const pending = service.verification(endpoint.id);
const assertion = expect(pending).rejects.toMatchObject({
status: 422,
details: { providerStatus: status },
});
await vi.runAllTimersAsync();
await assertion;
} finally {
vi.useRealTimers();
}
},
);
it("keeps transient network errors during installation lookup separate from installation_missing", async () => {
vi.useFakeTimers();
try {
const { service } = verificationFixture({
resources: [],
installationError: new TypeError("fetch failed"),
});
const pending = service.verification(endpoint.id);
const assertion = expect(pending).rejects.toMatchObject({
status: 422,
details: { code: "github_bot_temporarily_unavailable", retryable: true },
});
await vi.runAllTimersAsync();
await assertion;
} finally {
vi.useRealTimers();
}
});
it("reports permissions_required rather than no_installation_repositories when a suspended installation has zero enabled repositories", async () => {
const { service } = verificationFixture({
resources: [],
installation: {
permissions: { contents: "read", pull_requests: "write", checks: "write" },
suspended_at: "2026-10-10T01:00:00Z",
html_url: "https://github.com/organizations/acme/settings/installations/12345",
},
});
const result = await service.verification(endpoint.id);
expect(result.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: false,
code: "installation_suspended",
});
expect(result.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "permissions_required",
});
});
it("reports permissions_required rather than no_enabled_repositories when permissions are missing and cached repositories are disabled", async () => {
const { service } = verificationFixture({
resources: [
{
id: "repo-1",
type: "repository",
enabled: false,
availability: "available",
label: "acme/web",
providerResourceId: "acme/web",
metadata: { providerRepositoryId: "101" },
},
],
installation: {
permissions: { contents: "read", pull_requests: "write" },
suspended_at: null,
html_url: "https://github.com/organizations/acme/settings/installations/12345",
},
});
const result = await service.verification(endpoint.id);
expect(result.checks.find((check) => check.key === "permissions")).toMatchObject({
ok: false,
code: "permissions_missing",
});
expect(result.checks.find((check) => check.key === "repositories")).toMatchObject({
ok: false,
code: "permissions_required",
});
});
it("validates shared GitHub App and installation management URLs strictly", async () => {
const {
safeGitHubAppInstallUrl,
safeGitHubAppUrl,
safeGitHubInstallationManagementUrl,
} = await import("@paperclipai/shared");
expect(
safeGitHubInstallationManagementUrl(
"https://github.com/organizations/acme/settings/installations/12345",
),
).toBe("https://github.com/organizations/acme/settings/installations/12345");
expect(
safeGitHubInstallationManagementUrl("https://github.com/settings/installations/12345"),
).toBe("https://github.com/settings/installations/12345");
expect(
safeGitHubInstallationManagementUrl(
"https://github.com/apps/maya-reviews/installations/new",
),
).toBeUndefined();
expect(
safeGitHubInstallationManagementUrl(
"https://github.com/settings/installations/12345?next=https://evil.example",
),
).toBeUndefined();
expect(
safeGitHubAppInstallUrl("https://github.com/apps/maya-reviews/installations/new"),
).toBe("https://github.com/apps/maya-reviews/installations/new");
expect(
safeGitHubAppInstallUrl(
"https://github.com/apps/maya-reviews/installations/new?suggested_target_id=1",
),
).toBeUndefined();
expect(
safeGitHubAppUrl("https://evil.example/apps/maya-reviews/installations/new"),
).toBeUndefined();
expect(
safeGitHubAppUrl("https://github.com/apps/maya-reviews/installations/new#frag"),
).toBeUndefined();
});
});
+34 -32
View File
@@ -19,6 +19,7 @@ import {
} from "@paperclipai/db";
import {
defaultGitHubReviewPolicy,
safeGitHubInstallationManagementUrl,
updateGitHubChatConfigurationSchema,
type GitHubChatConfiguration,
type GitHubVerificationCheck,
@@ -34,26 +35,10 @@ import { resolveExecutionWorkspaceEnvironmentId } from "./execution-workspace-po
type DbTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
function safeGitHubInstallationUrl(value: unknown): string | undefined {
if (typeof value !== "string" || !value.trim()) return undefined;
try {
const url = new URL(value);
if (
url.origin !== "https://github.com" ||
url.username ||
url.password ||
url.search ||
url.hash ||
!/^\/(?:settings|organizations\/[A-Za-z0-9-]+?\/settings)\/installations\/[1-9][0-9]*$/.test(
url.pathname,
)
) {
return undefined;
}
return url.toString();
} catch {
return undefined;
}
function isGitHubNotFoundError(error: unknown): boolean {
if (!(error instanceof HttpError)) return false;
if (!error.details || typeof error.details !== "object") return false;
return (error.details as { providerStatus?: unknown }).providerStatus === 404;
}
export function githubChatManagementService(db: Db, fetchImpl = fetch) {
@@ -431,8 +416,15 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
: "The vaulted credentials identify a different GitHub App.",
});
const installationId = credentials.credentials.installationId;
const installation = installationId
? await githubBotRequest<{
let installation: {
permissions?: Record<string, string>;
suspended_at?: string | null;
html_url?: string;
account?: { login?: string; type?: string };
} | null = null;
if (installationId) {
try {
installation = await githubBotRequest<{
permissions?: Record<string, string>;
suspended_at?: string | null;
html_url?: string;
@@ -441,8 +433,16 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
fetchImpl,
credentials.appJwt,
`/app/installations/${installationId}`,
)
: null;
);
} catch (error) {
// A saved installation removed on GitHub returns HTTP 404. Map that
// missing installation to installation_missing so verification returns
// reinstall guidance and managementUrl, while keeping auth/server/
// transient failures separate.
if (!isGitHubNotFoundError(error)) throw error;
installation = null;
}
}
const derivedManagementUrl =
installationId && /^[1-9][0-9]*$/.test(installationId)
? installation?.account?.type === "Organization" &&
@@ -452,9 +452,9 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
: `https://github.com/settings/installations/${installationId}`
: undefined;
const managementUrl =
safeGitHubInstallationUrl(installation?.html_url) ??
safeGitHubInstallationUrl(bot.setup.github?.managementUrl) ??
safeGitHubInstallationUrl(derivedManagementUrl);
safeGitHubInstallationManagementUrl(installation?.html_url) ??
safeGitHubInstallationManagementUrl(bot.setup.github?.managementUrl) ??
safeGitHubInstallationManagementUrl(derivedManagementUrl);
const permissions = installation?.permissions ?? {};
const installationSuspended = !!installation?.suspended_at;
const permissionsOk =
@@ -554,7 +554,7 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
permissionsOk && resources.length > 0 && inaccessible.length === 0;
const repositoriesCode = repositoriesOk
? undefined
: !permissionsOk && resources.length > 0
: !permissionsOk
? ("permissions_required" as const)
: resources.length === 0
? availableResources.length > 0
@@ -564,11 +564,13 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
const repositoriesDetail = repositoriesOk
? `GitHub confirmed review access to ${resources.length === 1 ? "1 enabled repository" : `all ${resources.length} enabled repositories`}.`
: repositoriesCode === "permissions_required"
? installationSuspended
? "Unsuspend the GitHub App installation before verifying repository access."
: "Approve the required GitHub App installation permissions before verifying repository access."
? !installation
? "Install the GitHub App on GitHub before verifying repository access."
: installationSuspended
? "Unsuspend the GitHub App installation before verifying repository access."
: "Approve the required GitHub App installation permissions before verifying repository access."
: repositoriesCode === "no_enabled_repositories"
? `GitHub granted access to ${availableResources.length} ${availableResources.length === 1 ? "repository" : "repositories"}, but none are enabled in Paperclip. Enable at least one repository in Access settings, then try again.`
? `${availableResources.length} ${availableResources.length === 1 ? "repository is" : "repositories are"} synced from GitHub, but none are enabled in Paperclip. Enable at least one repository in Access settings, then try again.`
: repositoriesCode === "no_installation_repositories"
? "No repositories are accessible to this GitHub App installation. Grant access to at least one repository on GitHub, then try again."
: `GitHub could not authorize access to: ${inaccessible.join(", ")}. Restore installation access on GitHub, then try again.`;
+87 -91
View File
@@ -14,10 +14,12 @@ import {
toolConnections,
type Db,
} from "@paperclipai/db";
import type {
GitHubAppRegistrationInput,
GitHubAppWizardState,
GitHubAppCloudState,
import {
safeGitHubAppInstallUrl,
safeGitHubInstallationManagementUrl,
type GitHubAppRegistrationInput,
type GitHubAppWizardState,
type GitHubAppCloudState,
} from "@paperclipai/shared";
import { badRequest, conflict, forbidden, notFound } from "../errors.js";
import { logActivity } from "./activity-log.js";
@@ -25,6 +27,11 @@ import {
githubBotCredentials,
githubBotRequest,
} from "./chat-github-client.js";
import {
deriveGitHubInitialRepositoryImport,
isGitHubInitialInstallRequired,
planGitHubAdvanceRepositoryRefresh,
} from "./chat-github-initial-import.js";
import {
resyncGitHubAppWebhook,
listGitHubAppWebhookDeliveries,
@@ -879,22 +886,10 @@ export function githubChatWizardService(
};
}
}
const needsInitialInstall =
!bot.providerAccountId ||
bot.setup.github?.stage === "install";
const pendingInitialRepositoryImport =
bot.status !== "active" &&
bot.setup.github?.initialRepositoryImportPending === true &&
!bot.setup.github?.repositorySelectionSaved;
const needsInitialImport =
bot.status !== "active" &&
(!bot.setup.github?.initialRepositoriesImported ||
pendingInitialRepositoryImport);
let shouldRefreshRepositories =
needsInitialInstall ||
needsInitialImport ||
bot.setup.github?.initialSetupPending === true;
if (!shouldRefreshRepositories && bot.status !== "active") {
const needsInitialInstall = isGitHubInitialInstallRequired(bot);
const refreshPlan = planGitHubAdvanceRepositoryRefresh(bot);
let shouldRefreshRepositories = refreshPlan === "refresh";
if (refreshPlan === "refresh_if_no_enabled_available") {
const existingResources = await options.resources(id);
shouldRefreshRepositories = !existingResources.some(
(resource) => resource.enabled && resource.availability === "available",
@@ -905,10 +900,13 @@ export function githubChatWizardService(
await options.refreshRepositories(id, userId, managementContext);
} catch (error) {
if (needsInitialInstall || bot.status !== "verifying") {
const installationUrl = safeGitHubAppInstallUrl(
bot.setup.github?.installationUrl,
);
return {
endpointId: id,
state: "install",
installationUrl: bot.setup.github?.installationUrl,
...(installationUrl ? { installationUrl } : {}),
message:
error instanceof Error
? error.message
@@ -921,67 +919,7 @@ export function githubChatWizardService(
}
}
bot = await endpoint(id, userId);
const saved = await management.configuration(id, userId);
const importPendingAfterRefresh =
bot.status !== "active" &&
bot.setup.github?.initialRepositoryImportPending === true &&
!bot.setup.github?.repositorySelectionSaved;
if (
!bot.setup.github?.initialRepositoriesImported ||
importPendingAfterRefresh
) {
const resources = await options.resources(id);
const availableResources = resources.filter(
(resource) => resource.availability === "available",
);
// Fresh manifest and manual Apps import GitHub's initial choices. Saved
// repository selections and review configuration still belong to the user
// on recovery, while pre-saved review configuration before App install
// must not block importing the App installation's repositories.
const initializeApp =
!!session ||
bot.setup.github?.initialSetupPending === true ||
importPendingAfterRefresh;
const awaitingInitialRepositories =
initializeApp &&
importPendingAfterRefresh &&
!resources.some((resource) => resource.enabled);
if (awaitingInitialRepositories && availableResources.length > 0) {
await options.replaceResources(
id,
availableResources.map((resource) => ({ id: resource.id, enabled: true })),
userId,
{ initialGitHubImport: true, managementContext },
);
}
// Keep initial import pending when GitHub returns zero repositories so
// granting a repository on GitHub and retrying still imports it cleanly.
if (!awaitingInitialRepositories || availableResources.length > 0) {
if (initializeApp && saved.revision === 0 && bot.status !== "active")
await management.saveConfiguration(
id,
{
expectedRevision: 0,
configuration: {
...saved.configuration,
toolsEnabled: true,
defaults: {
...saved.configuration.defaults,
invocation: "mentions_only",
events: [],
},
},
},
userId,
managementContext,
);
await managementContext?.reauthorize();
await setup(bot, {
initialRepositoriesImported: true,
initialSetupPending: false,
});
}
}
await importInitialRepositories(bot, userId, !!session, managementContext);
// Installation callbacks can precede the separately delivered signed ping.
// Keep the same vaulted App in the wizard instead of throwing JSON from
// the browser callback or relaxing the configure action's signature gate.
@@ -990,16 +928,18 @@ export function githubChatWizardService(
await pollGitHubBotCloudSetupEvents(db);
bot = await endpoint(id, userId);
}
const installationUrl = safeGitHubAppInstallUrl(
bot.setup.github?.installationUrl,
);
const storedManagementUrl = safeGitHubInstallationManagementUrl(
bot.setup.github?.managementUrl,
);
if (!bot.setup.webhookVerifiedAt)
return {
endpointId: id,
state: "verify",
...(bot.setup.github?.installationUrl
? { installationUrl: bot.setup.github.installationUrl }
: {}),
...(bot.setup.github?.managementUrl
? { managementUrl: bot.setup.github.managementUrl }
: {}),
...(installationUrl ? { installationUrl } : {}),
...(storedManagementUrl ? { managementUrl: storedManagementUrl } : {}),
message: "Waiting for GitHub to verify webhook delivery…",
verification: {
ready: false,
@@ -1077,19 +1017,75 @@ export function githubChatWizardService(
if (connectionReady && bot.status !== "active")
await options.finish(id, userId, ...(managementContext ? [managementContext] : []));
const managementUrl =
verification.managementUrl ?? bot.setup.github?.managementUrl;
safeGitHubInstallationManagementUrl(verification.managementUrl) ??
safeGitHubInstallationManagementUrl(bot.setup.github?.managementUrl);
const verifiedInstallationUrl = safeGitHubAppInstallUrl(
bot.setup.github?.installationUrl,
);
return {
endpointId: id,
state: connectionReady ? "connected" : "verify",
identityLinked: true,
...(bot.setup.github?.installationUrl
? { installationUrl: bot.setup.github.installationUrl }
...(verifiedInstallationUrl
? { installationUrl: verifiedInstallationUrl }
: {}),
...(managementUrl ? { managementUrl } : {}),
verification: { ready: connectionReady, checks: connectionChecks },
runtimeChecks,
};
}
async function importInitialRepositories(
bot: Endpoint,
userId: string,
hasRegistrationSession: boolean,
managementContext?: ConnectionManagementContext,
) {
const resources = await options.resources(bot.id);
const decision = deriveGitHubInitialRepositoryImport(bot, resources, {
hasRegistrationSession,
});
if (decision.mode === "skip" || decision.mode === "await_repositories") {
return;
}
if (decision.mode === "import_and_complete") {
await options.replaceResources(
bot.id,
decision.resourceIdsToEnable.map((resourceId) => ({
id: resourceId,
enabled: true,
})),
userId,
{ initialGitHubImport: true, managementContext },
);
}
if (decision.initializeDefaultConfig) {
const saved = await management.configuration(bot.id, userId);
if (saved.revision === 0) {
await management.saveConfiguration(
bot.id,
{
expectedRevision: 0,
configuration: {
...saved.configuration,
toolsEnabled: true,
defaults: {
...saved.configuration.defaults,
invocation: "mentions_only",
events: [],
},
},
},
userId,
managementContext,
);
}
}
await managementContext?.reauthorize();
await setup(bot, {
initialRepositoriesImported: true,
initialSetupPending: false,
});
}
async function linkedIdentity(bot: Endpoint, userId: string) {
const [link] = await db
.select({ id: chatIdentityLinks.id })
@@ -309,7 +309,7 @@ describe("GitHubChatSetup verify UX", () => {
...baseEndpoint.setup,
github: {
...baseEndpoint.setup.github,
managementUrl: "https://evil.example/settings/installations/12345",
managementUrl: "https://github.com/organizations/acme/settings/installations/12345?next=https://evil.example",
},
},
});
+15 -32
View File
@@ -3,7 +3,12 @@ import { useEffect, useRef, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { AlertCircle, ExternalLink, Loader2 } from "lucide-react";
import type { GitHubAppWizardState, GitHubVerificationCheck } from "@paperclipai/shared";
import {
safeGitHubAppInstallUrl,
safeGitHubInstallationManagementUrl,
type GitHubAppWizardState,
type GitHubVerificationCheck,
} from "@paperclipai/shared";
import { agentsApi } from "@/api/agents";
import { chatEndpointsApi } from "@/api/chatEndpoints";
import { githubChatApi } from "@/api/githubChat";
@@ -46,29 +51,6 @@ export function gitHubAppManifestAction(
return url.toString();
}
function safeGitHubAppUrl(value: string | undefined): string | undefined {
if (!value) return undefined;
try {
const url = new URL(value);
if (
url.origin !== "https://github.com" ||
url.username ||
url.password ||
url.hash ||
!(
/^\/(?:settings|organizations\/[A-Za-z0-9-]+?\/settings)\/installations\/[1-9][0-9]*$/.test(
url.pathname,
) || /^\/apps\/[a-z0-9-]+\/installations\/new$/.test(url.pathname)
)
) {
return undefined;
}
return url.toString();
} catch {
return undefined;
}
}
function verifyIssueHeading(checks: GitHubVerificationCheck[]): string {
if (checks.length !== 1) return "Action needed to finish GitHub setup";
switch (checks[0]!.code) {
@@ -261,12 +243,13 @@ export function GitHubChatSetup() {
const checkingVerify =
state?.state === "verify" &&
(busy || (progress.isFetching && !waitingForWebhook));
const verifyGitHubManagementUrl = safeGitHubAppUrl(
state?.managementUrl ?? bot?.setup?.github?.managementUrl,
);
const verifyGitHubInstallUrl = safeGitHubAppUrl(
state?.installationUrl ?? bot?.setup?.github?.installationUrl,
);
const verifyGitHubManagementUrl =
safeGitHubInstallationManagementUrl(state?.managementUrl) ??
safeGitHubInstallationManagementUrl(bot?.setup?.github?.managementUrl);
const verifyGitHubInstallUrl =
safeGitHubAppInstallUrl(state?.installationUrl) ??
safeGitHubAppInstallUrl(bot?.setup?.github?.installationUrl);
const installStateGitHubUrl = safeGitHubAppInstallUrl(state?.installationUrl);
const needsInstallationOnly = failedVerifyChecks.some(
(check) => check.code === "installation_missing",
);
@@ -627,10 +610,10 @@ export function GitHubChatSetup() {
<p role="status" className="text-sm text-muted-foreground">
Waiting for GitHub installation or administrator approval…
</p>
{state.installationUrl && (
{installStateGitHubUrl && (
<a
className="inline-flex items-center gap-1 text-sm underline"
href={state.installationUrl} target="_blank" rel="noopener noreferrer"
href={installStateGitHubUrl} target="_blank" rel="noopener noreferrer"
>
Continue installation on GitHub
<ExternalLink className="size-3" />