Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

manage apps idenpendently

Thiago Araujo da Silvaae5acb1aae1a
diff --git a/backend/src/db/migrations/20260513120000_create-github-apps.ts b/backend/src/db/migrations/20260529204743_create-github-apps.ts
similarity index 52%
rename from backend/src/db/migrations/20260513120000_create-github-apps.ts
rename to backend/src/db/migrations/20260529204743_create-github-apps.ts
index 69068be719..eefdbccf25 100644
--- a/backend/src/db/migrations/20260513120000_create-github-apps.ts
+++ b/backend/src/db/migrations/20260529204743_create-github-apps.ts
@@ -10,20 +10,38 @@ export async function up(knex: Knex): Promise<void> {
t.uuid("orgId").notNullable();
t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
t.string("name").notNullable();
- t.binary("encryptedAppId").notNullable();
- t.binary("encryptedClientId").notNullable();
+ t.string("appId").notNullable();
+ t.string("clientId").notNullable();
t.binary("encryptedClientSecret").notNullable();
t.binary("encryptedPrivateKey").notNullable();
- t.binary("encryptedSlug").notNullable();
+ t.string("slug").notNullable();
+ t.string("owner").nullable();
t.timestamps(true, true, true);
- t.unique(["orgId", "name"]);
+ // GitHub app names are globally unique, so enforce uniqueness across all orgs
+ t.unique(["name"]);
});
await createOnUpdateTrigger(knex, TableName.GitHubApp);
}
+
+ if (!(await knex.schema.hasColumn(TableName.AppConnection, "gitHubAppId"))) {
+ await knex.schema.alterTable(TableName.AppConnection, (t) => {
+ t.uuid("gitHubAppId").nullable();
+ t.foreign("gitHubAppId").references("id").inTable(TableName.GitHubApp).onDelete("SET NULL");
+ t.index("gitHubAppId");
+ });
+ }
}
export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasColumn(TableName.AppConnection, "gitHubAppId")) {
+ await knex.schema.alterTable(TableName.AppConnection, (t) => {
+ t.dropForeign(["gitHubAppId"]);
+ t.dropIndex("gitHubAppId");
+ t.dropColumn("gitHubAppId");
+ });
+ }
+
await knex.schema.dropTableIfExists(TableName.GitHubApp);
await dropOnUpdateTrigger(knex, TableName.GitHubApp);
}
diff --git a/backend/src/db/schemas/app-connections.ts b/backend/src/db/schemas/app-connections.ts
index e27ece3b9c..cabcb6b93e 100644
--- a/backend/src/db/schemas/app-connections.ts
+++ b/backend/src/db/schemas/app-connections.ts
@@ -25,7 +25,8 @@ export const AppConnectionsSchema = z.object({
projectId: z.string().nullable().optional(),
isAutoRotationEnabled: z.boolean().default(false),
gatewayPoolId: z.string().uuid().nullable().optional(),
- encryptedConfiguration: zodBuffer.nullable().optional()
+ encryptedConfiguration: zodBuffer.nullable().optional(),
+ gitHubAppId: z.string().uuid().nullable().optional()
});
export type TAppConnections = z.infer<typeof AppConnectionsSchema>;
diff --git a/backend/src/db/schemas/github-apps.ts b/backend/src/db/schemas/github-apps.ts
index 9c4d1d7edd..c6c8e2c1a9 100644
--- a/backend/src/db/schemas/github-apps.ts
+++ b/backend/src/db/schemas/github-apps.ts
@@ -13,11 +13,12 @@ export const GithubAppsSchema = z.object({
id: z.string().uuid(),
orgId: z.string().uuid(),
name: z.string(),
- encryptedAppId: zodBuffer,
- encryptedClientId: zodBuffer,
+ appId: z.string(),
+ clientId: z.string(),
encryptedClientSecret: zodBuffer,
encryptedPrivateKey: zodBuffer,
- encryptedSlug: zodBuffer,
+ slug: z.string(),
+ owner: z.string().nullable().optional(),
createdAt: z.date(),
updatedAt: z.date()
});
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 16c46d8499..6205611223 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1032,6 +1032,7 @@ export const registerRoutes = async (
const gitHubAppService = gitHubAppServiceFactory({
gitHubAppDAL,
+ appConnectionDAL,
permissionService,
kmsService
});
diff --git a/backend/src/server/routes/v1/github-app-router.ts b/backend/src/server/routes/v1/github-app-router.ts
index 4f5a458768..b36629400e 100644
--- a/backend/src/server/routes/v1/github-app-router.ts
+++ b/backend/src/server/routes/v1/github-app-router.ts
@@ -10,6 +10,8 @@ const SanitizedGitHubAppSchema = z.object({
name: z.string(),
appId: z.string(),
slug: z.string(),
+ owner: z.string().nullable(),
+ connectionCount: z.number(),
createdAt: z.date().nullable(),
updatedAt: z.date().nullable()
});
diff --git a/backend/src/services/app-connection/app-connection-dal.ts b/backend/src/services/app-connection/app-connection-dal.ts
index 0135ad7fa0..5926896c0e 100644
--- a/backend/src/services/app-connection/app-connection-dal.ts
+++ b/backend/src/services/app-connection/app-connection-dal.ts
@@ -203,6 +203,23 @@ export const appConnectionDALFactory = (db: TDbClient) => {
return parseInt(String(result?.count || "0"), 10);
};
+ // Counts GitHub App method connections per referenced GitHub App. The null bucket corresponds
+ // to connections using the instance-default (shared) GitHub App.
+ const countByGitHubApp = async (orgId: string, tx?: Knex) => {
+ const rows = await (tx || db.replicaNode())(TableName.AppConnection)
+ .where(`${TableName.AppConnection}.orgId`, orgId)
+ .andWhere(`${TableName.AppConnection}.app`, "github")
+ .andWhere(`${TableName.AppConnection}.method`, "github-app")
+ .groupBy(`${TableName.AppConnection}.gitHubAppId`)
+ .select(db.ref("gitHubAppId").withSchema(TableName.AppConnection))
+ .count("id");
+
+ return rows.map((row) => ({
+ gitHubAppId: (row as { gitHubAppId: string | null }).gitHubAppId,
+ count: parseInt(String(row.count || "0"), 10)
+ }));
+ };
+
return {
...appConnectionOrm,
findAppConnectionUsageById,
@@ -210,6 +227,7 @@ export const appConnectionDALFactory = (db: TDbClient) => {
findByGatewayId,
countByGatewayId,
findByGatewayPoolId,
- countByGatewayPoolId
+ countByGatewayPoolId,
+ countByGitHubApp
};
};
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index 006d0ce152..3400ddc4bd 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -266,6 +266,17 @@ const VALIDATE_APP_CONNECTION_CREDENTIALS_MAP: Record<AppConnection, TValidateAp
[AppConnection.F5BigIp]: ValidateF5BigIpConnectionCredentialsSchema
};
+// Extracts the GitHub App reference to persist in the queryable app_connections.gitHubAppId column.
+// Only GitHub App method connections reference a custom app; null means the instance-default (shared) app.
+const resolveGitHubAppIdColumn = (
+ app: AppConnection,
+ method: string,
+ credentials: TAppConnection["credentials"] | undefined
+): string | null => {
+ if (app !== AppConnection.GitHub || method !== GitHubConnectionMethod.App) return null;
+ return (credentials as { gitHubAppId?: string | null } | undefined)?.gitHubAppId ?? null;
+};
+
export const appConnectionServiceFactory = ({
appConnectionDAL,
permissionService,
@@ -549,6 +560,10 @@ export const appConnectionServiceFactory = ({
{ identityUaDAL, gitHubAppDAL, kmsService }
);
+ // For GitHub App connections we mirror the referenced GitHub App into a queryable FK column so
+ // we can count/enforce reuse without decrypting credentials. Null = instance-default (shared) app.
+ const gitHubAppId = resolveGitHubAppIdColumn(app, method, validatedCredentials);
+
try {
const createConnection = async (connectionCredentials: TAppConnection["credentials"]) => {
return appConnectionDAL.transaction(async (tx) => {
@@ -573,6 +588,7 @@ export const appConnectionServiceFactory = ({
encryptedConfiguration,
method,
app,
+ gitHubAppId,
gatewayId: gatewayPoolId ? null : gatewayId,
gatewayPoolId: gatewayPoolId ?? null,
projectId,
@@ -806,11 +822,17 @@ export const appConnectionServiceFactory = ({
})
: undefined;
+ // Keep the queryable GitHub App FK in sync whenever credentials are re-validated on update.
+ const gitHubAppIdUpdate = updatedCredentials
+ ? { gitHubAppId: resolveGitHubAppIdColumn(app, method, updatedCredentials) }
+ : {};
+
return appConnectionDAL.updateById(
connectionId,
{
orgId: actor.orgId,
encryptedCredentials,
+ ...gitHubAppIdUpdate,
...(encryptedConfiguration !== undefined && { encryptedConfiguration }),
...(gatewayIdValue !== undefined && { gatewayId: gatewayIdValue }),
...(gatewayPoolIdValue !== undefined && { gatewayPoolId: gatewayPoolIdValue }),
@@ -966,13 +988,12 @@ export const appConnectionServiceFactory = ({
// TODO (scott): add option to delete all dependencies
- let dedicatedGitHubAppId: string | null = null;
-
if (app === AppConnection.GitHub) {
const decrypted = await decryptAppConnection(appConnection, kmsService);
if (decrypted.method === GitHubConnectionMethod.App) {
- // Best-effort uninstall on GitHub. Failures don't block local deletion — the user can
- // always remove the installation manually if our cleanup couldn't reach GitHub.
+ // Best-effort uninstall of THIS connection's installation on GitHub. Failures don't block
+ // local deletion — the user can always remove the installation manually. The underlying
+ // GitHub App is reusable and intentionally left intact; it's managed separately.
try {
await uninstallGitHubAppInstallation(decrypted, gatewayService, gatewayV2Service, gatewayPoolService, {
gitHubAppDAL,
@@ -984,26 +1005,12 @@ export const appConnectionServiceFactory = ({
`Failed to uninstall GitHub App for connection [connectionId=${connectionId}]`
);
}
- dedicatedGitHubAppId = decrypted.credentials.gitHubAppId ?? null;
}
}
try {
const deletedAppConnection = await appConnectionDAL.deleteById(connectionId);
- // For dedicated GitHub Apps, drop the encrypted app record now that no connection refers
- // to it. Best-effort: the connection is already deleted, and an orphaned row is recoverable.
- if (dedicatedGitHubAppId) {
- try {
- await gitHubAppDAL.deleteById(dedicatedGitHubAppId);
- } catch (err) {
- logger.warn(
- { err, gitHubAppId: dedicatedGitHubAppId, connectionId },
- `Failed to delete dedicated GitHub App row [gitHubAppId=${dedicatedGitHubAppId}]`
- );
- }
- }
-
return await decryptAppConnection(deletedAppConnection, kmsService);
} catch (err) {
if (
diff --git a/backend/src/services/app-connection/github/github-connection-fns.ts b/backend/src/services/app-connection/github/github-connection-fns.ts
index 60c0c07c59..7babcc74ca 100644
--- a/backend/src/services/app-connection/github/github-connection-fns.ts
+++ b/backend/src/services/app-connection/github/github-connection-fns.ts
@@ -60,9 +60,9 @@ export const resolveGitHubAppCredentials = async (
});
return {
- appId: decryptor({ cipherTextBlob: app.encryptedAppId }).toString(),
- slug: decryptor({ cipherTextBlob: app.encryptedSlug }).toString(),
- clientId: decryptor({ cipherTextBlob: app.encryptedClientId }).toString(),
+ appId: app.appId,
+ slug: app.slug,
+ clientId: app.clientId,
clientSecret: decryptor({ cipherTextBlob: app.encryptedClientSecret }).toString(),
privateKey: decryptor({ cipherTextBlob: app.encryptedPrivateKey }).toString()
};
diff --git a/backend/src/services/github-app/github-app-service.ts b/backend/src/services/github-app/github-app-service.ts
index e61941f925..33ddb861c3 100644
--- a/backend/src/services/github-app/github-app-service.ts
+++ b/backend/src/services/github-app/github-app-service.ts
@@ -9,6 +9,7 @@ import { request } from "@app/lib/config/request";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
@@ -27,6 +28,7 @@ import {
type TGitHubAppServiceFactoryDep = {
gitHubAppDAL: TGitHubAppDALFactory;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "countByGitHubApp">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
};
@@ -35,6 +37,7 @@ export type TGitHubAppServiceFactory = ReturnType<typeof gitHubAppServiceFactory
export const gitHubAppServiceFactory = ({
gitHubAppDAL,
+ appConnectionDAL,
permissionService,
kmsService
}: TGitHubAppServiceFactoryDep) => {
@@ -86,14 +89,17 @@ export const gitHubAppServiceFactory = ({
orgId: orgPermission.orgId
});
+ const owner = manifestResponse.owner?.login ?? null;
+
const created = await gitHubAppDAL.create({
orgId: orgPermission.orgId,
name,
- encryptedAppId: encryptor({ plainText: Buffer.from(String(manifestResponse.id)) }).cipherTextBlob,
- encryptedClientId: encryptor({ plainText: Buffer.from(manifestResponse.client_id) }).cipherTextBlob,
+ appId: String(manifestResponse.id),
+ clientId: manifestResponse.client_id,
encryptedClientSecret: encryptor({ plainText: Buffer.from(manifestResponse.client_secret) }).cipherTextBlob,
encryptedPrivateKey: encryptor({ plainText: Buffer.from(manifestResponse.pem) }).cipherTextBlob,
- encryptedSlug: encryptor({ plainText: Buffer.from(manifestResponse.slug) }).cipherTextBlob
+ slug: manifestResponse.slug,
+ owner
});
return {
@@ -102,6 +108,8 @@ export const gitHubAppServiceFactory = ({
name: created.name,
appId: String(manifestResponse.id),
slug: manifestResponse.slug,
+ owner,
+ connectionCount: 0,
createdAt: created.createdAt,
updatedAt: created.updatedAt
};
@@ -121,25 +129,20 @@ export const gitHubAppServiceFactory = ({
const apps = await gitHubAppDAL.find({ orgId: orgPermission.orgId });
- const dbApps: TSanitizedGitHubApp[] = [];
- if (apps.length > 0) {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId: orgPermission.orgId
- });
-
- for (const app of apps) {
- dbApps.push({
- id: app.id,
- orgId: app.orgId,
- name: app.name,
- appId: decryptor({ cipherTextBlob: app.encryptedAppId }).toString(),
- slug: decryptor({ cipherTextBlob: app.encryptedSlug }).toString(),
- createdAt: app.createdAt,
- updatedAt: app.updatedAt
- });
- }
- }
+ const connectionCounts = await appConnectionDAL.countByGitHubApp(orgPermission.orgId);
+ const countByAppId = new Map(connectionCounts.map(({ gitHubAppId, count }) => [gitHubAppId, count]));
+
+ const dbApps: TSanitizedGitHubApp[] = apps.map((app) => ({
+ id: app.id,
+ orgId: app.orgId,
+ name: app.name,
+ appId: app.appId,
+ slug: app.slug,
+ owner: app.owner ?? null,
+ connectionCount: countByAppId.get(app.id) ?? 0,
+ createdAt: app.createdAt,
+ updatedAt: app.updatedAt
+ }));
const { INF_APP_CONNECTION_GITHUB_APP_ID, INF_APP_CONNECTION_GITHUB_APP_SLUG } = getConfig();
@@ -151,6 +154,9 @@ export const gitHubAppServiceFactory = ({
name: INF_APP_CONNECTION_GITHUB_APP_SLUG,
appId: INF_APP_CONNECTION_GITHUB_APP_ID,
slug: INF_APP_CONNECTION_GITHUB_APP_SLUG,
+ owner: null,
+ // connections referencing the instance-default app store a null gitHubAppId
+ connectionCount: countByAppId.get(null) ?? 0,
createdAt: null,
updatedAt: null
}
@@ -176,17 +182,25 @@ export const gitHubAppServiceFactory = ({
throw new NotFoundError({ message: `GitHub App with id ${id} not found in this organization.` });
}
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId: orgPermission.orgId
- });
+ const connectionCounts = await appConnectionDAL.countByGitHubApp(orgPermission.orgId);
+ const connectionCount = connectionCounts.find(({ gitHubAppId }) => gitHubAppId === existing.id)?.count ?? 0;
+
+ if (connectionCount > 0) {
+ throw new BadRequestError({
+ message: `Cannot delete GitHub App "${existing.name}" while it is in use by ${connectionCount} connection${
+ connectionCount === 1 ? "" : "s"
+ }. Remove those connections first.`
+ });
+ }
const sanitized: TSanitizedGitHubApp = {
id: existing.id,
orgId: existing.orgId,
name: existing.name,
- appId: decryptor({ cipherTextBlob: existing.encryptedAppId }).toString(),
- slug: decryptor({ cipherTextBlob: existing.encryptedSlug }).toString(),
+ appId: existing.appId,
+ slug: existing.slug,
+ owner: existing.owner ?? null,
+ connectionCount: 0,
createdAt: existing.createdAt,
updatedAt: existing.updatedAt
};
@@ -231,11 +245,11 @@ export const gitHubAppServiceFactory = ({
const created = await gitHubAppDAL.create({
orgId: orgPermission.orgId,
name,
- encryptedAppId: encryptor({ plainText: Buffer.from(appId) }).cipherTextBlob,
- encryptedClientId: encryptor({ plainText: Buffer.from(clientId) }).cipherTextBlob,
+ appId,
+ clientId,
encryptedClientSecret: encryptor({ plainText: Buffer.from(clientSecret) }).cipherTextBlob,
encryptedPrivateKey: encryptor({ plainText: Buffer.from(privateKey) }).cipherTextBlob,
- encryptedSlug: encryptor({ plainText: Buffer.from(slug) }).cipherTextBlob
+ slug
});
return {
@@ -244,6 +258,8 @@ export const gitHubAppServiceFactory = ({
name: created.name,
appId,
slug,
+ owner: null,
+ connectionCount: 0,
createdAt: created.createdAt,
updatedAt: created.updatedAt
};
@@ -342,7 +358,8 @@ export const gitHubAppServiceFactory = ({
throw new BadRequestError({ message: "Invalid or expired GitHub manifest state. Please try again." });
}
- const { orgId, actorId, actorType, authMethod, name, instanceType, githubHost, installState } = statePayload;
+ const { orgId, actorId, actorType, authMethod, name, instanceType, githubOrg, githubHost, installState } =
+ statePayload;
const { permission } = await permissionService.getOrgPermission({
actor: actorType as ActorType,
@@ -392,16 +409,19 @@ export const gitHubAppServiceFactory = ({
orgId
});
+ const owner = manifestResponse.owner?.login ?? (githubOrg || null);
+
let created: Awaited<ReturnType<typeof gitHubAppDAL.create>>;
try {
created = await gitHubAppDAL.create({
orgId,
name,
- encryptedAppId: encryptor({ plainText: Buffer.from(String(manifestResponse.id)) }).cipherTextBlob,
- encryptedClientId: encryptor({ plainText: Buffer.from(manifestResponse.client_id) }).cipherTextBlob,
+ appId: String(manifestResponse.id),
+ clientId: manifestResponse.client_id,
encryptedClientSecret: encryptor({ plainText: Buffer.from(manifestResponse.client_secret) }).cipherTextBlob,
encryptedPrivateKey: encryptor({ plainText: Buffer.from(manifestResponse.pem) }).cipherTextBlob,
- encryptedSlug: encryptor({ plainText: Buffer.from(manifestResponse.slug) }).cipherTextBlob
+ slug: manifestResponse.slug,
+ owner
});
} catch (err) {
if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
diff --git a/backend/src/services/github-app/github-app-types.ts b/backend/src/services/github-app/github-app-types.ts
index ce9f9d66f4..01434d3e6c 100644
--- a/backend/src/services/github-app/github-app-types.ts
+++ b/backend/src/services/github-app/github-app-types.ts
@@ -53,6 +53,9 @@ export type TGitHubAppManifestResponse = {
client_secret: string;
pem: string;
html_url: string;
+ owner?: {
+ login?: string;
+ } | null;
};
export type TSanitizedGitHubApp = {
@@ -61,6 +64,8 @@ export type TSanitizedGitHubApp = {
name: string;
appId: string;
slug: string;
+ owner: string | null;
+ connectionCount: number;
createdAt: Date | null;
updatedAt: Date | null;
};
diff --git a/frontend/src/hooks/api/gitHubApps/index.ts b/frontend/src/hooks/api/gitHubApps/index.ts
index 1a8b13edff..043f44f5fc 100644
--- a/frontend/src/hooks/api/gitHubApps/index.ts
+++ b/frontend/src/hooks/api/gitHubApps/index.ts
@@ -1,2 +1,3 @@
+export { useDeleteGitHubApp } from "./mutations";
export { gitHubAppKeys, useListGitHubApps } from "./queries";
export type { TGitHubApp } from "./types";
diff --git a/frontend/src/hooks/api/gitHubApps/mutations.tsx b/frontend/src/hooks/api/gitHubApps/mutations.tsx
new file mode 100644
index 0000000000..4d0ff58b50
--- /dev/null
+++ b/frontend/src/hooks/api/gitHubApps/mutations.tsx
@@ -0,0 +1,22 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { gitHubAppKeys } from "./queries";
+import { TGitHubApp } from "./types";
+
+export const useDeleteGitHubApp = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (id: string) => {
+ const { data } = await apiRequest.delete<{ gitHubApp: TGitHubApp }>(
+ `/api/v1/github-apps/${id}`
+ );
+ return data.gitHubApp;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: gitHubAppKeys.all });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/gitHubApps/types.ts b/frontend/src/hooks/api/gitHubApps/types.ts
index 90dc280c29..54a4f3b218 100644
--- a/frontend/src/hooks/api/gitHubApps/types.ts
+++ b/frontend/src/hooks/api/gitHubApps/types.ts
@@ -4,6 +4,8 @@ export type TGitHubApp = {
name: string;
appId: string;
slug: string;
+ owner: string | null;
+ connectionCount: number;
createdAt: string | null;
updatedAt: string | null;
};
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx
new file mode 100644
index 0000000000..4b3d1ec472
--- /dev/null
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx
@@ -0,0 +1,399 @@
+import { useLayoutEffect, useRef, useState } from "react";
+import { faGithub } from "@fortawesome/free-brands-svg-icons";
+import {
+ faArrowUpRightFromSquare,
+ faChevronLeft,
+ faCircleInfo,
+ faLock,
+ faPlus,
+ faTrash,
+ faTriangleExclamation
+} from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import slugify from "@sindresorhus/slugify";
+import { twMerge } from "tailwind-merge";
+
+import { createNotification } from "@app/components/notifications";
+import { Button, FormControl, Input } from "@app/components/v2";
+import {
+ Command,
+ CommandGroup,
+ CommandItem,
+ CommandList
+} from "@app/components/v3/generic/Command";
+import { TGitHubApp, useDeleteGitHubApp } from "@app/hooks/api/gitHubApps";
+
+const SHARED_KEY = "__shared__";
+
+// New GitHub Apps are pre-filled with this prefix so they're easy to identify in the GitHub account.
+const GITHUB_APP_NAME_PREFIX = "infisical-";
+
+const getAppKey = (app: TGitHubApp | null) => (app ? (app.id ?? SHARED_KEY) : null);
+
+const buildAppUrl = (app: TGitHubApp, host?: string, instanceType?: "cloud" | "server") => {
+ const resolvedHost =
+ host && host.trim().length > 0 ? `https://${host.trim()}` : "https://github.com";
+ const segment = instanceType === "server" ? "github-apps" : "apps";
+ return `${resolvedHost}/${segment}/${app.slug}`;
+};
+
+type Props = {
+ apps: TGitHubApp[];
+ isLoading: boolean;
+ value: TGitHubApp | null;
+ onChange: (app: TGitHubApp | null) => void;
+ host?: string;
+ instanceType?: "cloud" | "server";
+ // Kicks off the GitHub App manifest creation flow on the parent form (redirects to GitHub).
+ // Returns false when the parent form is invalid so we can return to the list view.
+ onCreateApp: (params: { name: string; githubOrg: string }) => Promise<boolean> | void;
+ isCreating?: boolean;
+};
+
+export const GitHubAppSelector = ({
+ apps,
+ isLoading,
+ value,
+ onChange,
+ host,
+ instanceType,
+ onCreateApp,
+ isCreating
+}: Props) => {
+ const [mode, setMode] = useState<"list" | "create">("list");
+ const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
+ const [newAppName, setNewAppName] = useState("");
+ const [newAppOrg, setNewAppOrg] = useState("");
+ const containerRef = useRef<HTMLDivElement>(null);
+ const nameInputRef = useRef<HTMLInputElement>(null);
+
+ // Toggling `mode` unmounts the focused button (e.g. "Create new GitHub App"). If focus dropped to
+ // <body>, the Dialog's focus trap would yank it to the first field at the top of the modal and
+ // scroll up. Park focus on the always-mounted panel first so the trap never reacts.
+ const switchMode = (next: "list" | "create") => {
+ containerRef.current?.focus({ preventScroll: true });
+ setMode(next);
+ };
+
+ // Once the create view is mounted, move focus to its first field (without scrolling).
+ useLayoutEffect(() => {
+ if (mode === "create") nameInputRef.current?.focus({ preventScroll: true });
+ }, [mode]);
+
+ const deleteGitHubApp = useDeleteGitHubApp();
+
+ const sharedApp = apps.find((app) => app.id === null) ?? null;
+ const customApps = apps.filter((app) => app.id !== null);
+
+ const resetCreate = () => {
+ switchMode("list");
+ setNewAppName("");
+ setNewAppOrg("");
+ };
+
+ const handleSelect = (app: TGitHubApp) => {
+ onChange(app);
+ };
+
+ const handleDelete = async (app: TGitHubApp) => {
+ if (!app.id) return;
+ try {
+ await deleteGitHubApp.mutateAsync(app.id);
+ createNotification({ type: "success", text: `Deleted GitHub App "${app.name}"` });
+ if (getAppKey(value) === app.id) onChange(null);
+ setDeleteTargetId(null);
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to delete GitHub App"
+ });
+ }
+ };
+
+ const handleContinueCreate = async () => {
+ if (!newAppName.trim()) return;
+ const didRedirect = await onCreateApp({
+ // Send the same slugified name shown in the URL preview so it matches GitHub's app slug.
+ name: `${GITHUB_APP_NAME_PREFIX}${slugify(newAppName, { lowercase: true })}`,
+ githubOrg: newAppOrg.trim()
+ });
+ // When the parent form is invalid the redirect is aborted; return to the list view.
+ if (didRedirect === false) {
+ resetCreate();
+ }
+ };
+
+ const renderCustomAppRow = (app: TGitHubApp) => {
+ const isInUse = app.connectionCount > 0;
+
+ if (deleteTargetId === app.id) {
+ if (isInUse) {
+ return (
+ <div
+ key={app.id}
+ className="m-1 rounded-md border border-yellow-500/40 bg-yellow-500/5 p-3"
+ >
+ <div className="flex items-center gap-2 text-sm font-medium text-mineshaft-100">
+ <FontAwesomeIcon icon={faTriangleExclamation} className="text-yellow-500" />
+ <span>
+ Can&apos;t delete <span className="font-mono">{app.name}</span>
+ </span>
+ </div>
+ <p className="mt-1 text-xs leading-relaxed text-mineshaft-300">
+ In use by {app.connectionCount} connection{app.connectionCount === 1 ? "" : "s"}.
+ Remove the connection{app.connectionCount === 1 ? "" : "s"} before deleting this app.
+ </p>
+ <div className="mt-3 flex items-center justify-end gap-2">
+ <Button
+ variant="plain"
+ colorSchema="secondary"
+ size="xs"
+ onClick={() => setDeleteTargetId(null)}
+ >
+ Cancel
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div key={app.id} className="m-1 rounded-md border border-red-500/40 bg-red-500/5 p-3">
+ <div className="flex items-center gap-2 text-sm font-medium text-mineshaft-100">
+ <FontAwesomeIcon icon={faTrash} className="text-red-400" />
+ <span>
+ Delete <span className="font-mono">{app.name}</span>?
+ </span>
+ </div>
+ <p className="mt-1 text-xs leading-relaxed text-mineshaft-300">
+ Removes it from Infisical. The app still exists on GitHub until you uninstall it there.
+ </p>
+ <div className="mt-3 flex items-center justify-end gap-2">
+ <Button
+ variant="plain"
+ colorSchema="secondary"
+ size="xs"
+ onClick={() => setDeleteTargetId(null)}
+ >
+ Cancel
+ </Button>
+ <Button
+ colorSchema="danger"
+ size="xs"
+ isLoading={deleteGitHubApp.isPending}
+ onClick={() => handleDelete(app)}
+ >
+ Delete
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <CommandItem
+ key={app.id}
+ value={`${app.name} ${app.owner ?? ""} ${app.slug}`}
+ onSelect={() => handleSelect(app)}
+ className={twMerge(
+ "group",
+ getAppKey(value) === app.id &&
+ "bg-primary/5 ring-1 ring-primary/40 ring-inset data-[selected=true]:bg-primary/10"
+ )}
+ >
+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-sm bg-mineshaft-600 text-mineshaft-100">
+ <FontAwesomeIcon icon={faGithub} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="truncate font-mono text-sm text-mineshaft-100">{app.name}</p>
+ <p className="truncate text-xs text-mineshaft-400">
+ {app.owner ? `${app.owner} · ` : ""}
+ {app.connectionCount} connection{app.connectionCount === 1 ? "" : "s"}
+ </p>
+ </div>
+ <div className="flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100 data-[selected=true]:opacity-100">
+ <button
+ type="button"
+ title="Open in GitHub"
+ className="rounded p-1 text-mineshaft-300 hover:bg-mineshaft-600 hover:text-mineshaft-100"
+ onClick={(e) => {
+ e.stopPropagation();
+ window.open(buildAppUrl(app, host, instanceType), "_blank", "noopener,noreferrer");
+ }}
+ >
+ <FontAwesomeIcon icon={faArrowUpRightFromSquare} className="text-xs" />
+ </button>
+ <button
+ type="button"
+ title="Delete"
+ className="rounded p-1 text-mineshaft-300 hover:bg-mineshaft-600 hover:text-red-400"
+ onClick={(e) => {
+ e.stopPropagation();
+ setDeleteTargetId(app.id);
+ }}
+ >
+ <FontAwesomeIcon icon={faTrash} className="text-xs" />
+ </button>
+ </div>
+ </CommandItem>
+ );
+ };
+
+ return (
+ <div
+ ref={containerRef}
+ tabIndex={-1}
+ className="overflow-hidden rounded-md border border-mineshaft-600 bg-mineshaft-900 outline-none"
+ >
+ {mode === "create" ? (
+ <div className="p-3">
+ <div className="mb-3 flex items-center gap-2 border-b border-mineshaft-600 pb-2 text-sm font-medium text-mineshaft-100">
+ <button
+ type="button"
+ className="rounded p-1 text-mineshaft-300 hover:bg-mineshaft-600 hover:text-mineshaft-100"
+ onClick={resetCreate}
+ >
+ <FontAwesomeIcon icon={faChevronLeft} className="text-xs" />
+ </button>
+ Create GitHub App
+ </div>
+ <FormControl
+ label="App name"
+ className="mb-1"
+ helperText={
+ <>
+ github.com/apps/
+ <span className="font-mono text-mineshaft-200">
+ {GITHUB_APP_NAME_PREFIX}
+ {newAppName.trim() ? slugify(newAppName, { lowercase: true }) : "your-app"}
+ </span>
+ </>
+ }
+ >
+ <Input
+ ref={nameInputRef}
+ value={newAppName}
+ onChange={(e) => setNewAppName(e.target.value)}
+ placeholder="deploy-bot"
+ className="font-mono"
+ />
+ </FormControl>
+ <FormControl label="GitHub account / org" isOptional className="mt-3 mb-0">
+ <Input
+ value={newAppOrg}
+ onChange={(e) => setNewAppOrg(e.target.value)}
+ placeholder="Leave blank for your personal account"
+ />
+ </FormControl>
+ <div className="mt-3 flex items-start gap-2 rounded-md border border-mineshaft-500 bg-mineshaft-700/40 px-3 py-2.5 text-xs leading-relaxed text-mineshaft-300">
+ <FontAwesomeIcon icon={faCircleInfo} className="mt-0.5 text-mineshaft-400" />
+ You&apos;ll be redirected to GitHub to install the app and grant repository access. It
+ appears here as soon as you return.
+ </div>
+ <div className="mt-3 flex items-center justify-end gap-2">
+ <Button variant="plain" colorSchema="secondary" size="xs" onClick={resetCreate}>
+ Cancel
+ </Button>
+ <Button
+ colorSchema="secondary"
+ size="xs"
+ isDisabled={!newAppName.trim() || isCreating}
+ isLoading={isCreating}
+ leftIcon={<FontAwesomeIcon icon={faGithub} />}
+ onClick={handleContinueCreate}
+ >
+ Continue on GitHub
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <>
+ <Command className="bg-transparent">
+ <CommandList className="max-h-[360px]">
+ {sharedApp && (
+ <CommandGroup heading="SHARED">
+ <CommandItem
+ value={`instance-default ${sharedApp.name}`}
+ onSelect={() => handleSelect(sharedApp)}
+ className={twMerge(
+ "group",
+ getAppKey(value) === SHARED_KEY &&
+ "bg-primary/5 ring-1 ring-primary/40 ring-inset data-[selected=true]:bg-primary/10"
+ )}
+ >
+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-sm bg-blue-500/15 text-blue-400">
+ <FontAwesomeIcon icon={faLock} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium text-mineshaft-100">
+ Instance default
+ </p>
+ <p className="truncate text-xs text-mineshaft-400">
+ Configured by instance admin
+ </p>
+ </div>
+ <div className="flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100 data-[selected=true]:opacity-100">
+ <button
+ type="button"
+ title="Open in GitHub"
+ className="rounded p-1 text-mineshaft-300 hover:bg-mineshaft-600 hover:text-mineshaft-100"
+ onClick={(e) => {
+ e.stopPropagation();
+ window.open(
+ buildAppUrl(sharedApp, host, instanceType),
+ "_blank",
+ "noopener,noreferrer"
+ );
+ }}
+ >
+ <FontAwesomeIcon icon={faArrowUpRightFromSquare} className="text-xs" />
+ </button>
+ </div>
+ </CommandItem>
+ </CommandGroup>
+ )}
+ <CommandGroup
+ heading={
+ <span className="flex items-center gap-2">
+ CUSTOM APPS
+ {customApps.length > 0 && (
+ <span className="rounded-full bg-mineshaft-600 px-1.5 text-[10px] text-mineshaft-200">
+ {customApps.length}
+ </span>
+ )}
+ </span>
+ }
+ >
+ {customApps.length === 0 && !isLoading ? (
+ <div className="flex flex-col items-center gap-2 px-4 py-6 text-center">
+ <div className="flex h-12 w-12 items-center justify-center rounded-md bg-mineshaft-600 text-xl text-mineshaft-300">
+ <FontAwesomeIcon icon={faGithub} />
+ </div>
+ <p className="text-sm font-medium text-mineshaft-100">No custom apps yet</p>
+ <p className="max-w-[260px] text-xs leading-relaxed text-mineshaft-400">
+ Create a dedicated GitHub App for tighter, per-team permission scoping.
+ </p>
+ </div>
+ ) : (
+ customApps.map((app) => renderCustomAppRow(app))
+ )}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ <button
+ type="button"
+ onClick={() => switchMode("create")}
+ className="group flex w-full items-center gap-2.5 border-t border-mineshaft-600 px-3 py-2.5 text-left hover:bg-foreground/5"
+ >
+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-sm border border-mineshaft-500 text-mineshaft-200">
+ <FontAwesomeIcon icon={faPlus} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-mineshaft-100">Create new GitHub App</p>
+ </div>
+ </button>
+ </>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
index 84573e29d4..ff89a70c52 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
@@ -1,11 +1,9 @@
import { useEffect, useState } from "react";
import { Controller, FormProvider, useForm } from "react-hook-form";
-import { faGithub } from "@fortawesome/free-brands-svg-icons";
-import { faCheck, faPlus } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
+import { createNotification } from "@app/components/notifications";
import { OrgPermissionCan } from "@app/components/permissions";
import {
Accordion,
@@ -21,10 +19,9 @@ import {
SelectItem,
Tooltip
} from "@app/components/v2";
-import { Badge } from "@app/components/v3/generic/Badge";
import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";
import { apiRequest } from "@app/config/request";
-import { useSubscription } from "@app/context";
+import { useOrganization, useSubscription } from "@app/context";
import {
OrgGatewayPermissionActions,
OrgPermissionSubjects
@@ -41,12 +38,14 @@ import {
useGetAppConnectionOption
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { TGitHubApp, useListGitHubApps } from "@app/hooks/api/gitHubApps";
import { GitHubFormData } from "../../../OauthCallbackPage/OauthCallbackPage.types";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
} from "./GenericAppConnectionFields";
+import { GitHubAppSelector } from "./GitHubAppSelector";
type Props = {
appConnection?: TGitHubConnection;
@@ -54,8 +53,6 @@ type Props = {
onSubmit: (formData: PatSchemaForm) => Promise<void>;
};
-type GitHubAppSource = "shared" | "dedicated";
-
const rootSchema = genericAppConnectionFieldsSchema.extend({
app: z.literal(AppConnection.GitHub),
method: z.nativeEnum(GitHubConnectionMethod)
@@ -98,70 +95,29 @@ const patSchema = rootSchema.extend({
])
});
+const GITHUB_CONNECTION_FORM_KEY = "githubConnectionFormData";
+
type PatSchemaForm = z.infer<typeof patSchema>;
const formSchema = z.discriminatedUnion("method", [appSchema, oauthSchema, patSchema]);
type FormData = z.infer<typeof formSchema>;
-const slugifyConnectionName = (name: string) =>
- name
- .trim()
- .toLowerCase()
- .replace(/\s+/g, "-")
- .replace(/[^a-z0-9-]/g, "")
- .replace(/-+/g, "-")
- .replace(/^-|-$/g, "");
-
-const buildDedicatedAppSlug = (connectionName: string) => {
- const slug = slugifyConnectionName(connectionName || "");
- return `infisical-${slug}`;
-};
-
-type AppSourceCardProps = {
- title: string;
- description: string;
- icon: React.ReactNode;
- selected: boolean;
- onClick: () => void;
-};
-
-const AppSourceCard = ({ title, description, icon, selected, onClick }: AppSourceCardProps) => (
- <button
- type="button"
- onClick={onClick}
- className={`relative flex h-full flex-col items-start gap-2 rounded-md border p-3 text-left transition-all ${
- selected
- ? "border-primary/60 bg-primary/10"
- : "border-mineshaft-500 bg-mineshaft-700/30 hover:border-mineshaft-400 hover:bg-mineshaft-700/60"
- }`}
- >
- {selected && (
- <div className="absolute top-2 right-2 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-mineshaft-900">
- <FontAwesomeIcon icon={faCheck} className="text-[8px]" />
- </div>
- )}
- <div className="flex items-center gap-2">
- <div className="flex h-7 w-7 items-center justify-center rounded-sm bg-mineshaft-600 text-mineshaft-100">
- {icon}
- </div>
- <div className="flex flex-wrap items-center gap-1.5">
- <span className="text-sm font-medium text-mineshaft-100">{title}</span>
- </div>
- </div>
- <p className="text-xs leading-relaxed text-mineshaft-300">{description}</p>
- </button>
-);
-
export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
+ const { currentOrg } = useOrganization();
+
const {
option: { oauthClientId, appClientSlug },
isLoading
} = useGetAppConnectionOption(AppConnection.GitHub);
+ const { data: gitHubApps = [], isPending: isGitHubAppsLoading } = useListGitHubApps(
+ currentOrg?.id
+ );
+
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: appConnection ?? {
@@ -189,87 +145,183 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro
const instanceType = watch("credentials.instanceType");
const gatewayId = watch("gatewayId");
const gatewayPoolId = watch("gatewayPoolId");
- const connectionName = watch("name") ?? "";
-
- // Dedicated is the recommended default for new connections; update flow is reconnect-only
- // and uses the instance-default app since the dedicated app slug lives in the DB.
- const [appSource, setAppSource] = useState<GitHubAppSource>(isUpdate ? "shared" : "dedicated");
- const [dedicatedAppOrg, setDedicatedAppOrg] = useState("");
-
- useEffect(() => {
- if (isUpdate) setAppSource("shared");
- }, [isUpdate]);
const returnUrl = useGetAppConnectionOauthReturnUrl();
- const dedicatedAppSlug = buildDedicatedAppSlug(connectionName);
+ const sharedApp = gitHubApps.find((app) => app.id === null) ?? null;
- const submitHandler = async (formData: FormData) => {
- if (formData.method === GitHubConnectionMethod.Pat) {
- await onSubmit(formData);
- return;
+ // For new App-method connections the user picks which GitHub App to install. Default to the
+ // instance-default (shared) app when one is configured.
+ const [selectedGitHubApp, setSelectedGitHubApp] = useState<TGitHubApp | null>(null);
+ // After returning from the "Create new GitHub App" flow, the app to auto-select once it loads.
+ const [pendingGitHubAppId, setPendingGitHubAppId] = useState<string | null>(null);
+ // The form is restored (not edited) after resuming, so `isDirty` stays false — track this to keep
+ // the Connect button enabled.
+ const [isResumed, setIsResumed] = useState(false);
+
+ // When we come back from creating a new GitHub App, restore the in-progress form and remember the
+ // new app so we can select it. The connection itself is created later when the user hits Connect.
+ useEffect(() => {
+ if (isUpdate) return;
+ try {
+ const raw = localStorage.getItem(GITHUB_CONNECTION_FORM_KEY);
+ if (!raw) return;
+ const stored = JSON.parse(raw) as {
+ method?: GitHubConnectionMethod;
+ name?: string;
+ description?: string | null;
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ credentials?: { instanceType?: "cloud" | "server"; host?: string };
+ resumeWithGitHubAppId?: string;
+ };
+ if (!stored.resumeWithGitHubAppId) return;
+
+ form.reset({
+ app: AppConnection.GitHub,
+ method: stored.method ?? GitHubConnectionMethod.App,
+ gatewayId: stored.gatewayId ?? null,
+ gatewayPoolId: stored.gatewayPoolId ?? null,
+ name: stored.name ?? "",
+ description: stored.description ?? null,
+ credentials: {
+ instanceType: stored.credentials?.instanceType ?? "cloud",
+ ...(stored.credentials?.host ? { host: stored.credentials.host } : {})
+ }
+ } as FormData);
+ setPendingGitHubAppId(stored.resumeWithGitHubAppId);
+ setIsResumed(true);
+ } catch {
+ // ignore malformed state
+ } finally {
+ localStorage.removeItem(GITHUB_CONNECTION_FORM_KEY);
}
+ // run once on mount
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
- setIsRedirecting(true);
+ // Resolve the pending (newly created) app to the loaded list, then select it.
+ useEffect(() => {
+ if (!pendingGitHubAppId) return;
+ const match = gitHubApps.find((app) => app.id === pendingGitHubAppId);
+ if (match) {
+ setSelectedGitHubApp(match);
+ setPendingGitHubAppId(null);
+ }
+ }, [pendingGitHubAppId, gitHubApps]);
- // generate install state here so the OAuth callback can validate it
- const installState = Array.from(crypto.getRandomValues(new Uint8Array(16)))
+ useEffect(() => {
+ if (isUpdate || selectedGitHubApp || pendingGitHubAppId || !sharedApp) return;
+ setSelectedGitHubApp(sharedApp);
+ }, [isUpdate, selectedGitHubApp, pendingGitHubAppId, sharedApp]);
+
+ // On reconnect, reuse the GitHub App the connection was originally created with.
+ const existingGitHubAppId =
+ (appConnection?.credentials as { gitHubAppId?: string | null } | undefined)?.gitHubAppId ??
+ null;
+ const reconnectApp = isUpdate
+ ? (gitHubApps.find((app) => (app.id ?? null) === existingGitHubAppId) ?? null)
+ : null;
+
+ const buildGithubHost = (host?: string) =>
+ host && host.length > 0 ? `https://${host}` : "https://github.com";
+
+ const generateInstallState = () =>
+ Array.from(crypto.getRandomValues(new Uint8Array(16)))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
+ const storeConnectionFormData = (
+ formData: FormData,
+ installState: string,
+ gitHubAppId?: string | null
+ ) => {
localStorage.setItem("latestCSRFToken", installState);
localStorage.setItem(
- "githubConnectionFormData",
+ GITHUB_CONNECTION_FORM_KEY,
JSON.stringify({
...formData,
- credentials: formData.credentials as TGitHubConnection["credentials"],
+ credentials: {
+ ...(formData.credentials as TGitHubConnection["credentials"]),
+ ...(gitHubAppId ? { gitHubAppId } : {})
+ },
connectionId: appConnection?.id,
projectId,
returnUrl
} as GitHubFormData)
);
+ };
- const githubHost =
- formData.credentials?.host && formData.credentials.host.length > 0
- ? `https://${formData.credentials.host}`
- : "https://github.com";
+ // Kicks off GitHub App manifest creation, then redirects to GitHub to create + install the app.
+ // This only creates the GitHub App — when the user returns they land back on this form with the
+ // new app selected and complete the connection separately, so the connection fields aren't
+ // required here (only the GitHub App name, which the selector validates).
+ const handleCreateApp = async ({ name, githubOrg }: { name: string; githubOrg: string }) => {
+ const formData = form.getValues();
+ setIsRedirecting(true);
+ const installState = generateInstallState();
+ storeConnectionFormData(formData, installState);
+
+ try {
+ const { data } = await apiRequest.post<{
+ state: string;
+ manifest: Record<string, unknown>;
+ githubActionUrl: string;
+ }>("/api/v1/github-apps/manifest/initiate", {
+ name,
+ instanceType: formData.credentials?.instanceType ?? "cloud",
+ githubOrg: githubOrg || undefined,
+ githubHost: formData.credentials?.host || undefined,
+ installState
+ });
+
+ const formEl = document.createElement("form");
+ formEl.method = "post";
+ formEl.action = `${data.githubActionUrl}?state=${encodeURIComponent(data.state)}`;
+ const input = document.createElement("input");
+ input.type = "hidden";
+ input.name = "manifest";
+ input.value = JSON.stringify(data.manifest);
+ formEl.appendChild(input);
+ document.body.appendChild(formEl);
+ formEl.submit();
+ return true;
+ } catch (err) {
+ setIsRedirecting(false);
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to start GitHub App creation."
+ });
+ return false;
+ }
+ };
+
+ const submitHandler = async (formData: FormData) => {
+ if (formData.method === GitHubConnectionMethod.Pat) {
+ await onSubmit(formData);
+ return;
+ }
+
+ setIsRedirecting(true);
+
+ // generate install state here so the OAuth callback can validate it
+ const installState = generateInstallState();
+ const githubHost = buildGithubHost(formData.credentials?.host);
switch (formData.method) {
case GitHubConnectionMethod.App: {
- if (appSource === "dedicated") {
- const { data } = await apiRequest.post<{
- state: string;
- manifest: Record<string, unknown>;
- githubActionUrl: string;
- }>("/api/v1/github-apps/manifest/initiate", {
- name: dedicatedAppSlug,
- instanceType: formData.credentials?.instanceType ?? "cloud",
- githubOrg: dedicatedAppOrg.trim() || undefined,
- githubHost: formData.credentials?.host || undefined,
- installState
- });
-
- const formEl = document.createElement("form");
- formEl.method = "post";
- formEl.action = `${data.githubActionUrl}?state=${encodeURIComponent(data.state)}`;
-
- const input = document.createElement("input");
- input.type = "hidden";
- input.name = "manifest";
- input.value = JSON.stringify(data.manifest);
- formEl.appendChild(input);
-
- document.body.appendChild(formEl);
- formEl.submit();
- return;
- }
-
+ const targetApp = isUpdate ? reconnectApp : selectedGitHubApp;
+ const slug = targetApp?.slug ?? appClientSlug;
+ // Custom apps carry an id we persist into credentials; the shared app (id null) resolves
+ // to the instance-default app on the backend.
+ storeConnectionFormData(formData, installState, targetApp?.id ?? undefined);
window.location.assign(
- `${githubHost}/${formData.credentials?.instanceType === "server" ? "github-apps" : "apps"}/${appClientSlug}/installations/new?state=${installState}`
+ `${githubHost}/${formData.credentials?.instanceType === "server" ? "github-apps" : "apps"}/${slug}/installations/new?state=${installState}`
);
break;
}
case GitHubConnectionMethod.OAuth:
+ storeConnectionFormData(formData, installState);
window.location.assign(
`${githubHost}/login/oauth/authorize?client_id=${oauthClientId}&response_type=code&scope=repo,admin:org&redirect_uri=${window.location.origin}/organization/app-connections/github/oauth/callback&state=${installState}`
);
@@ -286,7 +338,9 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro
isMissingConfig = !oauthClientId;
break;
case GitHubConnectionMethod.App:
- isMissingConfig = (isUpdate || appSource === "shared") && !appClientSlug;
+ // On reconnect we need the original app to still resolve. For new connections the selector
+ // always lets the user pick or create an app, so there's no missing-config state.
+ isMissingConfig = isUpdate && !reconnectApp && !appClientSlug;
break;
case GitHubConnectionMethod.Pat:
isMissingConfig = false;
@@ -317,15 +371,14 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro
return fieldError?.message;
};
+ const isAppMethodMissingSelection =
+ selectedMethod === GitHubConnectionMethod.App && !isUpdate && !selectedGitHubApp;
+
const getButtonText = () => {
if (selectedMethod === GitHubConnectionMethod.Pat) {
return isUpdate ? "Update Connection" : "Create Connection";
}
- if (selectedMethod === GitHubConnectionMethod.App && appSource === "dedicated" && !isUpdate) {
- return "Create app & connect";
- }
-
return isUpdate ? "Reconnect to GitHub" : "Connect to GitHub";
};
@@ -349,6 +402,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro
isDisabled={isUpdate}
value={value}
onValueChange={(val) => onChange(val)}
+ containerClassName="w-full"
className="w-full border border-mineshaft-500"
position="popper"
dropdownContainerClassName="max-w-none"
@@ -367,74 +421,19 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro
/>
{selectedMethod === GitHubConnectionMethod.App && !isUpdate && (
<FormControl
- label="GitHub App setup"
- tooltipText="Reuse the shared instance-default GitHub App or create a new private app dedicated to this connection."
+ label="GitHub App"
+ tooltipText="Reuse an existing GitHub App in your organization or create a new one. Apps can be shared across multiple connections."
>
- <div className="flex flex-col gap-3">
- {appClientSlug && (
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
- <AppSourceCard
- title="Use shared app"
- description="Reuse the instance-default GitHub App. Best for teams managing many connections."
- icon={<FontAwesomeIcon icon={faGithub} className="text-base" />}
- selected={appSource === "shared"}
- onClick={() => setAppSource("shared")}
- />
- <AppSourceCard
- title="Create dedicated app"
- description="One app per connection. Maximum isolation, no admin handoff."
- icon={<FontAwesomeIcon icon={faPlus} className="text-base" />}
- selected={appSource === "dedicated"}
- onClick={() => setAppSource("dedicated")}
- />
- </div>
- )}
- {appSource === "dedicated" && (
- <>
- <div className="flex items-start gap-3 rounded-md border border-mineshaft-500 bg-mineshaft-700/40 px-3 py-2.5">
- <div className="mt-0.5 flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-sm bg-primary/15 text-primary">
- <FontAwesomeIcon icon={faPlus} className="text-xs" />
- </div>
- <div className="text-xs leading-relaxed text-mineshaft-300">
- Will create and install{" "}
- <span className="font-mono text-mineshaft-100">{dedicatedAppSlug}</span>{" "}
- <Badge variant="info" className="ml-1">
- New
- </Badge>
- <div className="mt-0.5 text-mineshaft-400">
- Private · scoped to this connection
- </div>
- </div>
- </div>
- <FormControl
- label="GitHub Organization"
- isOptional
- helperText="Leave blank to register under your personal account."
- className="mb-0"
- >
- <Input
- value={dedicatedAppOrg}
- onChange={(e) => setDedicatedAppOrg(e.target.value)}
- placeholder="my-github-org"
- />
- </FormControl>
- </>
- )}
- {appSource === "shared" && appClientSlug && (
- <div className="flex items-start gap-3 rounded-md border border-mineshaft-500 bg-mineshaft-700/40 px-3 py-2.5">
- <div className="mt-0.5 flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-sm bg-mineshaft-600 text-mineshaft-200">
- <FontAwesomeIcon icon={faGithub} className="text-xs" />
- </div>
- <div className="text-xs leading-relaxed text-mineshaft-300">
- Will install{" "}
- <span className="font-mono text-mineshaft-100">{appClientSlug}</span>
- <div className="mt-0.5 text-mineshaft-400">
- Public · shared across all connections
- </div>
- </div>
- </div>
- )}
- </div>
+ <GitHubAppSelector
+ apps={gitHubApps}
+ isLoading={isGitHubAppsLoading}
+ value={selectedGitHubApp}
+ onChange={setSelectedGitHubApp}
+ host={instanceType === "server" ? watch("credentials.host") : undefined}
+ instanceType={instanceType}
+ onCreateApp={handleCreateApp}
+ isCreating={isRedirecting}
+ />
</FormControl>
)}
{selectedMethod === GitHubConnectionMethod.Pat && (
@@ -477,6 +476,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro
setValue("gatewayPoolId", null);
}
}}
+ containerClassName="w-full"
className="w-full border border-mineshaft-500"
dropdownContainerClassName="max-w-none"
placeholder="Enterprise Cloud"
@@ -545,11 +545,12 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro
colorSchema="secondary"
isLoading={isSubmitting || isRedirecting}
isDisabled={
+ (!isUpdate && !isDirty && !isResumed) ||
isSubmitting ||
- (!isUpdate && !isDirty) ||
isMissingConfig ||
isRedirecting ||
- isCloudCustomHostUnsupported
+ isCloudCustomHostUnsupported ||
+ isAppMethodMissingSelection
}
>
{getButtonText()}
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx
index 97c9760f5c..eae3c0275a 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import {
faArrowDown,
faArrowUp,
@@ -10,6 +10,7 @@ import {
faSearch
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useNavigate, useSearch } from "@tanstack/react-router";
import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
@@ -97,6 +98,23 @@ export const AppConnectionsTable = ({ projectId, projectType }: Props) => {
"editDetails"
] as const);
+ // When returning from the "Create new GitHub App" flow, reopen the Add Connection modal straight
+ // into that app's form (the param is set by the GitHub manifest callback).
+ const routeSearch = useSearch({ strict: false }) as { addConnectionApp?: AppConnection };
+ const navigate = useNavigate();
+ const [presetApp, setPresetApp] = useState<AppConnection | undefined>();
+
+ useEffect(() => {
+ if (!routeSearch.addConnectionApp) return;
+ setPresetApp(routeSearch.addConnectionApp);
+ handlePopUpOpen("addConnection");
+ navigate({
+ from: "/organizations/$orgId/app-connections/",
+ search: (prev) => ({ ...prev, addConnectionApp: undefined }),
+ replace: true
+ });
+ }, [routeSearch.addConnectionApp]);
+
const [view, setView] = useState<View>(() => {
const storedView = localStorage.getItem(APP_CONNECTION_VIEW_STORAGE_KEY) as View | null;
@@ -510,7 +528,11 @@ export const AppConnectionsTable = ({ projectId, projectType }: Props) => {
/>
<AddAppConnectionModal
isOpen={popUp.addConnection.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("addConnection", isOpen)}
+ onOpenChange={(isOpen) => {
+ handlePopUpToggle("addConnection", isOpen);
+ if (!isOpen) setPresetApp(undefined);
+ }}
+ app={presetApp}
projectId={projectId}
projectType={projectType}
/>
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/route.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/route.tsx
index a036c1e892..d6b08e3230 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/route.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/route.tsx
@@ -1,6 +1,8 @@
import { createFileRoute } from "@tanstack/react-router";
import { z } from "zod";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+
import { AppConnectionsPage } from "./AppConnectionsPage";
export const Route = createFileRoute(
@@ -10,7 +12,9 @@ export const Route = createFileRoute(
validateSearch: z.object({
error: z.string().optional(),
success: z.string().optional(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ // Set after creating a new GitHub App so we reopen the Add Connection modal to that app's form.
+ addConnectionApp: z.nativeEnum(AppConnection).optional()
}),
context: () => ({
breadcrumbs: [
diff --git a/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx b/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx
index c7134bcd1a..23268575a1 100644
--- a/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx
+++ b/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx
@@ -4,6 +4,7 @@ import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { createNotification } from "@app/components/notifications";
import { ContentLoader } from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
const GITHUB_CONNECTION_FORM_KEY = "githubConnectionFormData";
@@ -19,48 +20,47 @@ export const GitHubManifestCallbackPage = () => {
if (hasRunRef.current) return;
hasRunRef.current = true;
- const { gitHubAppId, slug, installState, instanceType, host } = search;
+ const { gitHubAppId, slug, installState } = search;
- const fallback = () =>
+ const returnToForm = () =>
navigate({
to: "/organizations/$orgId/app-connections",
- params: { orgId }
+ params: { orgId },
+ search: { addConnectionApp: AppConnection.GitHub }
});
if (!gitHubAppId || !slug || !installState) {
createNotification({ type: "error", text: "Invalid GitHub manifest callback parameters." });
- fallback();
- return;
- }
-
- const connectionFormRaw = localStorage.getItem(GITHUB_CONNECTION_FORM_KEY);
- if (!connectionFormRaw) {
- createNotification({ type: "error", text: "Missing GitHub connection form state." });
- fallback();
+ navigate({ to: "/organizations/$orgId/app-connections", params: { orgId } });
return;
}
+ // The GitHub App is already created at this point. Mark the in-progress connection form so it
+ // resumes with the new app selected, then send the user back to it to finish the connection.
try {
- const connectionForm = JSON.parse(connectionFormRaw) as {
- credentials?: Record<string, unknown>;
- };
+ const connectionFormRaw = localStorage.getItem(GITHUB_CONNECTION_FORM_KEY);
+ const connectionForm = connectionFormRaw
+ ? (JSON.parse(connectionFormRaw) as {
+ credentials?: Record<string, unknown>;
+ resumeWithGitHubAppId?: string;
+ })
+ : {};
connectionForm.credentials = {
...(connectionForm.credentials ?? {}),
gitHubAppId
};
+ connectionForm.resumeWithGitHubAppId = gitHubAppId;
localStorage.setItem(GITHUB_CONNECTION_FORM_KEY, JSON.stringify(connectionForm));
} catch {
- createNotification({ type: "error", text: "Corrupt GitHub connection form state." });
- fallback();
- return;
+ // A corrupt form just means we can't restore the other fields; the app was still created.
+ localStorage.removeItem(GITHUB_CONNECTION_FORM_KEY);
}
- const githubHost = host && host.length > 0 ? `https://${host}` : "https://github.com";
- const appPathSegment = instanceType === "server" ? "github-apps" : "apps";
-
- window.location.assign(
- `${githubHost}/${appPathSegment}/${slug}/installations/new?state=${installState}`
- );
+ createNotification({
+ type: "success",
+ text: "GitHub App created. Select it and finish setting up your connection."
+ });
+ returnToForm();
}, []);
return (