Skip to content
Merged
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
31 changes: 22 additions & 9 deletions lib/sandbox/validateSnapshotPatchBody.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,33 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { validateAuthContext, type AuthContext } from "@/lib/auth/validateAuthContext";
import { validateAuthContext } from "@/lib/auth/validateAuthContext";
import { safeParseJson } from "@/lib/networking/safeParseJson";
import { z } from "zod";

export const snapshotPatchBodySchema = z.object({
snapshotId: z.string({ message: "snapshotId is required" }).min(1, "snapshotId cannot be empty"),
account_id: z.string().uuid("account_id must be a valid UUID").optional(),
});

export type SnapshotPatchBody = z.infer<typeof snapshotPatchBodySchema> & AuthContext;
export type SnapshotPatchBody = {
/** The account ID to update */
accountId: string;
/** The snapshot ID to set */
snapshotId: string;
};

/**
* Validates auth and request body for PATCH /api/sandboxes/snapshot.
* Handles authentication via x-api-key or Authorization bearer token,
* body validation, and optional account_id override for organization API keys.
*
* @param request - The NextRequest object
* @returns A NextResponse with an error if validation fails, or the validated body with auth context.
*/
export async function validateSnapshotPatchBody(
request: NextRequest,
): Promise<NextResponse | SnapshotPatchBody> {
const authResult = await validateAuthContext(request);
if (authResult instanceof NextResponse) {
return authResult;
}

const body = await safeParseJson(request);
const result = snapshotPatchBodySchema.safeParse(body);

Expand All @@ -43,8 +46,18 @@ export async function validateSnapshotPatchBody(
);
}

const { snapshotId, account_id: targetAccountId } = result.data;

const authResult = await validateAuthContext(request, {
accountId: targetAccountId,
});

if (authResult instanceof NextResponse) {
return authResult;
}

return {
...authResult,
...result.data,
accountId: authResult.accountId,
snapshotId,
};
}
Loading