feat(projects): select multiple GitHub source repositories (#13010)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Projects give tasks a common source repository and execution
context.
> - The current project form asks for a raw URL and unrelated metadata.
> - Teams need to select several repos from GitHub connections they can
use.
> - This pull request implements the reviewed project form and
repository editor.
> - The server checks credential ownership and shared audiences before
discovery.
> - Existing workspace URLs and runtime identity rules remain
compatible.

## Linked Issues or Issue Description

**Problem or motivation**

Project creation accepts one raw repository URL. It does not help users
select repos from their usable GitHub connections or attach several
repos together.

**Proposed solution**

Add a shared GitHub repository picker to project creation and
Configuration. Support multiple selections, transactional persistence,
and the existing GitHub setup flow. Simplify the project form and
Configuration tab as reviewed.

**Alternatives considered**

Keep a raw URL field or add a separate repository table. The existing
workspace collection already supports several repositories and keeps
legacy URLs compatible.

**Roadmap alignment**

This builds on the shipped MCP Tool Gateway and Apps capability. It does
not change runtime credential delegation.

Related work: #11662 addresses the existing dialog's viewport limits.
#4552 addresses generic Git URLs; this change preserves those URLs in
existing workspaces.

## What Changed

- Add company-scoped repository discovery from usable personal and
shared GitHub grants, with provider-ID deduplication, PAT pagination,
and partial failure handling.
- Document the repository endpoints and board access requirements in
OpenAPI.
- Validate new selections and save projects with multiple repository
workspaces in one transaction. Preserve legacy URLs and existing
selections whose access was lost.
- Implement the reviewed Create project dialog, shared repository
editor, scrolling, and mobile layout.
- Move repositories above environment variables, remove Status and Goals
controls and env help paragraphs, move Created to the bottom, and
redirect Overview to Configuration.
- Reuse GitHub setup in dialogs, preserve project drafts, and verify
popup completion through the API.
- Replace the configuration story's DOM adapter with explicit production
composition. Keep the reviewed mobile and short-viewport stories.

## Verification

- Passed: `pnpm build`, `pnpm -r typecheck`, `pnpm build-storybook`, and
`pnpm check:token-gates`.
- Passed: focused repository access, database persistence,
configuration, and connection setup tests.
- Passed: `pnpm exec playwright test --config
tests/e2e/playwright.config.ts tests/e2e/project-repositories.spec.ts`.
- The browser tests use a real temporary server/database. They cover
create, forty persisted repos, mobile scrolling, save/reload, legacy URL
editing, and rejection without a partial project.
- GitHub responses and popup completion use deterministic fixtures. No
real GitHub account was authorized by the test suite.
- All CI general, serialized server, and browser test shards pass on the
final commit.
- The local full-suite run overlapped review edits and was stopped;
fresh repository, OpenAPI, UI/CLI, and connection tests pass. Unrelated
local worker, built-in-agent, and routine timing/socket failures passed
isolated reruns.
- Final commit `1b3308dca`: all CI gates pass, including build, runner
verification, typecheck, canary dry run, and security checks. Greptile
is 5/5 with no unresolved review threads.
- Storybook visual regression is opt-in and was skipped by CI; the
Storybook build passed locally.

## Risks

- Repository discovery depends on provider availability. Failed
connections are reported while successful results stay usable.
- Selections identify source workspaces; they do not grant agents new
credentials. The existing primary-workspace and responsible-user
identity rules still apply.
- No database migration is needed. Existing API status, goals, dates,
and manual workspace URLs remain supported.

## Model Used

OpenAI Codex, based on GPT-6, with repository inspection, code
execution, and browser tools. The runtime does not expose a more
specific model deployment ID or context-window size.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-08 08:21:28 -05:00
1 parent 297d8741f5
commit b97101893f
34 files changed
+1428 -875

No files matched your search

@@ -280,6 +280,18 @@ describe("openapi routes", () => {
});
});
it("documents board-only repository discovery and selection", () => {
const { spec } = loadSpecRoutes();
const discovery = spec.paths["/api/companies/{companyId}/project-repositories"].get;
const replacement = spec.paths["/api/projects/{id}/repositories"].put;
for (const operation of [discovery, replacement]) {
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
}
expect(replacement.requestBody.content["application/json"].schema.required).toContain("repositoryIds");
expect(replacement.responses["422"]).toBeDefined();
});
it("documents auth and reviewed response-code invariants", () => {
const { spec } = loadSpecRoutes();
@@ -0,0 +1,115 @@
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { companies, companyMemberships, companySecrets, connectionGrants, connectionGrantMembers, toolApplications, toolConnections, createDb, projects as projectTable } from "@paperclipai/db";
import { eq } from "drizzle-orm";
import { toolAccessService } from "../services/tool-access.js";
import { projectService } from "../services/projects.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
vi.mock("../services/secrets.js", () => ({ secretService: () => ({
resolveSecretValue: async (_companyId: string, secretId: string) => secretId,
}) }));
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("project repository persistence", () => {
let temp: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let companyId: string;
const repo = (id: string) => ({ id, fullName: `org/repo-${id}`, url: `https://github.com/org/repo-${id}`, connections: [] });
beforeAll(async () => {
temp = await startEmbeddedPostgresTestDatabase("paperclip-repositories-");
db = createDb(temp.connectionString);
[companyId] = (await db.insert(companies).values({ name: "Repositories", issuePrefix: "REPO" }).returning()).map((company) => company.id);
}, 20_000);
afterAll(async () => { await temp?.cleanup(); });
afterEach(() => vi.unstubAllGlobals());
it("creates multiple source repos atomically and persists them across reads", async () => {
const svc = projectService(db);
const created = await svc.createWithRepositories(companyId, { name: "Multi" }, [repo("1"), repo("2")]);
const fetched = await svc.getById(created.id);
expect(fetched?.workspaces.map((workspace) => workspace.repoUrl).sort()).toEqual([repo("1").url, repo("2").url]);
expect(fetched?.workspaces.filter((workspace) => workspace.isPrimary)).toHaveLength(1);
expect(fetched?.workspaces.every((workspace) => workspace.companyId === companyId)).toBe(true);
});
it("adds/removes repos, promotes the remaining primary, and preserves legacy and local config", async () => {
const svc = projectService(db);
const created = await svc.createWithRepositories(companyId, { name: "Edit" }, [repo("3"), repo("4")]);
const legacy = await svc.createWorkspace(created.id, { repoUrl: "https://git.example/legacy/repo" });
const local = await svc.createWorkspace(created.id, { cwd: "/tmp/local-project", repoUrl: repo("5").url, metadata: { githubRepositoryId: "5", retained: true } });
const updated = await svc.replaceRepositories(created.id, [repo("4"), repo("6")]);
expect(updated?.workspaces.find((workspace) => workspace.id === legacy!.id)?.repoUrl).toBe("https://git.example/legacy/repo");
expect(updated?.workspaces.find((workspace) => workspace.id === local!.id)).toMatchObject({ cwd: "/tmp/local-project", repoUrl: null, metadata: { retained: true } });
expect(updated?.workspaces.some((workspace) => workspace.repoUrl === repo("3").url)).toBe(false);
expect(updated?.workspaces.filter((workspace) => workspace.isPrimary)).toHaveLength(1);
const repeated = await svc.replaceRepositories(created.id, [repo("4"), repo("6")]);
expect(repeated?.workspaces).toHaveLength(updated!.workspaces.length);
});
it("handles a repo recreated at the same URL with a new GitHub identity", async () => {
const svc = projectService(db);
const original = repo("20");
const created = await svc.createWithRepositories(companyId, { name: "Recreated" }, [original]);
const updated = await svc.replaceRepositories(created.id, [{ ...original, id: "21" }]);
expect(updated?.workspaces).toHaveLength(1);
expect(updated?.workspaces[0]?.metadata?.githubRepositoryId).toBe("21");
});
it("refreshes renamed and transferred repositories without replacing workspace identity or configuration", async () => {
const svc = projectService(db);
const created = await svc.createWithRepositories(companyId, { name: "Renamed" }, [repo("22")]);
const workspace = created.workspaces[0];
await svc.updateWorkspace(created.id, workspace.id, { cwd: "/tmp/renamed-project", repoRef: "release", metadata: { ...workspace.metadata, retained: true } });
const renamed = { ...repo("22"), fullName: "new-owner/new-name", url: "https://github.com/new-owner/new-name" };
const updated = await svc.replaceRepositories(created.id, [renamed]);
expect(updated?.workspaces).toHaveLength(1);
expect(updated?.workspaces[0]).toMatchObject({ id: workspace.id, name: renamed.fullName, repoUrl: renamed.url, cwd: "/tmp/renamed-project", repoRef: "release", isPrimary: true, metadata: { githubRepositoryId: "22", retained: true } });
expect(updated?.codebase.repoUrl).toBe(renamed.url);
});
it("loads only usable connection grants, deduplicates repos, and reports partial provider failures", async () => {
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "alice", membershipRole: "admin" });
const [otherCompany] = await db.insert(companies).values({ name: "Other", issuePrefix: "OTHER" }).returning();
const tokenRepos = new Map<string, Array<{ id: number; full_name: string }>>();
async function connection(name: string, kind: "user" | "organization", owner: string | null, audience: string[] = [], targetCompanyId = companyId) {
const [app] = await db.insert(toolApplications).values({ companyId: targetCompanyId, name, type: "mcp_http" }).returning();
const [secret] = await db.insert(companySecrets).values({ companyId: targetCompanyId, name, key: name }).returning();
const [conn] = await db.insert(toolConnections).values({ companyId: targetCompanyId, applicationId: app.id, name, uid: name, status: "active", enabled: true,
transport: "mcp_remote", authKind: "api_key", credentialPolicy: kind === "user" ? "per_user" : "shared", config: { sourceTemplateKey: "github" } }).returning();
const [grant] = await db.insert(connectionGrants).values({ companyId: targetCompanyId, connectionId: conn.id, kind, subjectUserId: owner,
credentialSecretRefs: [{ secretId: secret.id, configPath: "credentials.authorization", versionSelector: "latest" }] }).returning();
for (const subjectId of audience) await db.insert(connectionGrantMembers).values({ companyId: targetCompanyId, grantId: grant.id, subjectType: "user", subjectId });
return secret.id;
}
const personal = await connection("personal", "user", "alice");
const shared = await connection("shared", "organization", null);
const otherPerson = await connection("other-person", "user", "bob");
const restricted = await connection("restricted", "organization", null, ["bob"]);
const crossCompany = await connection("cross-company", "organization", null, [], otherCompany.id);
const broken = await connection("broken", "organization", null);
tokenRepos.set(personal, [{ id: 10, full_name: "org/common" }, { id: 11, full_name: "alice/private" }]);
tokenRepos.set(shared, [{ id: 10, full_name: "org/common" }, { id: 12, full_name: "org/shared" }]);
const request = vi.fn<typeof fetch>(async (_url, init) => {
const token = new Headers(init?.headers).get("authorization")?.replace("Bearer ", "") ?? "";
if (token === broken) return new Response("secret-provider-error", { status: 503 });
expect([otherPerson, restricted, crossCompany]).not.toContain(token);
return Response.json(tokenRepos.get(token) ?? []);
});
vi.stubGlobal("fetch", request);
const result = await toolAccessService(db).listProjectRepositories(companyId, "alice");
expect(result.connectionCount).toBe(3);
expect(result.failedConnectionCount).toBe(1);
expect(result.repositories.map((repo) => repo.id).sort()).toEqual(["10", "11", "12"]);
expect(result.repositories.find((repo) => repo.id === "10")?.connections.sort()).toEqual(["personal", "shared"]);
expect(JSON.stringify(result)).not.toContain("secret-provider-error");
expect(request).toHaveBeenCalledTimes(3);
const revokedMembership = await db.update(companyMemberships).set({ status: "inactive" }).where(eq(companyMemberships.principalId, "alice")).returning();
expect(revokedMembership).toHaveLength(1);
expect((await toolAccessService(db).listProjectRepositories(companyId, "alice")).repositories).toEqual([]);
expect(request).toHaveBeenCalledTimes(3);
});
it("rolls back the project if a later repository insert fails", async () => {
const svc = projectService(db);
await expect(svc.createWithRepositories(companyId, { name: "Rollback" }, [repo("7"), { ...repo("8"), fullName: "invalid" + String.fromCharCode(0) + "name" }])).rejects.toThrow();
expect(await db.select().from(projectTable).where(eq(projectTable.name, "Rollback"))).toEqual([]);
});
});
@@ -0,0 +1,54 @@
import { describe, expect, it, vi } from "vitest";
import { canBrowseProjectRepositoryGrant, mergeProjectRepository, resolveProjectRepositorySelection } from "../services/project-repositories.js";
import { loadGitHubTokenRepositories } from "../services/tool-access.js";
import type { ProjectRepository } from "@paperclipai/shared";
describe("project repository access", () => {
const own = { status: "active", kind: "user", subjectUserId: "alice" };
const shared = { ...own, kind: "organization", subjectUserId: null };
const allowed = (grant: { status: string; kind: string; subjectUserId: string | null } = own, userId: string | null = "alice", activeMember = true, audience: string[] = []) =>
canBrowseProjectRepositoryGrant({ grant, userId, activeMember, audience });
it("includes only the caller's personal identity and active company membership", () => {
expect(allowed()).toBe(true);
expect(allowed(own, "bob")).toBe(false);
expect(allowed(own, null)).toBe(false);
expect(allowed(own, "alice", false)).toBe(false);
expect(allowed({ ...own, kind: "agent" })).toBe(false);
for (const status of ["revoked", "expired", "needs_reauthorization"]) expect(allowed({ ...own, status })).toBe(false);
});
it("honors shared audiences without an administrator bypass", () => {
expect(allowed(shared)).toBe(true);
expect(allowed(shared, "alice", true, ["alice"])).toBe(true);
expect(allowed(shared, "alice", true, ["bob"])).toBe(false);
expect(allowed(shared, "alice", false)).toBe(false);
expect(allowed(shared, null, false)).toBe(true); // local trusted board
expect(allowed(shared, null, false, ["alice"])).toBe(false);
});
it("deduplicates by provider id across personal and shared connections", () => {
const repos = new Map<string, ProjectRepository>();
mergeProjectRepository(repos, { id: "10", fullName: "org/old", private: true }, "Personal");
mergeProjectRepository(repos, { id: "10", fullName: "org/renamed", private: true }, "Company");
mergeProjectRepository(repos, { id: "10", fullName: "org/renamed", private: true }, "Company");
expect([...repos.values()]).toEqual([{ id: "10", fullName: "org/renamed", url: "https://github.com/org/renamed", private: true, connections: ["Personal", "Company"] }]);
});
it("refreshes retained selections from discovery, falls back only for unavailable existing IDs, and rejects new unavailable IDs", () => {
const existing = [{ name: "old/name", repoUrl: "https://github.com/old/name", metadata: { githubRepositoryId: "1" } }];
const renamed = { id: "1", fullName: "new/name", url: "https://github.com/new/name", connections: ["Personal"] };
expect(resolveProjectRepositorySelection(["1", "1"], [renamed], existing)).toEqual([renamed]);
expect(resolveProjectRepositorySelection(["1"], [], existing)).toEqual([{ id: "1", fullName: "old/name", url: existing[0].repoUrl, connections: [] }]);
expect(() => resolveProjectRepositorySelection(["2"], [], existing)).toThrow("no longer available");
});
it("loads every PAT repository page and never follows provider-supplied URLs", async () => {
const request = vi.fn<typeof fetch>().mockResolvedValueOnce(new Response(JSON.stringify([{ id: 1, full_name: "org/a" }]), { headers: { link: '<https://evil.test/steal>; rel="next"' } }))
.mockResolvedValueOnce(new Response(JSON.stringify([{ id: 2, full_name: "org/b", private: true }])));
expect(await loadGitHubTokenRepositories({ Authorization: "Bearer fixture" }, request)).toEqual([{ id: "1", fullName: "org/a" }, { id: "2", fullName: "org/b", private: true }]);
expect(request.mock.calls.map(([url]) => String(url))).toEqual([
"https://api.github.com/user/repos?per_page=100&page=1", "https://api.github.com/user/repos?per_page=100&page=2",
]);
});
it("surfaces failed or invalid provider responses without exposing their body", async () => {
for (const response of [new Response("secret", { status: 401 }), new Response(JSON.stringify([{ id: 1, full_name: "../bad" }]))]) {
await expect(loadGitHubTokenRepositories({}, vi.fn().mockResolvedValue(response))).rejects.toThrow(/GitHub/);
}
});
});
+31 -1
View File
@@ -858,6 +858,8 @@ const BOARD_ONLY_PREFIXES = [
];
const BOARD_ONLY_OPERATIONS = new Set([
"GET /api/companies/{companyId}/project-repositories",
"PUT /api/projects/{id}/repositories",
"DELETE /api/issues/{id}/documents/{key}",
"GET /api/companies/{companyId}/decisions",
"GET /api/cloud/stacks",
@@ -2830,6 +2832,33 @@ registry.registerPath({
// ─── Projects ────────────────────────────────────────────────────────────────
registry.registerPath({
method: "get",
path: "/api/companies/{companyId}/project-repositories",
tags: ["projects"],
summary: "Discover GitHub repositories available to the current board user",
description: "Deduplicates repositories across usable personal and company-shared GitHub connections. Failed connections are reported without discarding successful results.",
request: { params: z.object({ companyId: z.string() }) },
responses: {
200: r.ok(z.object({
repositories: z.array(z.object({ id: z.string(), fullName: z.string(), url: z.string(), private: z.boolean().optional(), connections: z.array(z.string()) })),
connectionCount: z.number().int().nonnegative(),
failedConnectionCount: z.number().int().nonnegative(),
})),
401: r.unauthorized, 403: r.forbidden,
},
});
registry.registerPath({
method: "put",
path: "/api/projects/{id}/repositories",
tags: ["projects"],
summary: "Replace selected GitHub source repositories",
description: "Saves provider IDs transactionally, refreshes canonical names and URLs, and preserves legacy workspace URLs. Unavailable existing selections can remain; new selections must be available to the caller.",
request: { params: z.object({ id: z.string() }), body: jsonBody(createProjectSchema.pick({ repositoryIds: true }).required()) },
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 422: r.unprocessable },
});
registry.registerPath({
method: "get",
path: "/api/companies/{companyId}/projects",
@@ -2844,11 +2873,12 @@ registry.registerPath({
path: "/api/companies/{companyId}/projects",
tags: ["projects"],
summary: "Create a project",
description: "The optional repositoryIds field selects GitHub source repositories and requires a board caller. It cannot be combined with workspace. All selections are validated before the project and repository workspaces are created atomically.",
request: {
params: z.object({ companyId: z.string() }),
body: jsonBody(createProjectSchema),
},
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 422: r.unprocessable },
});
registry.registerPath({
+38 -3
View File
@@ -1,3 +1,6 @@
import { z } from "zod";
import { resolveProjectRepositorySelection } from "../services/project-repositories.js";
import { toolAccessService } from "../services/tool-access.js";
import { Router, type Request, type Response } from "express";
import type { Db } from "@paperclipai/db";
import {
@@ -17,7 +20,7 @@ import { accessService, projectService, logActivity, workspaceOperationService }
import { conflict, forbidden, unprocessable } from "../errors.js";
import { externalObjectService } from "../services/external-objects.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
import {
buildWorkspaceRuntimeDesiredStatePatch,
listConfiguredRuntimeServiceEntries,
@@ -43,6 +46,13 @@ const SHARED_WORKSPACE_STOP_AND_RESTART_ACTIONS = new Set(["stop", "restart"]);
export function projectRoutes(db: Db) {
const router = Router();
const svc = projectService(db);
async function selectedRepositories(req: Request, companyId: string, ids: string[], existing: import("@paperclipai/shared").ProjectWorkspace[] = []) {
assertBoard(req);
if (!ids.length) return [];
const available = await toolAccessService(db).listProjectRepositories(companyId, req.actor.userId ?? null, req.actor.source === "local_implicit");
return resolveProjectRepositorySelection(ids, available.repositories, existing);
}
const access = accessService(db);
const secretsSvc = secretService(db);
const workspaceOperations = workspaceOperationService(db);
@@ -162,6 +172,28 @@ export function projectRoutes(db: Db) {
}
});
router.get("/companies/:companyId/project-repositories", async (req, res) => {
assertBoard(req);
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
res.json(await toolAccessService(db).listProjectRepositories(companyId, req.actor.userId ?? null, req.actor.source === "local_implicit"));
});
router.put("/projects/:id/repositories", validate(z.object({ repositoryIds: z.array(z.string().regex(/^\d+$/)) })), async (req, res) => {
assertBoard(req);
const project = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Project not found");
if (!project) return;
const repositories = await selectedRepositories(req, project.companyId, req.body.repositoryIds, project.workspaces);
const updated = await svc.replaceRepositories(project.id, repositories);
const actor = getActorInfo(req);
await logActivity(db, {
companyId: project.companyId, actorType: actor.actorType, actorId: actor.actorId,
action: "project.repositories_updated", entityType: "project", entityId: project.id,
details: { repositoryIds: repositories.map((repo) => repo.id) },
});
res.json(updated);
});
router.get("/companies/:companyId/projects", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
@@ -191,9 +223,10 @@ export function projectRoutes(db: Db) {
assertCompanyAccess(req, companyId);
type CreateProjectPayload = Parameters<typeof svc.create>[1] & {
workspace?: Parameters<typeof svc.createWorkspace>[1];
repositoryIds?: string[];
};
const { workspace, ...projectData } = req.body as CreateProjectPayload;
const { workspace, repositoryIds, ...projectData } = req.body as CreateProjectPayload;
await assertProjectEnvironmentSelection(
companyId,
readProjectPolicyEnvironmentId(projectData.executionWorkspacePolicy),
@@ -213,7 +246,9 @@ export function projectRoutes(db: Db) {
{ strictMode: strictSecretsMode, fieldPath: "env" },
);
}
const project = await svc.create(companyId, projectData);
if (workspace && repositoryIds) throw unprocessable("Use either workspace or repositoryIds when creating a project");
const repositories = repositoryIds ? await selectedRepositories(req, companyId, repositoryIds) : null;
const project = repositories ? await svc.createWithRepositories(companyId, projectData, repositories) : await svc.create(companyId, projectData);
if (project.env) {
await secretsSvc.syncEnvBindingsForTarget?.(
companyId,
@@ -0,0 +1,42 @@
import type { ProjectRepository, ProjectWorkspace } from "@paperclipai/shared";
import { unprocessable } from "../errors.js";
import { isConnectionGrantAudienceAllowed } from "./tool-gateway.js";
export function canBrowseProjectRepositoryGrant(input: {
grant: { status: string; kind: string; subjectUserId: string | null };
userId: string | null;
activeMember: boolean;
audience: string[];
}) {
const { grant, userId, activeMember, audience } = input;
if (grant.status !== "active") return false;
if (grant.kind === "user") return Boolean(userId && activeMember && grant.subjectUserId === userId);
return grant.kind === "organization" && isConnectionGrantAudienceAllowed(audience, userId, activeMember);
}
export function mergeProjectRepository(
repositories: Map<string, ProjectRepository>,
repo: { id: string; fullName: string; private?: boolean },
connectionName: string,
) {
const previous = repositories.get(repo.id);
repositories.set(repo.id, {
...repo, url: `https://github.com/${repo.fullName}`,
connections: [...new Set([...(previous?.connections ?? []), connectionName])],
});
}
/** Prefer current provider metadata; unavailable existing selections can remain. */
export function resolveProjectRepositorySelection(
ids: string[],
available: ProjectRepository[],
existing: Pick<ProjectWorkspace, "name" | "repoUrl" | "metadata">[] = [],
): ProjectRepository[] {
return [...new Set(ids)].map((id) => {
const current = available.find((repo) => repo.id === id);
if (current) return current;
const retained = existing.find((workspace) => workspace.metadata?.githubRepositoryId === id && workspace.repoUrl);
if (retained) return { id, fullName: retained.name, url: retained.repoUrl!, connections: [] };
throw unprocessable("A selected GitHub repository is no longer available. Refresh repositories and try again.");
});
}
+46
View File
@@ -811,6 +811,52 @@ export function projectService(db: Db) {
};
},
createWithRepositories: async (companyId: string, data: Parameters<typeof createProject>[1], repositories: import("@paperclipai/shared").ProjectRepository[]): Promise<ProjectWithGoals> => {
return db.transaction(async (tx) => {
const service = projectService(tx as unknown as Db);
const project = await service.create(companyId, data);
for (const repo of repositories) {
await service.createWorkspace(project.id, { name: repo.fullName, repoUrl: repo.url, metadata: { githubRepositoryId: repo.id } });
}
return (await service.getById(project.id))!;
});
},
replaceRepositories: async (projectId: string, repositories: import("@paperclipai/shared").ProjectRepository[]): Promise<ProjectWithGoals | null> => {
return db.transaction(async (tx) => {
const [project] = await tx.select().from(projects).where(eq(projects.id, projectId)).for("update");
if (!project) return null;
const service = projectService(tx as unknown as Db);
const existing = await service.listWorkspaces(projectId);
const ids = new Set(repositories.map((repo) => repo.id));
for (const workspace of existing) {
const repoId = workspace.metadata?.githubRepositoryId;
if (typeof repoId === "string" && !ids.has(repoId)) {
// Keep local/runtime workspace configuration when detaching source.
if (workspace.cwd || workspace.remoteWorkspaceRef) {
const { githubRepositoryId: _id, ...metadata } = workspace.metadata!;
await service.updateWorkspace(projectId, workspace.id, { repoUrl: null, metadata });
} else await service.removeWorkspace(projectId, workspace.id);
}
}
for (const repo of repositories) {
const retained = existing.find((workspace) => workspace.metadata?.githubRepositoryId === repo.id);
if (retained) {
if (retained.repoUrl !== repo.url || retained.name !== repo.fullName) {
await service.updateWorkspace(projectId, retained.id, { name: repo.fullName, repoUrl: repo.url });
}
continue;
}
const legacy = existing.find((workspace) => !workspace.metadata?.githubRepositoryId && workspace.repoUrl?.replace(/\.git$/, "").replace(/\/$/, "").toLowerCase() === repo.url.toLowerCase());
if (legacy) {
await service.updateWorkspace(projectId, legacy.id, { metadata: { ...legacy.metadata, githubRepositoryId: repo.id } });
} else await service.createWorkspace(projectId, { name: repo.fullName, repoUrl: repo.url, metadata: { githubRepositoryId: repo.id } });
}
await tx.update(projects).set({ updatedAt: new Date() }).where(eq(projects.id, projectId));
return service.getById(projectId);
});
},
create: createProject,
update: async (
+87 -1
View File
@@ -1,3 +1,4 @@
import { canBrowseProjectRepositoryGrant, mergeProjectRepository } from "./project-repositories.js";
import { captureRunIdentity } from "./run-identity.js";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";
@@ -1930,6 +1931,27 @@ function managedConnectorProfile(value: string | undefined): {
return null;
}
export async function loadGitHubTokenRepositories(headers: Record<string, string>, request: typeof fetch = fetch) {
const repositories: Array<{ id: string; fullName: string; private?: boolean }> = [];
for (let page = 1; ; page += 1) {
const response = await request(`https://api.github.com/user/repos?per_page=100&page=${page}`, {
headers: { ...headers, accept: "application/vnd.github+json", "user-agent": "Paperclip", "x-github-api-version": "2022-11-28" },
signal: AbortSignal.timeout(15_000),
});
if (!response.ok) throw unprocessable("Could not load GitHub repositories. Reconnect GitHub and try again.");
const rows: unknown = await response.json();
if (!Array.isArray(rows)) throw unprocessable("GitHub returned invalid repositories");
for (const row of rows) {
if (!recordValue(row) || !githubId(row.id) || typeof row.full_name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9-]*\/(?!\.{1,2}$)[A-Za-z0-9_.-]+$/.test(row.full_name)) {
throw unprocessable("GitHub returned invalid repository metadata");
}
repositories.push({ id: githubId(row.id)!, fullName: row.full_name, ...(typeof row.private === "boolean" ? { private: row.private } : {}) });
}
if (!/;\s*rel="next"/.test(response.headers.get("link") ?? "")) return repositories;
if (!rows.length) throw unprocessable("GitHub returned invalid pagination");
}
}
export async function loadGitHubGrantMetadata(
accessToken: string,
request: typeof fetch = fetch,
@@ -2014,7 +2036,7 @@ export async function loadGitHubGrantMetadata(
for (const repository of await list(`/user/installations/${installationId}/repositories`, "repositories")) {
const id = githubId(repository.id);
const fullName = typeof repository.full_name === "string" ? repository.full_name : "";
if (!id || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(fullName)) {
if (!id || !/^[A-Za-z0-9][A-Za-z0-9-]*\/(?!\.{1,2}$)[A-Za-z0-9_.-]+$/.test(fullName)) {
throw unprocessable("GitHub returned invalid repository metadata", { code: "github_bad_response" });
}
repositories.set(id, {
@@ -12374,6 +12396,70 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
return toApplication(row);
},
// Repository discovery uses credential audiences, not connection-management
// visibility. An administrator cannot browse another user's private repos.
listProjectRepositories: async (companyId: string, userId: string | null, localTrusted = false) => {
const [connections, grants, members, memberships] = await Promise.all([
db.select().from(toolConnections).where(and(eq(toolConnections.companyId, companyId), eq(toolConnections.enabled, true))),
db.select().from(connectionGrants).where(eq(connectionGrants.companyId, companyId)),
db.select().from(connectionGrantMembers).where(eq(connectionGrantMembers.companyId, companyId)),
userId ? db.select().from(companyMemberships).where(and(
eq(companyMemberships.companyId, companyId), eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, userId), eq(companyMemberships.status, "active"),
)) : Promise.resolve([]),
]);
const repositories = new Map<string, import("@paperclipai/shared").ProjectRepository>();
let connectionCount = 0;
let failedConnectionCount = 0;
for (const connection of connections) {
if (connection.status !== "active" || asRecord(connection.config).sourceTemplateKey !== "github") continue;
const connectionGrants = grants.filter((grant) => grant.connectionId === connection.id);
const availableGrants = connectionGrants.filter((grant) =>
!(grant.kind === "organization" && ["per_user", "per_agent"].includes(connection.credentialPolicy))
&& canBrowseProjectRepositoryGrant({
grant, userId, activeMember: localTrusted || memberships.length > 0,
audience: members.filter((member) => member.grantId === grant.id).map((member) => member.subjectId),
}));
// Legacy shared PAT connections predate grants. Never fall back when a
// grant exists but is revoked, private, or outside the caller's audience.
const legacyShared = connectionGrants.length === 0 && connection.credentialPolicy === "shared"
&& (localTrusted || !!userId && memberships.length > 0);
if (!availableGrants.length && !legacyShared) continue;
connectionCount += 1;
const actor: ActorInfo = { actorType: "user", actorId: userId ?? "board" };
let failed = false;
for (const initialGrant of legacyShared ? [null] : availableGrants) {
try {
let rows: Array<{ id: string; fullName: string; private?: boolean }>;
if (initialGrant && asRecord(asRecord(connection.config).oauth).connectorProfile === "github.code") {
const grant = await refreshManagedGitHubGrantAccess(connection, initialGrant, actor);
rows = grant.providerTenant?.github?.repositories ?? [];
} else {
const headers = initialGrant
? await (async () => {
const ref = initialGrant.credentialSecretRefs.find((ref) =>
ref.configPath === "oauth.access_token" || /authorization|token|api_key/i.test(ref.configPath));
if (!ref) throw unprocessable("Reconnect GitHub to load repositories");
const secret = await resolveOAuthGrantSecret(connection, initialGrant, ref, actor, undefined);
return { Authorization: `Bearer ${secret.value}` };
})()
: await resolveCredentialHeaders(connection, actor);
rows = await loadGitHubTokenRepositories(headers);
}
for (const row of rows) {
mergeProjectRepository(repositories, row, connection.name);
}
} catch {
// Credential/provider errors may contain secrets. Only expose an
// aggregate failure; successful connections remain usable.
failed = true;
}
}
if (failed) failedConnectionCount += 1;
}
return { repositories: [...repositories.values()].sort((a, b) => a.fullName.localeCompare(b.fullName)), connectionCount, failedConnectionCount };
},
listConnections: async (companyId: string): Promise<ToolConnection[]> => {
const rows = await db
.select()