Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions lib/github/__tests__/createRepository.test.ts
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);
});
});
61 changes: 61 additions & 0 deletions lib/github/__tests__/repositoryExists.test.ts
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();
});
});
95 changes: 95 additions & 0 deletions lib/github/createRepository.ts
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;
}
Comment thread
sweetmantech marked this conversation as resolved.

/**
* 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" };
}
}
46 changes: 46 additions & 0 deletions lib/github/repositoryExists.ts
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;
}
}
58 changes: 58 additions & 0 deletions lib/recoupable/__tests__/ensurePersonalRepo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
Comment thread
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();
});
});
12 changes: 12 additions & 0 deletions lib/recoupable/__tests__/extractOrgId.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,18 @@ describe("extractOrgId", () => {
);
});

it("extracts the UUID from a bare new-naming repo (recoupable/<uuid>)", () => {
expect(extractOrgId("https://github.com/recoupable/fb678396-a68f-4294-ae50-b8cacf9ce77b")).toBe(
"fb678396-a68f-4294-ae50-b8cacf9ce77b",
);
});

it("accepts a bare new-naming repo name", () => {
expect(extractOrgId("fb678396-a68f-4294-ae50-b8cacf9ce77b")).toBe(
"fb678396-a68f-4294-ae50-b8cacf9ce77b",
);
});

it("returns null for non-Recoupable clone URLs", () => {
expect(
extractOrgId(
Expand Down
Loading
Loading