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
19 changes: 19 additions & 0 deletions app/api/sandbox/__tests__/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { describe, it, expect, vi } from "vitest";
import { NextRequest, NextResponse } from "next/server";

import { POST } from "@/app/api/sandbox/route";
import { createSandboxHandler } from "@/lib/sandbox/createSandboxHandler";

vi.mock("@/lib/sandbox/createSandboxHandler", () => ({
createSandboxHandler: vi.fn(async () => NextResponse.json({ ok: true }, { status: 200 })),
}));

describe("POST /api/sandbox route shell", () => {
it("delegates to createSandboxHandler", async () => {
const req = new NextRequest("http://localhost/api/sandbox", { method: "POST" });
const res = await POST(req);

expect(createSandboxHandler).toHaveBeenCalledWith(req);
expect(res.status).toBe(200);
});
});
29 changes: 29 additions & 0 deletions app/api/sandbox/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { NextRequest, NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { createSandboxHandler } from "@/lib/sandbox/createSandboxHandler";

/**
* OPTIONS handler for CORS preflight requests.
*
* @returns A NextResponse with CORS headers.
*/
export async function OPTIONS() {
return new NextResponse(null, {
status: 204,
headers: getCorsHeaders(),
});
}

/**
* `POST /api/sandbox` — provision (or resume) a Sandbox bound to a session.
*
* @param request - The incoming request.
* @returns A NextResponse with `{ createdAt, timeout, currentBranch, mode, timing }` on 200, or an error.
*/
export async function POST(request: NextRequest) {
return createSandboxHandler(request);
}

export const dynamic = "force-dynamic";
export const fetchCache = "force-no-store";
export const revalidate = 0;
21 changes: 21 additions & 0 deletions app/api/sandbox/status/__tests__/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, it, expect, vi } from "vitest";
import { NextRequest, NextResponse } from "next/server";

import { GET } from "@/app/api/sandbox/status/route";
import { getSandboxStatusHandler } from "@/lib/sandbox/getSandboxStatusHandler";

vi.mock("@/lib/sandbox/getSandboxStatusHandler", () => ({
getSandboxStatusHandler: vi.fn(async () => NextResponse.json({ ok: true }, { status: 200 })),
}));

describe("GET /api/sandbox/status route shell", () => {
it("delegates to getSandboxStatusHandler", async () => {
const req = new NextRequest("http://localhost/api/sandbox/status?sessionId=s", {
method: "GET",
});
const res = await GET(req);

expect(getSandboxStatusHandler).toHaveBeenCalledWith(req);
expect(res.status).toBe(200);
});
});
29 changes: 29 additions & 0 deletions app/api/sandbox/status/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { NextRequest, NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { getSandboxStatusHandler } from "@/lib/sandbox/getSandboxStatusHandler";

/**
* OPTIONS handler for CORS preflight requests.
*
* @returns A NextResponse with CORS headers.
*/
export async function OPTIONS() {
return new NextResponse(null, {
status: 204,
headers: getCorsHeaders(),
});
}

/**
* `GET /api/sandbox/status?sessionId=...` — current lifecycle/runtime state for the sandbox bound to a session.
*
* @param request - The incoming request.
* @returns A NextResponse with `{ status, hasSnapshot, lifecycleVersion, lifecycle }` on 200, or an error.
*/
export async function GET(request: NextRequest) {
return getSandboxStatusHandler(request);
}

export const dynamic = "force-dynamic";
export const fetchCache = "force-no-store";
export const revalidate = 0;
32 changes: 32 additions & 0 deletions lib/github/__tests__/getServiceGithubToken.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { getServiceGithubToken } from "@/lib/github/getServiceGithubToken";

const ORIGINAL = process.env.GITHUB_TOKEN;

beforeEach(() => {
delete process.env.GITHUB_TOKEN;
});

afterEach(() => {
if (ORIGINAL === undefined) {
delete process.env.GITHUB_TOKEN;
} else {
process.env.GITHUB_TOKEN = ORIGINAL;
}
});

describe("getServiceGithubToken", () => {
it("returns undefined when GITHUB_TOKEN is unset", () => {
expect(getServiceGithubToken()).toBeUndefined();
});

it("returns undefined when GITHUB_TOKEN is the empty string", () => {
process.env.GITHUB_TOKEN = "";
expect(getServiceGithubToken()).toBeUndefined();
});

it("returns the token when set", () => {
process.env.GITHUB_TOKEN = "ghs_secret";
expect(getServiceGithubToken()).toBe("ghs_secret");
});
});
12 changes: 12 additions & 0 deletions lib/github/getServiceGithubToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Returns the service-account GitHub token used for cloning private
* repositories into sandboxes. Returns undefined when the env var is
* unset or empty so callers can fall back to public-repo behavior
* without crashing.
*
* @returns The token string, or undefined.
*/
export function getServiceGithubToken(): string | undefined {
const token = process.env.GITHUB_TOKEN;
return token && token.length > 0 ? token : undefined;
}
42 changes: 42 additions & 0 deletions lib/sandbox/__tests__/buildLifecycle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, it, expect } from "vitest";
import { buildLifecycle } from "@/lib/sandbox/buildLifecycle";

