-
Notifications
You must be signed in to change notification settings - Fork 9
feat(sessions): ensure personal repo on POST /api/sessions #618
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
ad46fea
feat(sessions): ensure personal repo on POST /api/sessions
sweetmantech a54c39d
fix(sessions): flatten ResolveSessionCloneUrlResult to single interface
sweetmantech 8f161c3
refactor(repo-naming): unify workspace repos as recoupable/<accountId>
sweetmantech 1688646
review(PR #618): drop owner/token/description/isPrivate params
sweetmantech 3c9e18d
prune: drop runtime legacy-rename branch (script-once is enough)
sweetmantech b061ff0
prune: inline repo-name + URL into ensurePersonalRepo
sweetmantech 7a9d4dd
prune: ensurePersonalRepo now returns just the clone URL string
sweetmantech 90d194c
unify: provision org workspace repo too (cloneUrl: null branch fix)
sweetmantech 019229f
fix(migrate): match empty-slug -<uuid> repos too
sweetmantech 8576e2e
revert: createRepository back to private: true
sweetmantech 4ee6d2b
chore: drop migration script (already applied to prod GitHub)
sweetmantech 7e1b9e8
prune: slim CreateRepositoryResult to {success, repoUrl, error}
sweetmantech File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import { describe, it, expect, beforeEach, vi } from "vitest"; | ||
| import { createRepository } from "@/lib/github/createRepository"; | ||
| import { getServiceGithubToken } from "@/lib/github/getServiceGithubToken"; | ||
|
|
||
| vi.mock("@/lib/github/getServiceGithubToken", () => ({ | ||
| getServiceGithubToken: vi.fn(() => "tok"), | ||
| })); | ||
|
|
||
| describe("createRepository", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| vi.mocked(getServiceGithubToken).mockReturnValue("tok"); | ||
| }); | ||
|
|
||
| it("returns failure when GITHUB_TOKEN is missing", async () => { | ||
| vi.mocked(getServiceGithubToken).mockReturnValue(undefined); | ||
| const fetchSpy = vi.spyOn(globalThis, "fetch"); | ||
|
|
||
| const result = await createRepository({ name: "id-1" }); | ||
|
|
||
| expect(result.success).toBe(false); | ||
| expect(result.error).toMatch(/GITHUB_TOKEN/i); | ||
| expect(fetchSpy).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("rejects invalid names without hitting the network", async () => { | ||
| const fetchSpy = vi.spyOn(globalThis, "fetch"); | ||
|
|
||
| const result = await createRepository({ name: "bad name with spaces" }); | ||
|
|
||
| expect(result.success).toBe(false); | ||
| expect(result.error).toMatch(/invalid/i); | ||
| expect(fetchSpy).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("POSTs to /orgs/recoupable/repos with hard-coded private=true + auto_init=true", async () => { | ||
| const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue( | ||
| new Response( | ||
| JSON.stringify({ | ||
| html_url: "https://github.com/recoupable/id-1", | ||
| }), | ||
| { status: 201, headers: { "content-type": "application/json" } }, | ||
| ), | ||
| ); | ||
|
|
||
| const result = await createRepository({ name: "id-1" }); | ||
|
|
||
| expect(result).toEqual({ | ||
| success: true, | ||
| repoUrl: "https://github.com/recoupable/id-1", | ||
| }); | ||
| const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]; | ||
| expect(url).toBe("https://api.github.com/orgs/recoupable/repos"); | ||
| expect(init.method).toBe("POST"); | ||
| expect(JSON.parse(init.body as string)).toEqual({ | ||
| name: "id-1", | ||
| private: true, | ||
| auto_init: true, | ||
| }); | ||
| }); | ||
|
|
||
| it("returns name-conflict error on 422", async () => { | ||
| vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 422 })); | ||
|
|
||
| const result = await createRepository({ name: "id-1" }); | ||
|
|
||
| expect(result.success).toBe(false); | ||
| expect(result.error).toMatch(/already exists/i); | ||
| }); | ||
|
|
||
| it("returns permission-denied error on 403", async () => { | ||
| vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 403 })); | ||
|
|
||
| const result = await createRepository({ name: "id-1" }); | ||
|
|
||
| expect(result.success).toBe(false); | ||
| expect(result.error).toMatch(/permission/i); | ||
| }); | ||
|
|
||
| it("returns network-error on fetch rejection", async () => { | ||
| vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("ECONNRESET")); | ||
|
|
||
| const result = await createRepository({ name: "id-1" }); | ||
|
|
||
| expect(result.success).toBe(false); | ||
| expect(result.error).toMatch(/network/i); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| import { describe, it, expect, beforeEach, vi } from "vitest"; | ||
| import { repositoryExists } from "@/lib/github/repositoryExists"; | ||
| import { getServiceGithubToken } from "@/lib/github/getServiceGithubToken"; | ||
|
|
||
| vi.mock("@/lib/github/getServiceGithubToken", () => ({ | ||
| getServiceGithubToken: vi.fn(() => "tok"), | ||
| })); | ||
|
|
||
| describe("repositoryExists", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| vi.mocked(getServiceGithubToken).mockReturnValue("tok"); | ||
| }); | ||
|
|
||
| it("returns null when GITHUB_TOKEN is missing", async () => { | ||
| vi.mocked(getServiceGithubToken).mockReturnValue(undefined); | ||
| const fetchSpy = vi.spyOn(globalThis, "fetch"); | ||
|
|
||
| const result = await repositoryExists({ repo: "id-1" }); | ||
|
|
||
| expect(result).toBeNull(); | ||
| expect(fetchSpy).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns true on 200 and calls GET /repos/recoupable/<repo>", async () => { | ||
| const fetchSpy = vi | ||
| .spyOn(globalThis, "fetch") | ||
| .mockResolvedValue(new Response(null, { status: 200 })); | ||
|
|
||
| const result = await repositoryExists({ repo: "id-1" }); | ||
|
|
||
| expect(result).toBe(true); | ||
| expect(fetchSpy).toHaveBeenCalledWith( | ||
| "https://api.github.com/repos/recoupable/id-1", | ||
| expect.objectContaining({ | ||
| method: "GET", | ||
| headers: expect.objectContaining({ | ||
| Authorization: "Bearer tok", | ||
| }), | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it("returns false on 404", async () => { | ||
| vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 404 })); | ||
|
|
||
| expect(await repositoryExists({ repo: "missing" })).toBe(false); | ||
| }); | ||
|
|
||
| it("returns null on other statuses (auth, rate limit, etc.)", async () => { | ||
| vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 403 })); | ||
|
|
||
| expect(await repositoryExists({ repo: "rate-limited" })).toBeNull(); | ||
| }); | ||
|
|
||
| it("returns null on network failure", async () => { | ||
| vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("ECONNRESET")); | ||
|
|
||
| expect(await repositoryExists({ repo: "anything" })).toBeNull(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import { RECOUPABLE_GITHUB_OWNER } from "@/lib/recoupable/githubOwner"; | ||
| import { getServiceGithubToken } from "./getServiceGithubToken"; | ||
|
|
||
| export interface CreateRepositoryResult { | ||
| success: boolean; | ||
| /** GitHub UI URL (`html_url`). */ | ||
| repoUrl?: string; | ||
| /** Human-readable error message; only set when `success` is false. */ | ||
| error?: string; | ||
| } | ||
|
|
||
| /** | ||
| * Create a workspace repository under the Recoupable GitHub org. | ||
| * | ||
| * Hard-coded conventions (per PR #618 review — KISS / YAGNI): | ||
| * - owner = `recoupable` (no other owner makes sense; see | ||
| * `RECOUPABLE_GITHUB_OWNER`). | ||
| * - private = true (matches the 153 legacy workspace repos that | ||
| * pre-date this code path — keeps the fleet uniform; clones from | ||
| * sandboxes auth via the GITHUB_TOKEN service token). | ||
| * - description = none (GitHub doesn't render anything meaningful | ||
| * for these per-account repos). | ||
| * - token = read once from `GITHUB_TOKEN` via | ||
| * `getServiceGithubToken` (single source of truth — callers no | ||
| * longer thread the token through). | ||
| * | ||
| * `auto_init: true` so the repo has an initial `main` branch the | ||
| * sandbox can `git clone`. Without it, cloning a 0-commit repo fails. | ||
| * | ||
| * Uses plain `fetch` to match recoup-api's existing `lib/github/*` | ||
| * style (no Octokit dependency). | ||
| */ | ||
| export async function createRepository(params: { name: string }): Promise<CreateRepositoryResult> { | ||
| const { name } = params; | ||
|
|
||
| const token = getServiceGithubToken(); | ||
| if (!token) { | ||
| console.error("[createRepository] GITHUB_TOKEN missing"); | ||
| return { success: false, error: "GITHUB_TOKEN missing" }; | ||
| } | ||
|
|
||
| if (!/^[\w.-]+$/.test(name)) { | ||
| return { | ||
| success: false, | ||
| error: | ||
| "Invalid repository name. Use only letters, numbers, hyphens, underscores, and periods.", | ||
| }; | ||
| } | ||
|
|
||
| try { | ||
| const response = await fetch(`https://api.github.com/orgs/${RECOUPABLE_GITHUB_OWNER}/repos`, { | ||
| method: "POST", | ||
| headers: { | ||
| Accept: "application/vnd.github+json", | ||
| Authorization: `Bearer ${token}`, | ||
| "Content-Type": "application/json", | ||
| "X-GitHub-Api-Version": "2022-11-28", | ||
| }, | ||
| body: JSON.stringify({ | ||
| name, | ||
| private: true, | ||
| auto_init: true, | ||
| }), | ||
| }); | ||
|
|
||
| if (response.status === 201) { | ||
| const data = (await response.json()) as { html_url: string }; | ||
| return { success: true, repoUrl: data.html_url }; | ||
| } | ||
|
|
||
| if (response.status === 422) { | ||
| return { | ||
| success: false, | ||
| error: "Repository name already exists or is invalid", | ||
| }; | ||
| } | ||
| if (response.status === 403) { | ||
| return { success: false, error: "Permission denied" }; | ||
| } | ||
|
|
||
| let body = ""; | ||
| try { | ||
| body = await response.text(); | ||
| } catch { | ||
| body = ""; | ||
| } | ||
| console.error( | ||
| `[createRepository] unexpected status ${response.status} for ${RECOUPABLE_GITHUB_OWNER}/${name}: ${body}`, | ||
| ); | ||
| return { success: false, error: `GitHub returned ${response.status}` }; | ||
| } catch (error) { | ||
| console.error("[createRepository] network error:", error); | ||
| return { success: false, error: "Network error talking to GitHub" }; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| import { RECOUPABLE_GITHUB_OWNER } from "@/lib/recoupable/githubOwner"; | ||
| import { getServiceGithubToken } from "./getServiceGithubToken"; | ||
|
|
||
| /** | ||
| * Returns `true` if `recoupable/<repo>` exists, `false` if 404, `null` | ||
| * on any other failure (auth, rate limit, network, missing token). | ||
| * Lets callers distinguish "doesn't exist yet" from "couldn't reach | ||
| * GitHub" before attempting destructive ops like create. | ||
| * | ||
| * Owner is hard-coded to `recoupable` and the GitHub token is read | ||
| * from the environment (per PR #618 review — single source of truth). | ||
| */ | ||
| export async function repositoryExists(params: { repo: string }): Promise<boolean | null> { | ||
| const { repo } = params; | ||
|
|
||
| const token = getServiceGithubToken(); | ||
| if (!token) { | ||
| console.error("[repositoryExists] GITHUB_TOKEN missing"); | ||
| return null; | ||
| } | ||
|
|
||
| try { | ||
| const response = await fetch( | ||
| `https://api.github.com/repos/${RECOUPABLE_GITHUB_OWNER}/${repo}`, | ||
| { | ||
| method: "GET", | ||
| headers: { | ||
| Accept: "application/vnd.github+json", | ||
| Authorization: `Bearer ${token}`, | ||
| "X-GitHub-Api-Version": "2022-11-28", | ||
| }, | ||
| }, | ||
| ); | ||
|
|
||
| if (response.status === 200) return true; | ||
| if (response.status === 404) return false; | ||
|
|
||
| console.error( | ||
| `[repositoryExists] unexpected status ${response.status} for ${RECOUPABLE_GITHUB_OWNER}/${repo}`, | ||
| ); | ||
| return null; | ||
| } catch (error) { | ||
| console.error("[repositoryExists] network error:", error); | ||
| return null; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import { describe, it, expect, beforeEach, vi } from "vitest"; | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| import { ensurePersonalRepo } from "@/lib/recoupable/ensurePersonalRepo"; | ||
| import { repositoryExists } from "@/lib/github/repositoryExists"; | ||
| import { createRepository } from "@/lib/github/createRepository"; | ||
|
|
||
| vi.mock("@/lib/github/repositoryExists", () => ({ | ||
| repositoryExists: vi.fn(), | ||
| })); | ||
| vi.mock("@/lib/github/createRepository", () => ({ | ||
| createRepository: vi.fn(), | ||
| })); | ||
|
|
||
| const accountId = "fb678396-a68f-4294-ae50-b8cacf9ce77b"; | ||
|
|
||
| describe("ensurePersonalRepo", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| it("returns the existing repo URL when recoupable/<accountId> already exists", async () => { | ||
| vi.mocked(repositoryExists).mockResolvedValue(true); | ||
|
|
||
| const result = await ensurePersonalRepo({ accountId }); | ||
|
|
||
| expect(result).toBe(`https://github.com/recoupable/${accountId}`); | ||
| expect(createRepository).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns null when the existence check fails for non-404 reasons", async () => { | ||
| vi.mocked(repositoryExists).mockResolvedValue(null); | ||
|
|
||
| expect(await ensurePersonalRepo({ accountId })).toBeNull(); | ||
| expect(createRepository).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("creates a fresh repo when none exists and returns its URL", async () => { | ||
| vi.mocked(repositoryExists).mockResolvedValue(false); | ||
| vi.mocked(createRepository).mockResolvedValue({ | ||
| success: true, | ||
| repoUrl: `https://github.com/recoupable/${accountId}`, | ||
| }); | ||
|
|
||
| const result = await ensurePersonalRepo({ accountId }); | ||
|
|
||
| expect(createRepository).toHaveBeenCalledWith({ name: accountId }); | ||
| expect(result).toBe(`https://github.com/recoupable/${accountId}`); | ||
| }); | ||
|
|
||
| it("returns null when creation outright fails", async () => { | ||
| vi.mocked(repositoryExists).mockResolvedValue(false); | ||
| vi.mocked(createRepository).mockResolvedValue({ | ||
| success: false, | ||
| error: "Permission denied", | ||
| }); | ||
|
|
||
| expect(await ensurePersonalRepo({ accountId })).toBeNull(); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.