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
50 changes: 50 additions & 0 deletions src/lib/__tests__/githubViewer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { fetchViewerLogin } from "@/lib/githubViewer";

describe("fetchViewerLogin", () => {
const originalFetch = global.fetch;
const mockFetch = vi.fn();

beforeEach(() => {
global.fetch = mockFetch;
mockFetch.mockClear();
});

afterEach(() => {
global.fetch = originalFetch;
});

it("should successfully fetch viewer login with a valid token", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ login: "testuser" }),
} as Response);

const login = await fetchViewerLogin("valid_token-123.PAT");
expect(login).toBe("testuser");
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(mockFetch).toHaveBeenCalledWith("https://api.github.com/user", expect.objectContaining({
headers: expect.objectContaining({
Authorization: "Bearer valid_token-123.PAT",
}),
}));
});

it.each([
{ description: "a newline character", token: "invalid\ntoken" },
{ description: "a space", token: "invalid token" },
])("should throw a GitHubApiError when the token contains $description", async ({ token }) => {
await expect(fetchViewerLogin(token)).rejects.toMatchObject({ message: "Invalid token format", status: 400 });
expect(mockFetch).not.toHaveBeenCalled();
});

it("should throw a GitHubApiError when the fetch response is not ok", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 401,
statusText: "Unauthorized",
} as Response);

await expect(fetchViewerLogin("valid_token")).rejects.toMatchObject({ message: "Failed to resolve current GitHub user", status: 401 });
});
Comment thread
is0692vs marked this conversation as resolved.
});
5 changes: 5 additions & 0 deletions src/lib/githubViewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ type GitHubViewerResponse = {
};

export async function fetchViewerLogin(token: string): Promise<string> {
// Basic validation to prevent header injection / SSRF
if (!/^[A-Za-z0-9_.-]+$/.test(token)) {
throw new GitHubApiError("Invalid token format", 400);
}

const res = await fetch("https://api.github.com/user", {
headers: {
Accept: "application/vnd.github+json",
Expand Down
Loading