From b3c1dd2964b5d8604738e1f4d433a50d94a5de8d Mon Sep 17 00:00:00 2001 From: Recoup Coding Agent Date: Fri, 27 Mar 2026 10:14:09 -0500 Subject: [PATCH 1/8] feat: add slack_installations table type, Supabase lib functions, and tests (#354) Add database types, CRUD operations (select by id/org, select by team id, upsert on team id conflict, delete by org), and unit tests for the slack_installations table to support Slack Marketplace distribution. Co-authored-by: CTO Agent Co-authored-by: Paperclip --- .../__tests__/deleteSlackInstallation.test.ts | 51 +++++++++++ .../__tests__/selectSlackInstallation.test.ts | 82 +++++++++++++++++ .../selectSlackInstallationByTeamId.test.ts | 70 +++++++++++++++ .../__tests__/upsertSlackInstallation.test.ts | 90 +++++++++++++++++++ .../deleteSlackInstallation.ts | 17 ++++ .../selectSlackInstallation.ts | 28 ++++++ .../selectSlackInstallationByTeamId.ts | 25 ++++++ .../upsertSlackInstallation.ts | 29 ++++++ types/database.types.ts | 48 ++++++++++ 9 files changed, 440 insertions(+) create mode 100644 lib/supabase/slack_installations/__tests__/deleteSlackInstallation.test.ts create mode 100644 lib/supabase/slack_installations/__tests__/selectSlackInstallation.test.ts create mode 100644 lib/supabase/slack_installations/__tests__/selectSlackInstallationByTeamId.test.ts create mode 100644 lib/supabase/slack_installations/__tests__/upsertSlackInstallation.test.ts create mode 100644 lib/supabase/slack_installations/deleteSlackInstallation.ts create mode 100644 lib/supabase/slack_installations/selectSlackInstallation.ts create mode 100644 lib/supabase/slack_installations/selectSlackInstallationByTeamId.ts create mode 100644 lib/supabase/slack_installations/upsertSlackInstallation.ts diff --git a/lib/supabase/slack_installations/__tests__/deleteSlackInstallation.test.ts b/lib/supabase/slack_installations/__tests__/deleteSlackInstallation.test.ts new file mode 100644 index 000000000..45ed83b90 --- /dev/null +++ b/lib/supabase/slack_installations/__tests__/deleteSlackInstallation.test.ts @@ -0,0 +1,51 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import { deleteSlackInstallation } from "../deleteSlackInstallation"; + +const mockFrom = vi.fn(); +const mockDelete = vi.fn(); +const mockEq = vi.fn(); + +vi.mock("@/lib/supabase/serverClient", () => ({ + default: { + from: (...args: unknown[]) => { + mockFrom(...args); + return { + delete: (...dArgs: unknown[]) => { + mockDelete(...dArgs); + return { + eq: (...eqArgs: unknown[]) => { + mockEq(...eqArgs); + return mockResult; + }, + }; + }, + }; + }, + }, +})); + +let mockResult: { error: { message: string } | null } = { error: null }; + +describe("deleteSlackInstallation", () => { + const orgId = "660e8400-e29b-41d4-a716-446655440000"; + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("deletes by organization_id", async () => { + await deleteSlackInstallation(orgId); + + expect(mockFrom).toHaveBeenCalledWith("slack_installations"); + expect(mockEq).toHaveBeenCalledWith("organization_id", orgId); + }); + + it("throws on error", async () => { + mockResult = { error: { message: "Delete failed" } }; + + await expect(deleteSlackInstallation(orgId)).rejects.toThrow( + "Failed to delete slack installation: Delete failed", + ); + }); +}); diff --git a/lib/supabase/slack_installations/__tests__/selectSlackInstallation.test.ts b/lib/supabase/slack_installations/__tests__/selectSlackInstallation.test.ts new file mode 100644 index 000000000..d5c1ad402 --- /dev/null +++ b/lib/supabase/slack_installations/__tests__/selectSlackInstallation.test.ts @@ -0,0 +1,82 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import { selectSlackInstallation } from "../selectSlackInstallation"; + +const mockFrom = vi.fn(); +const mockSelect = vi.fn(); +const mockEq = vi.fn(); +const mockMaybeSingle = vi.fn(); + +vi.mock("@/lib/supabase/serverClient", () => ({ + default: { + from: (...args: unknown[]) => { + mockFrom(...args); + return { + select: (...sArgs: unknown[]) => { + mockSelect(...sArgs); + return { + eq: (...eqArgs: unknown[]) => { + mockEq(...eqArgs); + return { maybeSingle: mockMaybeSingle }; + }, + }; + }, + }; + }, + }, +})); + +const mockInstallation = { + id: "550e8400-e29b-41d4-a716-446655440000", + slack_team_id: "T01234567", + slack_team_name: "Test Workspace", + organization_id: "660e8400-e29b-41d4-a716-446655440000", + bot_token: "xoxb-test-token", + installed_by: "770e8400-e29b-41d4-a716-446655440000", + created_at: "2026-03-27T00:00:00.000Z", + updated_at: "2026-03-27T00:00:00.000Z", +}; + +describe("selectSlackInstallation", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("selects by id", async () => { + mockMaybeSingle.mockResolvedValue({ data: mockInstallation, error: null }); + + const result = await selectSlackInstallation({ id: mockInstallation.id }); + + expect(mockFrom).toHaveBeenCalledWith("slack_installations"); + expect(mockEq).toHaveBeenCalledWith("id", mockInstallation.id); + expect(result).toEqual(mockInstallation); + }); + + it("selects by organizationId", async () => { + mockMaybeSingle.mockResolvedValue({ data: mockInstallation, error: null }); + + const result = await selectSlackInstallation({ + organizationId: mockInstallation.organization_id, + }); + + expect(mockFrom).toHaveBeenCalledWith("slack_installations"); + expect(mockEq).toHaveBeenCalledWith("organization_id", mockInstallation.organization_id); + expect(result).toEqual(mockInstallation); + }); + + it("returns null on error", async () => { + mockMaybeSingle.mockResolvedValue({ data: null, error: { message: "Error" } }); + + const result = await selectSlackInstallation({ id: "bad-id" }); + + expect(result).toBeNull(); + }); + + it("returns null when not found", async () => { + mockMaybeSingle.mockResolvedValue({ data: null, error: null }); + + const result = await selectSlackInstallation({ id: "missing" }); + + expect(result).toBeNull(); + }); +}); diff --git a/lib/supabase/slack_installations/__tests__/selectSlackInstallationByTeamId.test.ts b/lib/supabase/slack_installations/__tests__/selectSlackInstallationByTeamId.test.ts new file mode 100644 index 000000000..d46a30088 --- /dev/null +++ b/lib/supabase/slack_installations/__tests__/selectSlackInstallationByTeamId.test.ts @@ -0,0 +1,70 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import { selectSlackInstallationByTeamId } from "../selectSlackInstallationByTeamId"; + +const mockFrom = vi.fn(); +const mockSelect = vi.fn(); +const mockEq = vi.fn(); +const mockMaybeSingle = vi.fn(); + +vi.mock("@/lib/supabase/serverClient", () => ({ + default: { + from: (...args: unknown[]) => { + mockFrom(...args); + return { + select: (...sArgs: unknown[]) => { + mockSelect(...sArgs); + return { + eq: (...eqArgs: unknown[]) => { + mockEq(...eqArgs); + return { maybeSingle: mockMaybeSingle }; + }, + }; + }, + }; + }, + }, +})); + +const mockInstallation = { + id: "550e8400-e29b-41d4-a716-446655440000", + slack_team_id: "T01234567", + slack_team_name: "Test Workspace", + organization_id: "660e8400-e29b-41d4-a716-446655440000", + bot_token: "xoxb-test-token", + installed_by: "770e8400-e29b-41d4-a716-446655440000", + created_at: "2026-03-27T00:00:00.000Z", + updated_at: "2026-03-27T00:00:00.000Z", +}; + +describe("selectSlackInstallationByTeamId", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("selects by slack_team_id", async () => { + mockMaybeSingle.mockResolvedValue({ data: mockInstallation, error: null }); + + const result = await selectSlackInstallationByTeamId("T01234567"); + + expect(mockFrom).toHaveBeenCalledWith("slack_installations"); + expect(mockEq).toHaveBeenCalledWith("slack_team_id", "T01234567"); + expect(result).toEqual(mockInstallation); + }); + + it("returns null on error", async () => { + mockMaybeSingle.mockResolvedValue({ data: null, error: { message: "Error" } }); + + const result = await selectSlackInstallationByTeamId("bad-team"); + + expect(result).toBeNull(); + }); + + it("returns null when not found", async () => { + mockMaybeSingle.mockResolvedValue({ data: null, error: null }); + + const result = await selectSlackInstallationByTeamId("missing"); + + expect(result).toBeNull(); + }); +}); diff --git a/lib/supabase/slack_installations/__tests__/upsertSlackInstallation.test.ts b/lib/supabase/slack_installations/__tests__/upsertSlackInstallation.test.ts new file mode 100644 index 000000000..b5c684f64 --- /dev/null +++ b/lib/supabase/slack_installations/__tests__/upsertSlackInstallation.test.ts @@ -0,0 +1,90 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import { upsertSlackInstallation } from "../upsertSlackInstallation"; + +const mockFrom = vi.fn(); +const mockUpsert = vi.fn(); +const mockSelect = vi.fn(); +const mockSingle = vi.fn(); + +vi.mock("@/lib/supabase/serverClient", () => ({ + default: { + from: (...args: unknown[]) => { + mockFrom(...args); + return { + upsert: (...uArgs: unknown[]) => { + mockUpsert(...uArgs); + return { + select: (...sArgs: unknown[]) => { + mockSelect(...sArgs); + return { single: mockSingle }; + }, + }; + }, + }; + }, + }, +})); + +const mockInstallation = { + id: "550e8400-e29b-41d4-a716-446655440000", + slack_team_id: "T01234567", + slack_team_name: "Test Workspace", + organization_id: "660e8400-e29b-41d4-a716-446655440000", + bot_token: "xoxb-test-token", + installed_by: "770e8400-e29b-41d4-a716-446655440000", + created_at: "2026-03-27T00:00:00.000Z", + updated_at: "2026-03-27T00:00:00.000Z", +}; + +describe("upsertSlackInstallation", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("upserts with slack_team_id conflict", async () => { + mockSingle.mockResolvedValue({ data: mockInstallation, error: null }); + + const input = { + slack_team_id: "T01234567", + slack_team_name: "Test Workspace", + organization_id: "660e8400-e29b-41d4-a716-446655440000", + bot_token: "xoxb-test-token", + installed_by: "770e8400-e29b-41d4-a716-446655440000", + }; + + const result = await upsertSlackInstallation(input); + + expect(mockFrom).toHaveBeenCalledWith("slack_installations"); + expect(mockUpsert).toHaveBeenCalledWith(input, { onConflict: "slack_team_id" }); + expect(result).toEqual(mockInstallation); + }); + + it("throws on error", async () => { + mockSingle.mockResolvedValue({ data: null, error: { message: "Conflict" } }); + + await expect( + upsertSlackInstallation({ + slack_team_id: "T01234567", + slack_team_name: "Test", + organization_id: "org-id", + bot_token: "token", + installed_by: "user-id", + }), + ).rejects.toThrow("Failed to upsert slack installation: Conflict"); + }); + + it("throws when no data returned", async () => { + mockSingle.mockResolvedValue({ data: null, error: null }); + + await expect( + upsertSlackInstallation({ + slack_team_id: "T01234567", + slack_team_name: "Test", + organization_id: "org-id", + bot_token: "token", + installed_by: "user-id", + }), + ).rejects.toThrow("Failed to upsert slack installation: No data returned"); + }); +}); diff --git a/lib/supabase/slack_installations/deleteSlackInstallation.ts b/lib/supabase/slack_installations/deleteSlackInstallation.ts new file mode 100644 index 000000000..6a69baef6 --- /dev/null +++ b/lib/supabase/slack_installations/deleteSlackInstallation.ts @@ -0,0 +1,17 @@ +import supabase from "../serverClient"; + +/** + * Delete a slack installation by organization_id. + * + * @param organizationId - The organization UUID to delete the installation for + */ +export async function deleteSlackInstallation(organizationId: string): Promise { + const { error } = await supabase + .from("slack_installations") + .delete() + .eq("organization_id", organizationId); + + if (error) { + throw new Error(`Failed to delete slack installation: ${error.message}`); + } +} diff --git a/lib/supabase/slack_installations/selectSlackInstallation.ts b/lib/supabase/slack_installations/selectSlackInstallation.ts new file mode 100644 index 000000000..350cae3ad --- /dev/null +++ b/lib/supabase/slack_installations/selectSlackInstallation.ts @@ -0,0 +1,28 @@ +import supabase from "../serverClient"; +import type { Tables } from "@/types/database.types"; + +/** + * Select a slack installation by id or organization_id. + * + * @param params - Either { id } or { organizationId } + * @returns The matching slack installation, or null if not found + */ +export async function selectSlackInstallation( + params: { id: string } | { organizationId: string }, +): Promise | null> { + let query = supabase.from("slack_installations").select("*"); + + if ("id" in params) { + query = query.eq("id", params.id); + } else { + query = query.eq("organization_id", params.organizationId); + } + + const { data, error } = await query.maybeSingle(); + + if (error) { + return null; + } + + return data; +} diff --git a/lib/supabase/slack_installations/selectSlackInstallationByTeamId.ts b/lib/supabase/slack_installations/selectSlackInstallationByTeamId.ts new file mode 100644 index 000000000..5cab5a4c1 --- /dev/null +++ b/lib/supabase/slack_installations/selectSlackInstallationByTeamId.ts @@ -0,0 +1,25 @@ +import supabase from "../serverClient"; +import type { Tables } from "@/types/database.types"; + +/** + * Select a slack installation by slack_team_id. + * Used in artist resolution to find the linked organization. + * + * @param slackTeamId - The Slack workspace team ID + * @returns The matching slack installation, or null if not found + */ +export async function selectSlackInstallationByTeamId( + slackTeamId: string, +): Promise | null> { + const { data, error } = await supabase + .from("slack_installations") + .select("*") + .eq("slack_team_id", slackTeamId) + .maybeSingle(); + + if (error) { + return null; + } + + return data; +} diff --git a/lib/supabase/slack_installations/upsertSlackInstallation.ts b/lib/supabase/slack_installations/upsertSlackInstallation.ts new file mode 100644 index 000000000..24ccfa43f --- /dev/null +++ b/lib/supabase/slack_installations/upsertSlackInstallation.ts @@ -0,0 +1,29 @@ +import supabase from "../serverClient"; +import type { Tables, TablesInsert } from "@/types/database.types"; + +/** + * Upsert a slack installation, using slack_team_id as the conflict column. + * If a row with the same slack_team_id exists, it will be updated. + * + * @param installation - The slack installation data to upsert + * @returns The upserted slack installation + */ +export async function upsertSlackInstallation( + installation: TablesInsert<"slack_installations">, +): Promise> { + const { data, error } = await supabase + .from("slack_installations") + .upsert(installation, { onConflict: "slack_team_id" }) + .select() + .single(); + + if (error) { + throw new Error(`Failed to upsert slack installation: ${error.message}`); + } + + if (!data) { + throw new Error("Failed to upsert slack installation: No data returned"); + } + + return data; +} diff --git a/types/database.types.ts b/types/database.types.ts index 50b0a8ef6..bd5bf92e0 100644 --- a/types/database.types.ts +++ b/types/database.types.ts @@ -2763,6 +2763,54 @@ export type Database = { }; Relationships: []; }; + slack_installations: { + Row: { + id: string; + slack_team_id: string; + slack_team_name: string; + organization_id: string; + bot_token: string; + installed_by: string; + created_at: string; + updated_at: string; + }; + Insert: { + id?: string; + slack_team_id: string; + slack_team_name: string; + organization_id: string; + bot_token: string; + installed_by: string; + created_at?: string; + updated_at?: string; + }; + Update: { + id?: string; + slack_team_id?: string; + slack_team_name?: string; + organization_id?: string; + bot_token?: string; + installed_by?: string; + created_at?: string; + updated_at?: string; + }; + Relationships: [ + { + foreignKeyName: "slack_installations_organization_id_fkey"; + columns: ["organization_id"]; + isOneToOne: false; + referencedRelation: "accounts"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "slack_installations_installed_by_fkey"; + columns: ["installed_by"]; + isOneToOne: false; + referencedRelation: "accounts"; + referencedColumns: ["id"]; + }, + ]; + }; social_fans: { Row: { artist_social_id: string; From c52f20f3e16313f98ac2722a3a1489cb814fd682 Mon Sep 17 00:00:00 2001 From: CTO Agent Date: Fri, 27 Mar 2026 15:44:47 +0000 Subject: [PATCH 2/8] feat: add POST /api/sandboxes/files endpoint for file uploads to GitHub repos Adds a new API endpoint that accepts multipart form data to upload files to the authenticated account's sandbox GitHub repository. Supports submodule path resolution so files targeting submodule directories are committed to the correct repository. Co-Authored-By: Paperclip --- app/api/sandboxes/files/route.ts | 46 ++++++++++ lib/github/createOrUpdateFileContent.ts | 87 ++++++++++++++++++ lib/sandbox/postSandboxesFilesHandler.ts | 88 +++++++++++++++++++ .../validatePostSandboxesFilesRequest.ts | 86 ++++++++++++++++++ 4 files changed, 307 insertions(+) create mode 100644 app/api/sandboxes/files/route.ts create mode 100644 lib/github/createOrUpdateFileContent.ts create mode 100644 lib/sandbox/postSandboxesFilesHandler.ts create mode 100644 lib/sandbox/validatePostSandboxesFilesRequest.ts diff --git a/app/api/sandboxes/files/route.ts b/app/api/sandboxes/files/route.ts new file mode 100644 index 000000000..92426f5b6 --- /dev/null +++ b/app/api/sandboxes/files/route.ts @@ -0,0 +1,46 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { postSandboxesFilesHandler } from "@/lib/sandbox/postSandboxesFilesHandler"; + +/** + * OPTIONS handler for CORS preflight requests. + * + * @returns A NextResponse with CORS headers. + */ +export async function OPTIONS() { + return new NextResponse(null, { + status: 200, + headers: getCorsHeaders(), + }); +} + +/** + * POST /api/sandboxes/files + * + * Uploads one or more files to the authenticated account's sandbox GitHub + * repository. Accepts multipart form data with files and an optional target + * directory path. Resolves submodule paths so files in submodule directories + * are committed to the correct repository. + * + * Authentication: x-api-key header or Authorization Bearer token required. + * + * Form data: + * - files: File[] (required) - One or more files to upload + * - path: string (optional) - Target directory path within the repository + * - message: string (optional) - Commit message (defaults to "Upload files via API") + * + * Response (200): + * - status: "success" + * - uploaded: Array<{ path: string, sha: string }> + * + * Error (400/401/403/404/500): + * - status: "error" + * - error: string + * + * @param request - The request object + * @returns A NextResponse with uploaded file details or error + */ +export async function POST(request: NextRequest): Promise { + return postSandboxesFilesHandler(request); +} diff --git a/lib/github/createOrUpdateFileContent.ts b/lib/github/createOrUpdateFileContent.ts new file mode 100644 index 000000000..5ef2a1b9a --- /dev/null +++ b/lib/github/createOrUpdateFileContent.ts @@ -0,0 +1,87 @@ +import { parseGitHubRepoUrl } from "./parseGitHubRepoUrl"; + +export interface CreateFileResult { + path: string; + sha: string; +} + +/** + * Creates or updates a file in a GitHub repository using the Contents API. + * + * @param params - The parameters for file creation + * @param params.githubRepo - The full GitHub repository URL + * @param params.path - The file path within the repository + * @param params.content - The file content as a Buffer + * @param params.message - The commit message + * @returns The created file path and SHA, or an error + */ +export async function createOrUpdateFileContent({ + githubRepo, + path, + content, + message, +}: { + githubRepo: string; + path: string; + content: Buffer; + message: string; +}): Promise { + const repoInfo = parseGitHubRepoUrl(githubRepo); + if (!repoInfo) { + return { error: "Invalid GitHub repository URL" }; + } + + const { owner, repo } = repoInfo; + const token = process.env.GITHUB_TOKEN; + + if (!token) { + return { error: "GitHub token not configured" }; + } + + const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`; + + // Check if file already exists to get its SHA for updates + let existingSha: string | undefined; + const getResponse = await fetch(url, { + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/vnd.github.v3+json", + }, + }); + + if (getResponse.ok) { + const existing = await getResponse.json(); + existingSha = existing.sha; + } + + const body: Record = { + message, + content: content.toString("base64"), + branch: "main", + }; + + if (existingSha) { + body.sha = existingSha; + } + + const response = await fetch(url, { + method: "PUT", + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/vnd.github.v3+json", + "Content-Type": "application/json", + }, + body: JSON.stringify(body), + }); + + if (!response.ok) { + const errorText = await response.text(); + return { error: `Failed to upload file: ${response.status} ${errorText}` }; + } + + const result = await response.json(); + return { + path: result.content.path, + sha: result.content.sha, + }; +} diff --git a/lib/sandbox/postSandboxesFilesHandler.ts b/lib/sandbox/postSandboxesFilesHandler.ts new file mode 100644 index 000000000..17dd65fa3 --- /dev/null +++ b/lib/sandbox/postSandboxesFilesHandler.ts @@ -0,0 +1,88 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { validatePostSandboxesFilesRequest } from "./validatePostSandboxesFilesRequest"; +import { selectAccountSnapshots } from "@/lib/supabase/account_snapshots/selectAccountSnapshots"; +import { resolveSubmodulePath } from "@/lib/github/resolveSubmodulePath"; +import { createOrUpdateFileContent } from "@/lib/github/createOrUpdateFileContent"; +import type { CreateFileResult } from "@/lib/github/createOrUpdateFileContent"; + +/** + * Handler for uploading files to a sandbox's GitHub repository. + * Requires authentication via x-api-key header or Authorization bearer token. + * + * Accepts multipart form data with: + * - files: One or more files to upload + * - path: Target directory path within the repository (optional, defaults to root) + * - message: Commit message (optional, defaults to "Upload files via API") + * + * Resolves submodule paths so files in submodule directories are committed + * to the correct submodule repository. + * + * @param request - The request object + * @returns A NextResponse with uploaded file details or error + */ +export async function postSandboxesFilesHandler(request: NextRequest): Promise { + const validated = await validatePostSandboxesFilesRequest(request); + if (validated instanceof NextResponse) { + return validated; + } + + const { accountIds, orgId, path, message, files } = validated; + + const snapshotAccountId = accountIds?.length === 1 ? accountIds[0] : orgId; + + if (!snapshotAccountId) { + return NextResponse.json( + { status: "error", error: "Could not determine account for snapshot lookup" }, + { status: 404, headers: getCorsHeaders() }, + ); + } + + const snapshots = await selectAccountSnapshots(snapshotAccountId); + const githubRepo = snapshots[0]?.github_repo ?? null; + + if (!githubRepo) { + return NextResponse.json( + { status: "error", error: "No GitHub repository found for this account" }, + { status: 404, headers: getCorsHeaders() }, + ); + } + + const uploaded: CreateFileResult[] = []; + const errors: string[] = []; + + for (const file of files) { + const filePath = path ? `${path}/${file.name}` : file.name; + + const resolved = await resolveSubmodulePath({ githubRepo, path: filePath }); + + const result = await createOrUpdateFileContent({ + githubRepo: resolved.githubRepo, + path: resolved.path, + content: file.content, + message, + }); + + if ("error" in result) { + errors.push(`${file.name}: ${result.error}`); + } else { + uploaded.push(result); + } + } + + if (uploaded.length === 0) { + return NextResponse.json( + { status: "error", error: `All uploads failed: ${errors.join("; ")}` }, + { status: 500, headers: getCorsHeaders() }, + ); + } + + return NextResponse.json( + { + status: "success", + uploaded, + ...(errors.length > 0 && { errors }), + }, + { status: 200, headers: getCorsHeaders() }, + ); +} diff --git a/lib/sandbox/validatePostSandboxesFilesRequest.ts b/lib/sandbox/validatePostSandboxesFilesRequest.ts new file mode 100644 index 000000000..22e9768f7 --- /dev/null +++ b/lib/sandbox/validatePostSandboxesFilesRequest.ts @@ -0,0 +1,86 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { validateAuthContext } from "@/lib/auth/validateAuthContext"; +import { buildGetSandboxesParams } from "./buildGetSandboxesParams"; + +export interface ValidatedPostSandboxesFilesParams { + accountIds?: string[]; + orgId?: string; + path: string; + message: string; + files: { name: string; content: Buffer }[]; +} + +/** + * Validates POST /api/sandboxes/files request. + * Handles authentication and multipart form data parsing. + * + * @param request - The NextRequest object + * @returns A NextResponse with an error if validation fails, or validated params + */ +export async function validatePostSandboxesFilesRequest( + request: NextRequest, +): Promise { + const authResult = await validateAuthContext(request); + if (authResult instanceof NextResponse) { + return authResult; + } + + const { accountId, orgId } = authResult; + + const { params, error } = await buildGetSandboxesParams({ + account_id: accountId, + }); + + if (error) { + return NextResponse.json( + { status: "error", error }, + { status: 403, headers: getCorsHeaders() }, + ); + } + + let formData: FormData; + try { + formData = await request.formData(); + } catch { + return NextResponse.json( + { status: "error", error: "Request must be multipart/form-data" }, + { status: 400, headers: getCorsHeaders() }, + ); + } + + const path = (formData.get("path") as string) ?? ""; + const message = (formData.get("message") as string) ?? "Upload files via API"; + + const fileEntries = formData.getAll("files"); + if (!fileEntries.length) { + return NextResponse.json( + { status: "error", missing_fields: ["files"], error: "At least one file is required" }, + { status: 400, headers: getCorsHeaders() }, + ); + } + + const files: { name: string; content: Buffer }[] = []; + for (const entry of fileEntries) { + if (!(entry instanceof File)) { + return NextResponse.json( + { status: "error", error: "Invalid file entry" }, + { status: 400, headers: getCorsHeaders() }, + ); + } + const arrayBuffer = await entry.arrayBuffer(); + files.push({ + name: entry.name, + content: Buffer.from(arrayBuffer), + }); + } + + return { + accountIds: params.accountIds, + orgId: orgId ?? undefined, + path, + message, + files, + }; +} From 3357bf61746cb6eef5414e932d43ef67c3df3525 Mon Sep 17 00:00:00 2001 From: "sweetman.eth" Date: Fri, 27 Mar 2026 10:50:42 -0500 Subject: [PATCH 3/8] Revert "feat: add slack_installations table type, Supabase lib functions, and tests (#354)" (#356) This reverts commit b3c1dd2964b5d8604738e1f4d433a50d94a5de8d. --- .../__tests__/deleteSlackInstallation.test.ts | 51 ----------- .../__tests__/selectSlackInstallation.test.ts | 82 ----------------- .../selectSlackInstallationByTeamId.test.ts | 70 --------------- .../__tests__/upsertSlackInstallation.test.ts | 90 ------------------- .../deleteSlackInstallation.ts | 17 ---- .../selectSlackInstallation.ts | 28 ------ .../selectSlackInstallationByTeamId.ts | 25 ------ .../upsertSlackInstallation.ts | 29 ------ types/database.types.ts | 48 ---------- 9 files changed, 440 deletions(-) delete mode 100644 lib/supabase/slack_installations/__tests__/deleteSlackInstallation.test.ts delete mode 100644 lib/supabase/slack_installations/__tests__/selectSlackInstallation.test.ts delete mode 100644 lib/supabase/slack_installations/__tests__/selectSlackInstallationByTeamId.test.ts delete mode 100644 lib/supabase/slack_installations/__tests__/upsertSlackInstallation.test.ts delete mode 100644 lib/supabase/slack_installations/deleteSlackInstallation.ts delete mode 100644 lib/supabase/slack_installations/selectSlackInstallation.ts delete mode 100644 lib/supabase/slack_installations/selectSlackInstallationByTeamId.ts delete mode 100644 lib/supabase/slack_installations/upsertSlackInstallation.ts diff --git a/lib/supabase/slack_installations/__tests__/deleteSlackInstallation.test.ts b/lib/supabase/slack_installations/__tests__/deleteSlackInstallation.test.ts deleted file mode 100644 index 45ed83b90..000000000 --- a/lib/supabase/slack_installations/__tests__/deleteSlackInstallation.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -import { deleteSlackInstallation } from "../deleteSlackInstallation"; - -const mockFrom = vi.fn(); -const mockDelete = vi.fn(); -const mockEq = vi.fn(); - -vi.mock("@/lib/supabase/serverClient", () => ({ - default: { - from: (...args: unknown[]) => { - mockFrom(...args); - return { - delete: (...dArgs: unknown[]) => { - mockDelete(...dArgs); - return { - eq: (...eqArgs: unknown[]) => { - mockEq(...eqArgs); - return mockResult; - }, - }; - }, - }; - }, - }, -})); - -let mockResult: { error: { message: string } | null } = { error: null }; - -describe("deleteSlackInstallation", () => { - const orgId = "660e8400-e29b-41d4-a716-446655440000"; - - beforeEach(() => { - vi.clearAllMocks(); - }); - - it("deletes by organization_id", async () => { - await deleteSlackInstallation(orgId); - - expect(mockFrom).toHaveBeenCalledWith("slack_installations"); - expect(mockEq).toHaveBeenCalledWith("organization_id", orgId); - }); - - it("throws on error", async () => { - mockResult = { error: { message: "Delete failed" } }; - - await expect(deleteSlackInstallation(orgId)).rejects.toThrow( - "Failed to delete slack installation: Delete failed", - ); - }); -}); diff --git a/lib/supabase/slack_installations/__tests__/selectSlackInstallation.test.ts b/lib/supabase/slack_installations/__tests__/selectSlackInstallation.test.ts deleted file mode 100644 index d5c1ad402..000000000 --- a/lib/supabase/slack_installations/__tests__/selectSlackInstallation.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -import { selectSlackInstallation } from "../selectSlackInstallation"; - -const mockFrom = vi.fn(); -const mockSelect = vi.fn(); -const mockEq = vi.fn(); -const mockMaybeSingle = vi.fn(); - -vi.mock("@/lib/supabase/serverClient", () => ({ - default: { - from: (...args: unknown[]) => { - mockFrom(...args); - return { - select: (...sArgs: unknown[]) => { - mockSelect(...sArgs); - return { - eq: (...eqArgs: unknown[]) => { - mockEq(...eqArgs); - return { maybeSingle: mockMaybeSingle }; - }, - }; - }, - }; - }, - }, -})); - -const mockInstallation = { - id: "550e8400-e29b-41d4-a716-446655440000", - slack_team_id: "T01234567", - slack_team_name: "Test Workspace", - organization_id: "660e8400-e29b-41d4-a716-446655440000", - bot_token: "xoxb-test-token", - installed_by: "770e8400-e29b-41d4-a716-446655440000", - created_at: "2026-03-27T00:00:00.000Z", - updated_at: "2026-03-27T00:00:00.000Z", -}; - -describe("selectSlackInstallation", () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - it("selects by id", async () => { - mockMaybeSingle.mockResolvedValue({ data: mockInstallation, error: null }); - - const result = await selectSlackInstallation({ id: mockInstallation.id }); - - expect(mockFrom).toHaveBeenCalledWith("slack_installations"); - expect(mockEq).toHaveBeenCalledWith("id", mockInstallation.id); - expect(result).toEqual(mockInstallation); - }); - - it("selects by organizationId", async () => { - mockMaybeSingle.mockResolvedValue({ data: mockInstallation, error: null }); - - const result = await selectSlackInstallation({ - organizationId: mockInstallation.organization_id, - }); - - expect(mockFrom).toHaveBeenCalledWith("slack_installations"); - expect(mockEq).toHaveBeenCalledWith("organization_id", mockInstallation.organization_id); - expect(result).toEqual(mockInstallation); - }); - - it("returns null on error", async () => { - mockMaybeSingle.mockResolvedValue({ data: null, error: { message: "Error" } }); - - const result = await selectSlackInstallation({ id: "bad-id" }); - - expect(result).toBeNull(); - }); - - it("returns null when not found", async () => { - mockMaybeSingle.mockResolvedValue({ data: null, error: null }); - - const result = await selectSlackInstallation({ id: "missing" }); - - expect(result).toBeNull(); - }); -}); diff --git a/lib/supabase/slack_installations/__tests__/selectSlackInstallationByTeamId.test.ts b/lib/supabase/slack_installations/__tests__/selectSlackInstallationByTeamId.test.ts deleted file mode 100644 index d46a30088..000000000 --- a/lib/supabase/slack_installations/__tests__/selectSlackInstallationByTeamId.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -import { selectSlackInstallationByTeamId } from "../selectSlackInstallationByTeamId"; - -const mockFrom = vi.fn(); -const mockSelect = vi.fn(); -const mockEq = vi.fn(); -const mockMaybeSingle = vi.fn(); - -vi.mock("@/lib/supabase/serverClient", () => ({ - default: { - from: (...args: unknown[]) => { - mockFrom(...args); - return { - select: (...sArgs: unknown[]) => { - mockSelect(...sArgs); - return { - eq: (...eqArgs: unknown[]) => { - mockEq(...eqArgs); - return { maybeSingle: mockMaybeSingle }; - }, - }; - }, - }; - }, - }, -})); - -const mockInstallation = { - id: "550e8400-e29b-41d4-a716-446655440000", - slack_team_id: "T01234567", - slack_team_name: "Test Workspace", - organization_id: "660e8400-e29b-41d4-a716-446655440000", - bot_token: "xoxb-test-token", - installed_by: "770e8400-e29b-41d4-a716-446655440000", - created_at: "2026-03-27T00:00:00.000Z", - updated_at: "2026-03-27T00:00:00.000Z", -}; - -describe("selectSlackInstallationByTeamId", () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - it("selects by slack_team_id", async () => { - mockMaybeSingle.mockResolvedValue({ data: mockInstallation, error: null }); - - const result = await selectSlackInstallationByTeamId("T01234567"); - - expect(mockFrom).toHaveBeenCalledWith("slack_installations"); - expect(mockEq).toHaveBeenCalledWith("slack_team_id", "T01234567"); - expect(result).toEqual(mockInstallation); - }); - - it("returns null on error", async () => { - mockMaybeSingle.mockResolvedValue({ data: null, error: { message: "Error" } }); - - const result = await selectSlackInstallationByTeamId("bad-team"); - - expect(result).toBeNull(); - }); - - it("returns null when not found", async () => { - mockMaybeSingle.mockResolvedValue({ data: null, error: null }); - - const result = await selectSlackInstallationByTeamId("missing"); - - expect(result).toBeNull(); - }); -}); diff --git a/lib/supabase/slack_installations/__tests__/upsertSlackInstallation.test.ts b/lib/supabase/slack_installations/__tests__/upsertSlackInstallation.test.ts deleted file mode 100644 index b5c684f64..000000000 --- a/lib/supabase/slack_installations/__tests__/upsertSlackInstallation.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -import { upsertSlackInstallation } from "../upsertSlackInstallation"; - -const mockFrom = vi.fn(); -const mockUpsert = vi.fn(); -const mockSelect = vi.fn(); -const mockSingle = vi.fn(); - -vi.mock("@/lib/supabase/serverClient", () => ({ - default: { - from: (...args: unknown[]) => { - mockFrom(...args); - return { - upsert: (...uArgs: unknown[]) => { - mockUpsert(...uArgs); - return { - select: (...sArgs: unknown[]) => { - mockSelect(...sArgs); - return { single: mockSingle }; - }, - }; - }, - }; - }, - }, -})); - -const mockInstallation = { - id: "550e8400-e29b-41d4-a716-446655440000", - slack_team_id: "T01234567", - slack_team_name: "Test Workspace", - organization_id: "660e8400-e29b-41d4-a716-446655440000", - bot_token: "xoxb-test-token", - installed_by: "770e8400-e29b-41d4-a716-446655440000", - created_at: "2026-03-27T00:00:00.000Z", - updated_at: "2026-03-27T00:00:00.000Z", -}; - -describe("upsertSlackInstallation", () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - it("upserts with slack_team_id conflict", async () => { - mockSingle.mockResolvedValue({ data: mockInstallation, error: null }); - - const input = { - slack_team_id: "T01234567", - slack_team_name: "Test Workspace", - organization_id: "660e8400-e29b-41d4-a716-446655440000", - bot_token: "xoxb-test-token", - installed_by: "770e8400-e29b-41d4-a716-446655440000", - }; - - const result = await upsertSlackInstallation(input); - - expect(mockFrom).toHaveBeenCalledWith("slack_installations"); - expect(mockUpsert).toHaveBeenCalledWith(input, { onConflict: "slack_team_id" }); - expect(result).toEqual(mockInstallation); - }); - - it("throws on error", async () => { - mockSingle.mockResolvedValue({ data: null, error: { message: "Conflict" } }); - - await expect( - upsertSlackInstallation({ - slack_team_id: "T01234567", - slack_team_name: "Test", - organization_id: "org-id", - bot_token: "token", - installed_by: "user-id", - }), - ).rejects.toThrow("Failed to upsert slack installation: Conflict"); - }); - - it("throws when no data returned", async () => { - mockSingle.mockResolvedValue({ data: null, error: null }); - - await expect( - upsertSlackInstallation({ - slack_team_id: "T01234567", - slack_team_name: "Test", - organization_id: "org-id", - bot_token: "token", - installed_by: "user-id", - }), - ).rejects.toThrow("Failed to upsert slack installation: No data returned"); - }); -}); diff --git a/lib/supabase/slack_installations/deleteSlackInstallation.ts b/lib/supabase/slack_installations/deleteSlackInstallation.ts deleted file mode 100644 index 6a69baef6..000000000 --- a/lib/supabase/slack_installations/deleteSlackInstallation.ts +++ /dev/null @@ -1,17 +0,0 @@ -import supabase from "../serverClient"; - -/** - * Delete a slack installation by organization_id. - * - * @param organizationId - The organization UUID to delete the installation for - */ -export async function deleteSlackInstallation(organizationId: string): Promise { - const { error } = await supabase - .from("slack_installations") - .delete() - .eq("organization_id", organizationId); - - if (error) { - throw new Error(`Failed to delete slack installation: ${error.message}`); - } -} diff --git a/lib/supabase/slack_installations/selectSlackInstallation.ts b/lib/supabase/slack_installations/selectSlackInstallation.ts deleted file mode 100644 index 350cae3ad..000000000 --- a/lib/supabase/slack_installations/selectSlackInstallation.ts +++ /dev/null @@ -1,28 +0,0 @@ -import supabase from "../serverClient"; -import type { Tables } from "@/types/database.types"; - -/** - * Select a slack installation by id or organization_id. - * - * @param params - Either { id } or { organizationId } - * @returns The matching slack installation, or null if not found - */ -export async function selectSlackInstallation( - params: { id: string } | { organizationId: string }, -): Promise | null> { - let query = supabase.from("slack_installations").select("*"); - - if ("id" in params) { - query = query.eq("id", params.id); - } else { - query = query.eq("organization_id", params.organizationId); - } - - const { data, error } = await query.maybeSingle(); - - if (error) { - return null; - } - - return data; -} diff --git a/lib/supabase/slack_installations/selectSlackInstallationByTeamId.ts b/lib/supabase/slack_installations/selectSlackInstallationByTeamId.ts deleted file mode 100644 index 5cab5a4c1..000000000 --- a/lib/supabase/slack_installations/selectSlackInstallationByTeamId.ts +++ /dev/null @@ -1,25 +0,0 @@ -import supabase from "../serverClient"; -import type { Tables } from "@/types/database.types"; - -/** - * Select a slack installation by slack_team_id. - * Used in artist resolution to find the linked organization. - * - * @param slackTeamId - The Slack workspace team ID - * @returns The matching slack installation, or null if not found - */ -export async function selectSlackInstallationByTeamId( - slackTeamId: string, -): Promise | null> { - const { data, error } = await supabase - .from("slack_installations") - .select("*") - .eq("slack_team_id", slackTeamId) - .maybeSingle(); - - if (error) { - return null; - } - - return data; -} diff --git a/lib/supabase/slack_installations/upsertSlackInstallation.ts b/lib/supabase/slack_installations/upsertSlackInstallation.ts deleted file mode 100644 index 24ccfa43f..000000000 --- a/lib/supabase/slack_installations/upsertSlackInstallation.ts +++ /dev/null @@ -1,29 +0,0 @@ -import supabase from "../serverClient"; -import type { Tables, TablesInsert } from "@/types/database.types"; - -/** - * Upsert a slack installation, using slack_team_id as the conflict column. - * If a row with the same slack_team_id exists, it will be updated. - * - * @param installation - The slack installation data to upsert - * @returns The upserted slack installation - */ -export async function upsertSlackInstallation( - installation: TablesInsert<"slack_installations">, -): Promise> { - const { data, error } = await supabase - .from("slack_installations") - .upsert(installation, { onConflict: "slack_team_id" }) - .select() - .single(); - - if (error) { - throw new Error(`Failed to upsert slack installation: ${error.message}`); - } - - if (!data) { - throw new Error("Failed to upsert slack installation: No data returned"); - } - - return data; -} diff --git a/types/database.types.ts b/types/database.types.ts index bd5bf92e0..50b0a8ef6 100644 --- a/types/database.types.ts +++ b/types/database.types.ts @@ -2763,54 +2763,6 @@ export type Database = { }; Relationships: []; }; - slack_installations: { - Row: { - id: string; - slack_team_id: string; - slack_team_name: string; - organization_id: string; - bot_token: string; - installed_by: string; - created_at: string; - updated_at: string; - }; - Insert: { - id?: string; - slack_team_id: string; - slack_team_name: string; - organization_id: string; - bot_token: string; - installed_by: string; - created_at?: string; - updated_at?: string; - }; - Update: { - id?: string; - slack_team_id?: string; - slack_team_name?: string; - organization_id?: string; - bot_token?: string; - installed_by?: string; - created_at?: string; - updated_at?: string; - }; - Relationships: [ - { - foreignKeyName: "slack_installations_organization_id_fkey"; - columns: ["organization_id"]; - isOneToOne: false; - referencedRelation: "accounts"; - referencedColumns: ["id"]; - }, - { - foreignKeyName: "slack_installations_installed_by_fkey"; - columns: ["installed_by"]; - isOneToOne: false; - referencedRelation: "accounts"; - referencedColumns: ["id"]; - }, - ]; - }; social_fans: { Row: { artist_social_id: string; From 0284b5547e5a453a36189a31b630685e10d6e0d6 Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Fri, 27 Mar 2026 11:19:15 -0500 Subject: [PATCH 4/8] Revert "Merge pull request #357 from recoupable/feature/sandbox-file-upload-api" This reverts commit 6f3a802c86d970ffb053f176d1b46d614923181a, reversing changes made to 3357bf61746cb6eef5414e932d43ef67c3df3525. --- app/api/sandboxes/files/route.ts | 46 ---------- lib/github/createOrUpdateFileContent.ts | 87 ------------------ lib/sandbox/postSandboxesFilesHandler.ts | 88 ------------------- .../validatePostSandboxesFilesRequest.ts | 86 ------------------ 4 files changed, 307 deletions(-) delete mode 100644 app/api/sandboxes/files/route.ts delete mode 100644 lib/github/createOrUpdateFileContent.ts delete mode 100644 lib/sandbox/postSandboxesFilesHandler.ts delete mode 100644 lib/sandbox/validatePostSandboxesFilesRequest.ts diff --git a/app/api/sandboxes/files/route.ts b/app/api/sandboxes/files/route.ts deleted file mode 100644 index 92426f5b6..000000000 --- a/app/api/sandboxes/files/route.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type { NextRequest } from "next/server"; -import { NextResponse } from "next/server"; -import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; -import { postSandboxesFilesHandler } from "@/lib/sandbox/postSandboxesFilesHandler"; - -/** - * OPTIONS handler for CORS preflight requests. - * - * @returns A NextResponse with CORS headers. - */ -export async function OPTIONS() { - return new NextResponse(null, { - status: 200, - headers: getCorsHeaders(), - }); -} - -/** - * POST /api/sandboxes/files - * - * Uploads one or more files to the authenticated account's sandbox GitHub - * repository. Accepts multipart form data with files and an optional target - * directory path. Resolves submodule paths so files in submodule directories - * are committed to the correct repository. - * - * Authentication: x-api-key header or Authorization Bearer token required. - * - * Form data: - * - files: File[] (required) - One or more files to upload - * - path: string (optional) - Target directory path within the repository - * - message: string (optional) - Commit message (defaults to "Upload files via API") - * - * Response (200): - * - status: "success" - * - uploaded: Array<{ path: string, sha: string }> - * - * Error (400/401/403/404/500): - * - status: "error" - * - error: string - * - * @param request - The request object - * @returns A NextResponse with uploaded file details or error - */ -export async function POST(request: NextRequest): Promise { - return postSandboxesFilesHandler(request); -} diff --git a/lib/github/createOrUpdateFileContent.ts b/lib/github/createOrUpdateFileContent.ts deleted file mode 100644 index 5ef2a1b9a..000000000 --- a/lib/github/createOrUpdateFileContent.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { parseGitHubRepoUrl } from "./parseGitHubRepoUrl"; - -export interface CreateFileResult { - path: string; - sha: string; -} - -/** - * Creates or updates a file in a GitHub repository using the Contents API. - * - * @param params - The parameters for file creation - * @param params.githubRepo - The full GitHub repository URL - * @param params.path - The file path within the repository - * @param params.content - The file content as a Buffer - * @param params.message - The commit message - * @returns The created file path and SHA, or an error - */ -export async function createOrUpdateFileContent({ - githubRepo, - path, - content, - message, -}: { - githubRepo: string; - path: string; - content: Buffer; - message: string; -}): Promise { - const repoInfo = parseGitHubRepoUrl(githubRepo); - if (!repoInfo) { - return { error: "Invalid GitHub repository URL" }; - } - - const { owner, repo } = repoInfo; - const token = process.env.GITHUB_TOKEN; - - if (!token) { - return { error: "GitHub token not configured" }; - } - - const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`; - - // Check if file already exists to get its SHA for updates - let existingSha: string | undefined; - const getResponse = await fetch(url, { - headers: { - Authorization: `Bearer ${token}`, - Accept: "application/vnd.github.v3+json", - }, - }); - - if (getResponse.ok) { - const existing = await getResponse.json(); - existingSha = existing.sha; - } - - const body: Record = { - message, - content: content.toString("base64"), - branch: "main", - }; - - if (existingSha) { - body.sha = existingSha; - } - - const response = await fetch(url, { - method: "PUT", - headers: { - Authorization: `Bearer ${token}`, - Accept: "application/vnd.github.v3+json", - "Content-Type": "application/json", - }, - body: JSON.stringify(body), - }); - - if (!response.ok) { - const errorText = await response.text(); - return { error: `Failed to upload file: ${response.status} ${errorText}` }; - } - - const result = await response.json(); - return { - path: result.content.path, - sha: result.content.sha, - }; -} diff --git a/lib/sandbox/postSandboxesFilesHandler.ts b/lib/sandbox/postSandboxesFilesHandler.ts deleted file mode 100644 index 17dd65fa3..000000000 --- a/lib/sandbox/postSandboxesFilesHandler.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { NextRequest, NextResponse } from "next/server"; -import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; -import { validatePostSandboxesFilesRequest } from "./validatePostSandboxesFilesRequest"; -import { selectAccountSnapshots } from "@/lib/supabase/account_snapshots/selectAccountSnapshots"; -import { resolveSubmodulePath } from "@/lib/github/resolveSubmodulePath"; -import { createOrUpdateFileContent } from "@/lib/github/createOrUpdateFileContent"; -import type { CreateFileResult } from "@/lib/github/createOrUpdateFileContent"; - -/** - * Handler for uploading files to a sandbox's GitHub repository. - * Requires authentication via x-api-key header or Authorization bearer token. - * - * Accepts multipart form data with: - * - files: One or more files to upload - * - path: Target directory path within the repository (optional, defaults to root) - * - message: Commit message (optional, defaults to "Upload files via API") - * - * Resolves submodule paths so files in submodule directories are committed - * to the correct submodule repository. - * - * @param request - The request object - * @returns A NextResponse with uploaded file details or error - */ -export async function postSandboxesFilesHandler(request: NextRequest): Promise { - const validated = await validatePostSandboxesFilesRequest(request); - if (validated instanceof NextResponse) { - return validated; - } - - const { accountIds, orgId, path, message, files } = validated; - - const snapshotAccountId = accountIds?.length === 1 ? accountIds[0] : orgId; - - if (!snapshotAccountId) { - return NextResponse.json( - { status: "error", error: "Could not determine account for snapshot lookup" }, - { status: 404, headers: getCorsHeaders() }, - ); - } - - const snapshots = await selectAccountSnapshots(snapshotAccountId); - const githubRepo = snapshots[0]?.github_repo ?? null; - - if (!githubRepo) { - return NextResponse.json( - { status: "error", error: "No GitHub repository found for this account" }, - { status: 404, headers: getCorsHeaders() }, - ); - } - - const uploaded: CreateFileResult[] = []; - const errors: string[] = []; - - for (const file of files) { - const filePath = path ? `${path}/${file.name}` : file.name; - - const resolved = await resolveSubmodulePath({ githubRepo, path: filePath }); - - const result = await createOrUpdateFileContent({ - githubRepo: resolved.githubRepo, - path: resolved.path, - content: file.content, - message, - }); - - if ("error" in result) { - errors.push(`${file.name}: ${result.error}`); - } else { - uploaded.push(result); - } - } - - if (uploaded.length === 0) { - return NextResponse.json( - { status: "error", error: `All uploads failed: ${errors.join("; ")}` }, - { status: 500, headers: getCorsHeaders() }, - ); - } - - return NextResponse.json( - { - status: "success", - uploaded, - ...(errors.length > 0 && { errors }), - }, - { status: 200, headers: getCorsHeaders() }, - ); -} diff --git a/lib/sandbox/validatePostSandboxesFilesRequest.ts b/lib/sandbox/validatePostSandboxesFilesRequest.ts deleted file mode 100644 index 22e9768f7..000000000 --- a/lib/sandbox/validatePostSandboxesFilesRequest.ts +++ /dev/null @@ -1,86 +0,0 @@ -import type { NextRequest } from "next/server"; -import { NextResponse } from "next/server"; -import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; -import { validateAuthContext } from "@/lib/auth/validateAuthContext"; -import { buildGetSandboxesParams } from "./buildGetSandboxesParams"; - -export interface ValidatedPostSandboxesFilesParams { - accountIds?: string[]; - orgId?: string; - path: string; - message: string; - files: { name: string; content: Buffer }[]; -} - -/** - * Validates POST /api/sandboxes/files request. - * Handles authentication and multipart form data parsing. - * - * @param request - The NextRequest object - * @returns A NextResponse with an error if validation fails, or validated params - */ -export async function validatePostSandboxesFilesRequest( - request: NextRequest, -): Promise { - const authResult = await validateAuthContext(request); - if (authResult instanceof NextResponse) { - return authResult; - } - - const { accountId, orgId } = authResult; - - const { params, error } = await buildGetSandboxesParams({ - account_id: accountId, - }); - - if (error) { - return NextResponse.json( - { status: "error", error }, - { status: 403, headers: getCorsHeaders() }, - ); - } - - let formData: FormData; - try { - formData = await request.formData(); - } catch { - return NextResponse.json( - { status: "error", error: "Request must be multipart/form-data" }, - { status: 400, headers: getCorsHeaders() }, - ); - } - - const path = (formData.get("path") as string) ?? ""; - const message = (formData.get("message") as string) ?? "Upload files via API"; - - const fileEntries = formData.getAll("files"); - if (!fileEntries.length) { - return NextResponse.json( - { status: "error", missing_fields: ["files"], error: "At least one file is required" }, - { status: 400, headers: getCorsHeaders() }, - ); - } - - const files: { name: string; content: Buffer }[] = []; - for (const entry of fileEntries) { - if (!(entry instanceof File)) { - return NextResponse.json( - { status: "error", error: "Invalid file entry" }, - { status: 400, headers: getCorsHeaders() }, - ); - } - const arrayBuffer = await entry.arrayBuffer(); - files.push({ - name: entry.name, - content: Buffer.from(arrayBuffer), - }); - } - - return { - accountIds: params.accountIds, - orgId: orgId ?? undefined, - path, - message, - files, - }; -} From 31c79472d6cc73ec4cb6afa3df254023265d6c5a Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Fri, 27 Mar 2026 11:19:37 -0500 Subject: [PATCH 5/8] Reapply "Merge pull request #357 from recoupable/feature/sandbox-file-upload-api" This reverts commit 0284b5547e5a453a36189a31b630685e10d6e0d6. --- app/api/sandboxes/files/route.ts | 46 ++++++++++ lib/github/createOrUpdateFileContent.ts | 87 ++++++++++++++++++ lib/sandbox/postSandboxesFilesHandler.ts | 88 +++++++++++++++++++ .../validatePostSandboxesFilesRequest.ts | 86 ++++++++++++++++++ 4 files changed, 307 insertions(+) create mode 100644 app/api/sandboxes/files/route.ts create mode 100644 lib/github/createOrUpdateFileContent.ts create mode 100644 lib/sandbox/postSandboxesFilesHandler.ts create mode 100644 lib/sandbox/validatePostSandboxesFilesRequest.ts diff --git a/app/api/sandboxes/files/route.ts b/app/api/sandboxes/files/route.ts new file mode 100644 index 000000000..92426f5b6 --- /dev/null +++ b/app/api/sandboxes/files/route.ts @@ -0,0 +1,46 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { postSandboxesFilesHandler } from "@/lib/sandbox/postSandboxesFilesHandler"; + +/** + * OPTIONS handler for CORS preflight requests. + * + * @returns A NextResponse with CORS headers. + */ +export async function OPTIONS() { + return new NextResponse(null, { + status: 200, + headers: getCorsHeaders(), + }); +} + +/** + * POST /api/sandboxes/files + * + * Uploads one or more files to the authenticated account's sandbox GitHub + * repository. Accepts multipart form data with files and an optional target + * directory path. Resolves submodule paths so files in submodule directories + * are committed to the correct repository. + * + * Authentication: x-api-key header or Authorization Bearer token required. + * + * Form data: + * - files: File[] (required) - One or more files to upload + * - path: string (optional) - Target directory path within the repository + * - message: string (optional) - Commit message (defaults to "Upload files via API") + * + * Response (200): + * - status: "success" + * - uploaded: Array<{ path: string, sha: string }> + * + * Error (400/401/403/404/500): + * - status: "error" + * - error: string + * + * @param request - The request object + * @returns A NextResponse with uploaded file details or error + */ +export async function POST(request: NextRequest): Promise { + return postSandboxesFilesHandler(request); +} diff --git a/lib/github/createOrUpdateFileContent.ts b/lib/github/createOrUpdateFileContent.ts new file mode 100644 index 000000000..5ef2a1b9a --- /dev/null +++ b/lib/github/createOrUpdateFileContent.ts @@ -0,0 +1,87 @@ +import { parseGitHubRepoUrl } from "./parseGitHubRepoUrl"; + +export interface CreateFileResult { + path: string; + sha: string; +} + +/** + * Creates or updates a file in a GitHub repository using the Contents API. + * + * @param params - The parameters for file creation + * @param params.githubRepo - The full GitHub repository URL + * @param params.path - The file path within the repository + * @param params.content - The file content as a Buffer + * @param params.message - The commit message + * @returns The created file path and SHA, or an error + */ +export async function createOrUpdateFileContent({ + githubRepo, + path, + content, + message, +}: { + githubRepo: string; + path: string; + content: Buffer; + message: string; +}): Promise { + const repoInfo = parseGitHubRepoUrl(githubRepo); + if (!repoInfo) { + return { error: "Invalid GitHub repository URL" }; + } + + const { owner, repo } = repoInfo; + const token = process.env.GITHUB_TOKEN; + + if (!token) { + return { error: "GitHub token not configured" }; + } + + const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`; + + // Check if file already exists to get its SHA for updates + let existingSha: string | undefined; + const getResponse = await fetch(url, { + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/vnd.github.v3+json", + }, + }); + + if (getResponse.ok) { + const existing = await getResponse.json(); + existingSha = existing.sha; + } + + const body: Record = { + message, + content: content.toString("base64"), + branch: "main", + }; + + if (existingSha) { + body.sha = existingSha; + } + + const response = await fetch(url, { + method: "PUT", + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/vnd.github.v3+json", + "Content-Type": "application/json", + }, + body: JSON.stringify(body), + }); + + if (!response.ok) { + const errorText = await response.text(); + return { error: `Failed to upload file: ${response.status} ${errorText}` }; + } + + const result = await response.json(); + return { + path: result.content.path, + sha: result.content.sha, + }; +} diff --git a/lib/sandbox/postSandboxesFilesHandler.ts b/lib/sandbox/postSandboxesFilesHandler.ts new file mode 100644 index 000000000..17dd65fa3 --- /dev/null +++ b/lib/sandbox/postSandboxesFilesHandler.ts @@ -0,0 +1,88 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { validatePostSandboxesFilesRequest } from "./validatePostSandboxesFilesRequest"; +import { selectAccountSnapshots } from "@/lib/supabase/account_snapshots/selectAccountSnapshots"; +import { resolveSubmodulePath } from "@/lib/github/resolveSubmodulePath"; +import { createOrUpdateFileContent } from "@/lib/github/createOrUpdateFileContent"; +import type { CreateFileResult } from "@/lib/github/createOrUpdateFileContent"; + +/** + * Handler for uploading files to a sandbox's GitHub repository. + * Requires authentication via x-api-key header or Authorization bearer token. + * + * Accepts multipart form data with: + * - files: One or more files to upload + * - path: Target directory path within the repository (optional, defaults to root) + * - message: Commit message (optional, defaults to "Upload files via API") + * + * Resolves submodule paths so files in submodule directories are committed + * to the correct submodule repository. + * + * @param request - The request object + * @returns A NextResponse with uploaded file details or error + */ +export async function postSandboxesFilesHandler(request: NextRequest): Promise { + const validated = await validatePostSandboxesFilesRequest(request); + if (validated instanceof NextResponse) { + return validated; + } + + const { accountIds, orgId, path, message, files } = validated; + + const snapshotAccountId = accountIds?.length === 1 ? accountIds[0] : orgId; + + if (!snapshotAccountId) { + return NextResponse.json( + { status: "error", error: "Could not determine account for snapshot lookup" }, + { status: 404, headers: getCorsHeaders() }, + ); + } + + const snapshots = await selectAccountSnapshots(snapshotAccountId); + const githubRepo = snapshots[0]?.github_repo ?? null; + + if (!githubRepo) { + return NextResponse.json( + { status: "error", error: "No GitHub repository found for this account" }, + { status: 404, headers: getCorsHeaders() }, + ); + } + + const uploaded: CreateFileResult[] = []; + const errors: string[] = []; + + for (const file of files) { + const filePath = path ? `${path}/${file.name}` : file.name; + + const resolved = await resolveSubmodulePath({ githubRepo, path: filePath }); + + const result = await createOrUpdateFileContent({ + githubRepo: resolved.githubRepo, + path: resolved.path, + content: file.content, + message, + }); + + if ("error" in result) { + errors.push(`${file.name}: ${result.error}`); + } else { + uploaded.push(result); + } + } + + if (uploaded.length === 0) { + return NextResponse.json( + { status: "error", error: `All uploads failed: ${errors.join("; ")}` }, + { status: 500, headers: getCorsHeaders() }, + ); + } + + return NextResponse.json( + { + status: "success", + uploaded, + ...(errors.length > 0 && { errors }), + }, + { status: 200, headers: getCorsHeaders() }, + ); +} diff --git a/lib/sandbox/validatePostSandboxesFilesRequest.ts b/lib/sandbox/validatePostSandboxesFilesRequest.ts new file mode 100644 index 000000000..22e9768f7 --- /dev/null +++ b/lib/sandbox/validatePostSandboxesFilesRequest.ts @@ -0,0 +1,86 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { validateAuthContext } from "@/lib/auth/validateAuthContext"; +import { buildGetSandboxesParams } from "./buildGetSandboxesParams"; + +export interface ValidatedPostSandboxesFilesParams { + accountIds?: string[]; + orgId?: string; + path: string; + message: string; + files: { name: string; content: Buffer }[]; +} + +/** + * Validates POST /api/sandboxes/files request. + * Handles authentication and multipart form data parsing. + * + * @param request - The NextRequest object + * @returns A NextResponse with an error if validation fails, or validated params + */ +export async function validatePostSandboxesFilesRequest( + request: NextRequest, +): Promise { + const authResult = await validateAuthContext(request); + if (authResult instanceof NextResponse) { + return authResult; + } + + const { accountId, orgId } = authResult; + + const { params, error } = await buildGetSandboxesParams({ + account_id: accountId, + }); + + if (error) { + return NextResponse.json( + { status: "error", error }, + { status: 403, headers: getCorsHeaders() }, + ); + } + + let formData: FormData; + try { + formData = await request.formData(); + } catch { + return NextResponse.json( + { status: "error", error: "Request must be multipart/form-data" }, + { status: 400, headers: getCorsHeaders() }, + ); + } + + const path = (formData.get("path") as string) ?? ""; + const message = (formData.get("message") as string) ?? "Upload files via API"; + + const fileEntries = formData.getAll("files"); + if (!fileEntries.length) { + return NextResponse.json( + { status: "error", missing_fields: ["files"], error: "At least one file is required" }, + { status: 400, headers: getCorsHeaders() }, + ); + } + + const files: { name: string; content: Buffer }[] = []; + for (const entry of fileEntries) { + if (!(entry instanceof File)) { + return NextResponse.json( + { status: "error", error: "Invalid file entry" }, + { status: 400, headers: getCorsHeaders() }, + ); + } + const arrayBuffer = await entry.arrayBuffer(); + files.push({ + name: entry.name, + content: Buffer.from(arrayBuffer), + }); + } + + return { + accountIds: params.accountIds, + orgId: orgId ?? undefined, + path, + message, + files, + }; +} From c8d03fb3018236925385be80b3c9d74f365942ee Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Fri, 27 Mar 2026 11:41:19 -0500 Subject: [PATCH 6/8] fix: remove orgId from sandbox file upload params orgId was always null since validateAuthContext is called without organizationId input. Remove the dead fallback logic. Co-Authored-By: Claude Opus 4.6 (1M context) --- lib/sandbox/postSandboxesFilesHandler.ts | 4 ++-- lib/sandbox/validatePostSandboxesFilesRequest.ts | 4 +--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/lib/sandbox/postSandboxesFilesHandler.ts b/lib/sandbox/postSandboxesFilesHandler.ts index 17dd65fa3..ab79d2131 100644 --- a/lib/sandbox/postSandboxesFilesHandler.ts +++ b/lib/sandbox/postSandboxesFilesHandler.ts @@ -27,9 +27,9 @@ export async function postSandboxesFilesHandler(request: NextRequest): Promise Date: Fri, 27 Mar 2026 12:07:11 -0500 Subject: [PATCH 7/8] fix: harden createOrUpdateFileContent and add test coverage - Encode path segments in GitHub API URL to handle special chars - Remove hardcoded branch: "main" to respect repo default branch - Add try/catch around fetch calls to handle network errors - Distinguish 404 (file not found) from other GET failures - Add 10 tests for createOrUpdateFileContent - Add 7 tests for postSandboxesFilesHandler Co-Authored-By: Claude Opus 4.6 (1M context) --- .../createOrUpdateFileContent.test.ts | 152 ++++++++++++++ lib/github/createOrUpdateFileContent.ts | 72 ++++--- .../postSandboxesFilesHandler.test.ts | 189 ++++++++++++++++++ 3 files changed, 384 insertions(+), 29 deletions(-) create mode 100644 lib/github/__tests__/createOrUpdateFileContent.test.ts create mode 100644 lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts diff --git a/lib/github/__tests__/createOrUpdateFileContent.test.ts b/lib/github/__tests__/createOrUpdateFileContent.test.ts new file mode 100644 index 000000000..d50a01d25 --- /dev/null +++ b/lib/github/__tests__/createOrUpdateFileContent.test.ts @@ -0,0 +1,152 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { createOrUpdateFileContent } from "../createOrUpdateFileContent"; + +vi.mock("../parseGitHubRepoUrl", () => ({ + parseGitHubRepoUrl: vi.fn(), +})); + +import { parseGitHubRepoUrl } from "../parseGitHubRepoUrl"; + +const mockFetch = vi.fn(); +global.fetch = mockFetch; + +describe("createOrUpdateFileContent", () => { + const validParams = { + githubRepo: "https://github.com/owner/repo", + path: "test/file.txt", + content: Buffer.from("hello"), + message: "Upload file", + }; + + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(parseGitHubRepoUrl).mockReturnValue({ owner: "owner", repo: "repo" }); + process.env.GITHUB_TOKEN = "test-token"; + }); + + it("returns error for invalid GitHub URL", async () => { + vi.mocked(parseGitHubRepoUrl).mockReturnValue(null); + + const result = await createOrUpdateFileContent(validParams); + + expect(result).toEqual({ error: "Invalid GitHub repository URL" }); + }); + + it("returns error when GITHUB_TOKEN is missing", async () => { + delete process.env.GITHUB_TOKEN; + + const result = await createOrUpdateFileContent(validParams); + + expect(result).toEqual({ error: "GitHub token not configured" }); + }); + + it("creates a new file when it does not exist", async () => { + mockFetch + .mockResolvedValueOnce({ ok: false, status: 404 }) + .mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ content: { path: "test/file.txt", sha: "abc123" } }), + }); + + const result = await createOrUpdateFileContent(validParams); + + expect(result).toEqual({ path: "test/file.txt", sha: "abc123" }); + const putBody = JSON.parse(mockFetch.mock.calls[1][1].body); + expect(putBody.sha).toBeUndefined(); + expect(putBody.branch).toBeUndefined(); + }); + + it("updates an existing file with its SHA", async () => { + mockFetch + .mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ sha: "existing-sha" }), + }) + .mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ content: { path: "test/file.txt", sha: "new-sha" } }), + }); + + const result = await createOrUpdateFileContent(validParams); + + expect(result).toEqual({ path: "test/file.txt", sha: "new-sha" }); + const putBody = JSON.parse(mockFetch.mock.calls[1][1].body); + expect(putBody.sha).toBe("existing-sha"); + }); + + it("returns error when GET fails with non-404 status", async () => { + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 403, + text: () => Promise.resolve("Rate limited"), + }); + + const result = await createOrUpdateFileContent(validParams); + + expect(result).toEqual({ error: "Failed to check existing file: 403 Rate limited" }); + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + + it("returns error when PUT fails", async () => { + mockFetch + .mockResolvedValueOnce({ ok: false, status: 404 }) + .mockResolvedValueOnce({ + ok: false, + status: 422, + text: () => Promise.resolve("Validation failed"), + }); + + const result = await createOrUpdateFileContent(validParams); + + expect(result).toEqual({ error: "Failed to upload file: 422 Validation failed" }); + }); + + it("returns error on network failure during GET", async () => { + mockFetch.mockRejectedValueOnce(new Error("Connection refused")); + + const result = await createOrUpdateFileContent(validParams); + + expect(result).toEqual({ error: "Network error checking existing file: Connection refused" }); + }); + + it("returns error on network failure during PUT", async () => { + mockFetch + .mockResolvedValueOnce({ ok: false, status: 404 }) + .mockRejectedValueOnce(new Error("Timeout")); + + const result = await createOrUpdateFileContent(validParams); + + expect(result).toEqual({ error: "Network error uploading file: Timeout" }); + }); + + it("encodes path segments in the URL", async () => { + mockFetch + .mockResolvedValueOnce({ ok: false, status: 404 }) + .mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ content: { path: "dir/file #1.txt", sha: "abc" } }), + }); + + await createOrUpdateFileContent({ + ...validParams, + path: "dir/file #1.txt", + }); + + const url = mockFetch.mock.calls[0][0]; + expect(url).toBe("https://api.github.com/repos/owner/repo/contents/dir/file%20%231.txt"); + }); + + it("does not hardcode branch in PUT body", async () => { + mockFetch + .mockResolvedValueOnce({ ok: false, status: 404 }) + .mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ content: { path: "file.txt", sha: "abc" } }), + }); + + await createOrUpdateFileContent(validParams); + + const putBody = JSON.parse(mockFetch.mock.calls[1][1].body); + expect(putBody).not.toHaveProperty("branch"); + }); +}); diff --git a/lib/github/createOrUpdateFileContent.ts b/lib/github/createOrUpdateFileContent.ts index 5ef2a1b9a..137f422a1 100644 --- a/lib/github/createOrUpdateFileContent.ts +++ b/lib/github/createOrUpdateFileContent.ts @@ -38,50 +38,64 @@ export async function createOrUpdateFileContent({ return { error: "GitHub token not configured" }; } - const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`; + const encodedPath = path + .split("/") + .map((segment) => encodeURIComponent(segment)) + .join("/"); + const url = `https://api.github.com/repos/${owner}/${repo}/contents/${encodedPath}`; // Check if file already exists to get its SHA for updates let existingSha: string | undefined; - const getResponse = await fetch(url, { - headers: { - Authorization: `Bearer ${token}`, - Accept: "application/vnd.github.v3+json", - }, - }); + try { + const getResponse = await fetch(url, { + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/vnd.github.v3+json", + }, + }); - if (getResponse.ok) { - const existing = await getResponse.json(); - existingSha = existing.sha; + if (getResponse.ok) { + const existing = await getResponse.json(); + existingSha = existing.sha; + } else if (getResponse.status !== 404) { + const errorText = await getResponse.text(); + return { error: `Failed to check existing file: ${getResponse.status} ${errorText}` }; + } + } catch (err) { + return { error: `Network error checking existing file: ${err instanceof Error ? err.message : String(err)}` }; } const body: Record = { message, content: content.toString("base64"), - branch: "main", }; if (existingSha) { body.sha = existingSha; } - const response = await fetch(url, { - method: "PUT", - headers: { - Authorization: `Bearer ${token}`, - Accept: "application/vnd.github.v3+json", - "Content-Type": "application/json", - }, - body: JSON.stringify(body), - }); + try { + const response = await fetch(url, { + method: "PUT", + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/vnd.github.v3+json", + "Content-Type": "application/json", + }, + body: JSON.stringify(body), + }); - if (!response.ok) { - const errorText = await response.text(); - return { error: `Failed to upload file: ${response.status} ${errorText}` }; - } + if (!response.ok) { + const errorText = await response.text(); + return { error: `Failed to upload file: ${response.status} ${errorText}` }; + } - const result = await response.json(); - return { - path: result.content.path, - sha: result.content.sha, - }; + const result = await response.json(); + return { + path: result.content.path, + sha: result.content.sha, + }; + } catch (err) { + return { error: `Network error uploading file: ${err instanceof Error ? err.message : String(err)}` }; + } } diff --git a/lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts b/lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts new file mode 100644 index 000000000..ff79d3b9b --- /dev/null +++ b/lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts @@ -0,0 +1,189 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest, NextResponse } from "next/server"; +import { postSandboxesFilesHandler } from "../postSandboxesFilesHandler"; + +vi.mock("@/lib/networking/getCorsHeaders", () => ({ + getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), +})); + +vi.mock("../validatePostSandboxesFilesRequest", () => ({ + validatePostSandboxesFilesRequest: vi.fn(), +})); + +vi.mock("@/lib/supabase/account_snapshots/selectAccountSnapshots", () => ({ + selectAccountSnapshots: vi.fn(), +})); + +vi.mock("@/lib/github/resolveSubmodulePath", () => ({ + resolveSubmodulePath: vi.fn(), +})); + +vi.mock("@/lib/github/createOrUpdateFileContent", () => ({ + createOrUpdateFileContent: vi.fn(), +})); + +import { validatePostSandboxesFilesRequest } from "../validatePostSandboxesFilesRequest"; +import { selectAccountSnapshots } from "@/lib/supabase/account_snapshots/selectAccountSnapshots"; +import { resolveSubmodulePath } from "@/lib/github/resolveSubmodulePath"; +import { createOrUpdateFileContent } from "@/lib/github/createOrUpdateFileContent"; + +describe("postSandboxesFilesHandler", () => { + const mockRequest = new NextRequest("https://example.com/api/sandboxes/files", { + method: "POST", + }); + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("returns validation error when validation fails", async () => { + const errorResponse = NextResponse.json({ status: "error", error: "Unauthorized" }, { status: 401 }); + vi.mocked(validatePostSandboxesFilesRequest).mockResolvedValue(errorResponse); + + const result = await postSandboxesFilesHandler(mockRequest); + + expect(result.status).toBe(401); + }); + + it("returns 404 when no accountIds resolved", async () => { + vi.mocked(validatePostSandboxesFilesRequest).mockResolvedValue({ + accountIds: [], + path: "", + message: "test", + files: [{ name: "f.txt", content: Buffer.from("x") }], + }); + + const result = await postSandboxesFilesHandler(mockRequest); + const body = await result.json(); + + expect(result.status).toBe(404); + expect(body.error).toBe("Could not determine account for snapshot lookup"); + }); + + it("returns 404 when no GitHub repo found", async () => { + vi.mocked(validatePostSandboxesFilesRequest).mockResolvedValue({ + accountIds: ["acc-1"], + path: "", + message: "test", + files: [{ name: "f.txt", content: Buffer.from("x") }], + }); + vi.mocked(selectAccountSnapshots).mockResolvedValue([]); + + const result = await postSandboxesFilesHandler(mockRequest); + const body = await result.json(); + + expect(result.status).toBe(404); + expect(body.error).toBe("No GitHub repository found for this account"); + }); + + it("uploads a single file successfully", async () => { + vi.mocked(validatePostSandboxesFilesRequest).mockResolvedValue({ + accountIds: ["acc-1"], + path: "docs", + message: "Upload", + files: [{ name: "readme.md", content: Buffer.from("# Hello") }], + }); + vi.mocked(selectAccountSnapshots).mockResolvedValue([ + { github_repo: "https://github.com/owner/repo" } as never, + ]); + vi.mocked(resolveSubmodulePath).mockResolvedValue({ + githubRepo: "https://github.com/owner/repo", + path: "docs/readme.md", + }); + vi.mocked(createOrUpdateFileContent).mockResolvedValue({ + path: "docs/readme.md", + sha: "abc123", + }); + + const result = await postSandboxesFilesHandler(mockRequest); + const body = await result.json(); + + expect(result.status).toBe(200); + expect(body.status).toBe("success"); + expect(body.uploaded).toEqual([{ path: "docs/readme.md", sha: "abc123" }]); + }); + + it("uploads multiple files successfully", async () => { + vi.mocked(validatePostSandboxesFilesRequest).mockResolvedValue({ + accountIds: ["acc-1"], + path: "", + message: "Upload", + files: [ + { name: "a.txt", content: Buffer.from("a") }, + { name: "b.txt", content: Buffer.from("b") }, + ], + }); + vi.mocked(selectAccountSnapshots).mockResolvedValue([ + { github_repo: "https://github.com/owner/repo" } as never, + ]); + vi.mocked(resolveSubmodulePath).mockResolvedValue({ + githubRepo: "https://github.com/owner/repo", + path: "a.txt", + }); + vi.mocked(createOrUpdateFileContent) + .mockResolvedValueOnce({ path: "a.txt", sha: "sha-a" }) + .mockResolvedValueOnce({ path: "b.txt", sha: "sha-b" }); + + const result = await postSandboxesFilesHandler(mockRequest); + const body = await result.json(); + + expect(result.status).toBe(200); + expect(body.uploaded).toHaveLength(2); + }); + + it("returns 500 when all uploads fail", async () => { + vi.mocked(validatePostSandboxesFilesRequest).mockResolvedValue({ + accountIds: ["acc-1"], + path: "", + message: "Upload", + files: [{ name: "f.txt", content: Buffer.from("x") }], + }); + vi.mocked(selectAccountSnapshots).mockResolvedValue([ + { github_repo: "https://github.com/owner/repo" } as never, + ]); + vi.mocked(resolveSubmodulePath).mockResolvedValue({ + githubRepo: "https://github.com/owner/repo", + path: "f.txt", + }); + vi.mocked(createOrUpdateFileContent).mockResolvedValue({ + error: "Network error", + }); + + const result = await postSandboxesFilesHandler(mockRequest); + const body = await result.json(); + + expect(result.status).toBe(500); + expect(body.error).toContain("All uploads failed"); + }); + + it("returns partial success with errors array", async () => { + vi.mocked(validatePostSandboxesFilesRequest).mockResolvedValue({ + accountIds: ["acc-1"], + path: "", + message: "Upload", + files: [ + { name: "good.txt", content: Buffer.from("ok") }, + { name: "bad.txt", content: Buffer.from("fail") }, + ], + }); + vi.mocked(selectAccountSnapshots).mockResolvedValue([ + { github_repo: "https://github.com/owner/repo" } as never, + ]); + vi.mocked(resolveSubmodulePath).mockResolvedValue({ + githubRepo: "https://github.com/owner/repo", + path: "good.txt", + }); + vi.mocked(createOrUpdateFileContent) + .mockResolvedValueOnce({ path: "good.txt", sha: "sha-good" }) + .mockResolvedValueOnce({ error: "Upload failed" }); + + const result = await postSandboxesFilesHandler(mockRequest); + const body = await result.json(); + + expect(result.status).toBe(200); + expect(body.status).toBe("success"); + expect(body.uploaded).toHaveLength(1); + expect(body.errors).toHaveLength(1); + expect(body.errors[0]).toContain("bad.txt"); + }); +}); From ebb59de3b2b861e9231730246745f251e3e3c709 Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Fri, 27 Mar 2026 12:11:20 -0500 Subject: [PATCH 8/8] style: fix formatting Co-Authored-By: Claude Opus 4.6 (1M context) --- .../createOrUpdateFileContent.test.ts | 42 ++++++++----------- lib/github/createOrUpdateFileContent.ts | 10 +++-- .../postSandboxesFilesHandler.test.ts | 5 ++- 3 files changed, 28 insertions(+), 29 deletions(-) diff --git a/lib/github/__tests__/createOrUpdateFileContent.test.ts b/lib/github/__tests__/createOrUpdateFileContent.test.ts index d50a01d25..8e2a19a15 100644 --- a/lib/github/__tests__/createOrUpdateFileContent.test.ts +++ b/lib/github/__tests__/createOrUpdateFileContent.test.ts @@ -41,12 +41,10 @@ describe("createOrUpdateFileContent", () => { }); it("creates a new file when it does not exist", async () => { - mockFetch - .mockResolvedValueOnce({ ok: false, status: 404 }) - .mockResolvedValueOnce({ - ok: true, - json: () => Promise.resolve({ content: { path: "test/file.txt", sha: "abc123" } }), - }); + mockFetch.mockResolvedValueOnce({ ok: false, status: 404 }).mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ content: { path: "test/file.txt", sha: "abc123" } }), + }); const result = await createOrUpdateFileContent(validParams); @@ -88,13 +86,11 @@ describe("createOrUpdateFileContent", () => { }); it("returns error when PUT fails", async () => { - mockFetch - .mockResolvedValueOnce({ ok: false, status: 404 }) - .mockResolvedValueOnce({ - ok: false, - status: 422, - text: () => Promise.resolve("Validation failed"), - }); + mockFetch.mockResolvedValueOnce({ ok: false, status: 404 }).mockResolvedValueOnce({ + ok: false, + status: 422, + text: () => Promise.resolve("Validation failed"), + }); const result = await createOrUpdateFileContent(validParams); @@ -120,12 +116,10 @@ describe("createOrUpdateFileContent", () => { }); it("encodes path segments in the URL", async () => { - mockFetch - .mockResolvedValueOnce({ ok: false, status: 404 }) - .mockResolvedValueOnce({ - ok: true, - json: () => Promise.resolve({ content: { path: "dir/file #1.txt", sha: "abc" } }), - }); + mockFetch.mockResolvedValueOnce({ ok: false, status: 404 }).mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ content: { path: "dir/file #1.txt", sha: "abc" } }), + }); await createOrUpdateFileContent({ ...validParams, @@ -137,12 +131,10 @@ describe("createOrUpdateFileContent", () => { }); it("does not hardcode branch in PUT body", async () => { - mockFetch - .mockResolvedValueOnce({ ok: false, status: 404 }) - .mockResolvedValueOnce({ - ok: true, - json: () => Promise.resolve({ content: { path: "file.txt", sha: "abc" } }), - }); + mockFetch.mockResolvedValueOnce({ ok: false, status: 404 }).mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ content: { path: "file.txt", sha: "abc" } }), + }); await createOrUpdateFileContent(validParams); diff --git a/lib/github/createOrUpdateFileContent.ts b/lib/github/createOrUpdateFileContent.ts index 137f422a1..78e5cc877 100644 --- a/lib/github/createOrUpdateFileContent.ts +++ b/lib/github/createOrUpdateFileContent.ts @@ -40,7 +40,7 @@ export async function createOrUpdateFileContent({ const encodedPath = path .split("/") - .map((segment) => encodeURIComponent(segment)) + .map(segment => encodeURIComponent(segment)) .join("/"); const url = `https://api.github.com/repos/${owner}/${repo}/contents/${encodedPath}`; @@ -62,7 +62,9 @@ export async function createOrUpdateFileContent({ return { error: `Failed to check existing file: ${getResponse.status} ${errorText}` }; } } catch (err) { - return { error: `Network error checking existing file: ${err instanceof Error ? err.message : String(err)}` }; + return { + error: `Network error checking existing file: ${err instanceof Error ? err.message : String(err)}`, + }; } const body: Record = { @@ -96,6 +98,8 @@ export async function createOrUpdateFileContent({ sha: result.content.sha, }; } catch (err) { - return { error: `Network error uploading file: ${err instanceof Error ? err.message : String(err)}` }; + return { + error: `Network error uploading file: ${err instanceof Error ? err.message : String(err)}`, + }; } } diff --git a/lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts b/lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts index ff79d3b9b..b3e8d0c65 100644 --- a/lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts +++ b/lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts @@ -37,7 +37,10 @@ describe("postSandboxesFilesHandler", () => { }); it("returns validation error when validation fails", async () => { - const errorResponse = NextResponse.json({ status: "error", error: "Unauthorized" }, { status: 401 }); + const errorResponse = NextResponse.json( + { status: "error", error: "Unauthorized" }, + { status: 401 }, + ); vi.mocked(validatePostSandboxesFilesRequest).mockResolvedValue(errorResponse); const result = await postSandboxesFilesHandler(mockRequest);