const ISO = "2030-01-01T00:00:00.000Z";
const EPOCH = Date.parse(ISO);

describe("buildLifecycle", () => {
it("converts every ISO timestamp on the row to epoch ms and sets serverTime", () => {
const row = {
lifecycle_state: "active",
last_activity_at: ISO,
hibernate_after: ISO,
sandbox_expires_at: ISO,
} as any;

const result = buildLifecycle(row);

expect(result).toEqual({
serverTime: expect.any(Number),
state: "active",
lastActivityAt: EPOCH,
hibernateAfter: EPOCH,
sandboxExpiresAt: EPOCH,
});
});

it("preserves null fields and a null lifecycle_state as-is", () => {
const row = {
lifecycle_state: null,
last_activity_at: null,
hibernate_after: null,
sandbox_expires_at: null,
} as any;

const result = buildLifecycle(row);

expect(result.state).toBeNull();
expect(result.lastActivityAt).toBeNull();
expect(result.hibernateAfter).toBeNull();
expect(result.sandboxExpiresAt).toBeNull();
});
});
162 changes: 162 additions & 0 deletions lib/sandbox/__tests__/createSandboxHandler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest, NextResponse } from "next/server";

import { createSandboxHandler } from "@/lib/sandbox/createSandboxHandler";
import { validateCreateSandboxBody } from "@/lib/sandbox/validateCreateSandboxBody";
import { selectSessions } from "@/lib/supabase/sessions/selectSessions";
import { connectSandbox } from "@/lib/sandbox/factory";
import { updateSession } from "@/lib/supabase/sessions/updateSession";

vi.mock("@/lib/networking/getCorsHeaders", () => ({
getCorsHeaders: () => ({ "Access-Control-Allow-Origin": "*" }),
}));
vi.mock("@/lib/sandbox/validateCreateSandboxBody", () => ({
validateCreateSandboxBody: vi.fn(),
}));
vi.mock("@/lib/supabase/sessions/selectSessions", () => ({
selectSessions: vi.fn(),
}));
vi.mock("@/lib/sandbox/factory", () => ({
connectSandbox: vi.fn(),
}));
vi.mock("@/lib/supabase/sessions/updateSession", () => ({
updateSession: vi.fn(),
}));
vi.mock("@/lib/github/getServiceGithubToken", () => ({
getServiceGithubToken: vi.fn(() => "ghs_test_token"),
}));

const ACCOUNT_ID = "acc-1";

function makeReq(): NextRequest {
return new NextRequest("http://localhost/api/sandbox", { method: "POST" });
}

function fakeSandbox(overrides: Partial<Record<string, unknown>> = {}) {
return {
timeout: 1_800_000,
expiresAt: Date.parse("2030-01-01T00:00:00.000Z"),
currentBranch: "main",
getState: () => ({ type: "vercel", sandboxName: "session-sess-1" }),
...overrides,
};
}

describe("createSandboxHandler", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(validateCreateSandboxBody).mockResolvedValue({
body: {
repoUrl: "https://github.com/o/r",
sessionId: "sess-1",
},
auth: { accountId: ACCOUNT_ID, orgId: null, authToken: "k" },
});
vi.mocked(selectSessions).mockResolvedValue([{ id: "sess-1", account_id: ACCOUNT_ID } as any]);
vi.mocked(connectSandbox).mockResolvedValue(
fakeSandbox() as unknown as Awaited<ReturnType<typeof connectSandbox>>,
);
vi.mocked(updateSession).mockResolvedValue({} as any);
});

it("short-circuits with the validator's response on validation failure", async () => {
const fail = NextResponse.json({ status: "error", error: "bad" }, { status: 400 });
vi.mocked(validateCreateSandboxBody).mockResolvedValueOnce(fail);

const res = await createSandboxHandler(makeReq());

expect(res).toBe(fail);
expect(connectSandbox).not.toHaveBeenCalled();
});

it("returns 404 when sessionId is provided but the session does not exist", async () => {
vi.mocked(selectSessions).mockResolvedValueOnce([]);

const res = await createSandboxHandler(makeReq());

expect(res.status).toBe(404);
expect(connectSandbox).not.toHaveBeenCalled();
});

it("returns 403 when the session is not owned by the authenticated account", async () => {
vi.mocked(selectSessions).mockResolvedValueOnce([
{ id: "sess-1", account_id: "someone-else" } as any,
]);

const res = await createSandboxHandler(makeReq());

expect(res.status).toBe(403);
expect(connectSandbox).not.toHaveBeenCalled();
});

it("returns 502 when the sandbox provider throws", async () => {
vi.mocked(connectSandbox).mockRejectedValueOnce(new Error("vercel down"));

const res = await createSandboxHandler(makeReq());

expect(res.status).toBe(502);
});

it("returns 200 with the documented response shape on success", async () => {
const res = await createSandboxHandler(makeReq());

expect(res.status).toBe(200);
const body = await res.json();
expect(body).toMatchObject({
timeout: 1_800_000,
currentBranch: "main",
mode: "vercel",
});
expect(typeof body.createdAt).toBe("number");
expect(typeof body.timing.readyMs).toBe("number");
});

it("reports currentBranch from the sandbox handle (not request input)", async () => {
vi.mocked(connectSandbox).mockResolvedValueOnce(
fakeSandbox({ currentBranch: "release/v2" }) as unknown as Awaited<
ReturnType<typeof connectSandbox>
>,
);

const res = await createSandboxHandler(makeReq());

const body = await res.json();
expect(body.currentBranch).toBe("release/v2");
});

it("persists sandbox state and clears stale snapshot fields on the session row", async () => {
await createSandboxHandler(makeReq());

expect(updateSession).toHaveBeenCalledWith(
"sess-1",
expect.objectContaining({
sandbox_state: { type: "vercel", sandboxName: "session-sess-1" },
lifecycle_state: "active",
snapshot_url: null,
snapshot_created_at: null,
}),
);
});

it("plumbs the service github token into connectSandbox options", async () => {
await createSandboxHandler(makeReq());

const arg = vi.mocked(connectSandbox).mock.calls[0]?.[0];
expect(arg).toBeDefined();
if (!arg || !("options" in arg)) throw new Error("expected new-API config shape");
expect(arg.options?.githubToken).toBe("ghs_test_token");
});

it("skips the session-row write when no sessionId is provided", async () => {
vi.mocked(validateCreateSandboxBody).mockResolvedValueOnce({
body: { repoUrl: "https://github.com/o/r" },
auth: { accountId: ACCOUNT_ID, orgId: null, authToken: "k" },
});

const res = await createSandboxHandler(makeReq());

expect(res.status).toBe(200);
expect(updateSession).not.toHaveBeenCalled();
expect(selectSessions).not.toHaveBeenCalled();
});
});
Loading
Loading