Skip to content
Open
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
3 changes: 2 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions packages/github-bot/src/control-plane-responses.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";

import { createSessionResponseSchema, sendPromptResponseSchema } from "./control-plane-responses";

describe("control-plane response schemas", () => {
it("parses valid session and prompt responses", () => {
expect(createSessionResponseSchema.safeParse({ sessionId: "session-123" }).success).toBe(true);
expect(sendPromptResponseSchema.safeParse({ messageId: "msg-456" }).success).toBe(true);
});

it("rejects malformed or partial responses", () => {
expect(createSessionResponseSchema.safeParse({ sessionId: 123 }).success).toBe(false);
expect(createSessionResponseSchema.safeParse({}).success).toBe(false);
expect(sendPromptResponseSchema.safeParse({ messageId: null }).success).toBe(false);
expect(sendPromptResponseSchema.safeParse({}).success).toBe(false);
});
});
12 changes: 12 additions & 0 deletions packages/github-bot/src/control-plane-responses.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { z } from "zod";

export const createSessionResponseSchema = z.object({
sessionId: z.string(),
});

export const sendPromptResponseSchema = z.object({
messageId: z.string(),
});

export type CreateSessionResponse = z.infer<typeof createSessionResponseSchema>;
export type SendPromptResponse = z.infer<typeof sendPromptResponseSchema>;
15 changes: 11 additions & 4 deletions packages/github-bot/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
import type { Logger } from "./logger";
import { generateInstallationToken, postReaction, checkSenderPermission } from "./github-auth";
import { buildCodeReviewPrompt, buildCommentActionPrompt } from "./prompts";
import { createSessionResponseSchema, sendPromptResponseSchema } from "./control-plane-responses";
import { getGitHubConfig, type ResolvedGitHubConfig } from "./utils/integration-config";

export type HandlerResult =
Expand Down Expand Up @@ -65,8 +66,11 @@ async function createSession(
const body = await response.text();
throw new Error(`Session creation failed: ${response.status} ${body}`);
}
const result = (await response.json()) as { sessionId: string };
return result.sessionId;
const result = createSessionResponseSchema.safeParse(await response.json());
if (!result.success) {
throw new Error("Session creation failed: invalid response");
}
return result.data.sessionId;
}

async function sendPrompt(
Expand All @@ -84,8 +88,11 @@ async function sendPrompt(
const body = await response.text();
throw new Error(`Prompt delivery failed: ${response.status} ${body}`);
}
const result = (await response.json()) as { messageId: string };
return result.messageId;
const result = sendPromptResponseSchema.safeParse(await response.json());
if (!result.success) {
throw new Error("Prompt delivery failed: invalid response");
}
return result.data.messageId;
}

function stripMention(body: string, botUsername: string): string {
Expand Down
3 changes: 2 additions & 1 deletion packages/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"sonner": "^2.0.7",
"swr": "^2.4.0",
"tailwind-merge": "^3.5.0",
"tailwindcss-animate": "^1.0.7"
"tailwindcss-animate": "^1.0.7",
"zod": "^4.4.3"
},
"devDependencies": {
"@opennextjs/cloudflare": "1.19.11",
Expand Down
21 changes: 18 additions & 3 deletions packages/web/src/lib/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import {
getVerifiedGitHubEmails,
} from "./auth";

vi.mock("@open-inspect/shared", () => ({
DEFAULT_APP_NAME: "Open-Inspect",
}));
vi.mock("@open-inspect/shared", async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>;
return { ...actual, DEFAULT_APP_NAME: "Open-Inspect" };
});

vi.mock("next-auth/providers/github", () => ({
default: (config: unknown) => ({
Expand Down Expand Up @@ -388,6 +389,20 @@ describe("getVerifiedGitHubEmails", () => {
await expect(getVerifiedGitHubEmails({ accessToken: "token" })).resolves.toEqual([]);
});

it("returns empty array for malformed GitHub email responses", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(JSON.stringify([{ email: "user@company.com", verified: true }]))
);

await expect(getVerifiedGitHubEmails({ accessToken: "token" })).resolves.toEqual([]);

expect(warn).toHaveBeenCalledWith(
"[github-email-fetch] invalid response",
expect.objectContaining({ elapsedMs: expect.any(Number) })
);
});

it("returns empty array when GitHub email lookup fails", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 403 }));

Expand Down
17 changes: 12 additions & 5 deletions packages/web/src/lib/auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Account, NextAuthOptions, Profile, Session } from "next-auth";
import type { JWT } from "next-auth/jwt";
import GitHubProvider from "next-auth/providers/github";
import type { GithubEmail, GithubProfile } from "next-auth/providers/github";
import type { GithubProfile } from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";
import { DEFAULT_APP_NAME } from "@open-inspect/shared";
import {
Expand All @@ -16,6 +16,7 @@ import {
type GitHubOrganizationAccessResult,
} from "./github-org-membership";
import { type AuthProvider, isAuthProvider } from "./build-auth-identity";
import { githubEmailListSchema, type GitHubEmail } from "./github-email-schema";

const GITHUB_EMAIL_FETCH_TIMEOUT_MS = 5_000;

Expand All @@ -26,7 +27,7 @@ interface GitHubEmailFetchParams {
timeoutMs?: number;
}

type GitHubProfileWithEmails = GithubProfile & { verifiedEmails?: GithubEmail[] };
type GitHubProfileWithEmails = GithubProfile & { verifiedEmails?: GitHubEmail[] };

/**
* Fetch verified email addresses from GitHub's API.
Expand All @@ -40,7 +41,7 @@ export async function getVerifiedGitHubEmails({
fetchImpl = fetch,
userAgent = "Open-Inspect",
timeoutMs = GITHUB_EMAIL_FETCH_TIMEOUT_MS,
}: GitHubEmailFetchParams): Promise<GithubEmail[]> {
}: GitHubEmailFetchParams): Promise<GitHubEmail[]> {
if (!accessToken) return [];

const controller = new AbortController();
Expand Down Expand Up @@ -73,8 +74,14 @@ export async function getVerifiedGitHubEmails({
});
return [];
}
const emails = (await response.json()) as GithubEmail[];
return emails.filter((e) => e.verified);
const result = githubEmailListSchema.safeParse(await response.json());
if (!result.success) {
console.warn("[github-email-fetch] invalid response", {
elapsedMs: Math.round(performance.now() - startedAt),
});
return [];
}
return result.data.filter((e) => e.verified);
} catch (error) {
console.warn("[github-email-fetch] request error", {
error: error instanceof Error ? error.name : "unknown",
Expand Down
35 changes: 35 additions & 0 deletions packages/web/src/lib/github-email-schema.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";

import { githubEmailListSchema } from "./github-email-schema";

describe("githubEmailListSchema", () => {
it("parses valid GitHub email API responses", () => {
const result = githubEmailListSchema.safeParse([
{ email: "user@example.com", primary: true, verified: true, visibility: "private" },
]);

expect(result.success).toBe(true);
});

it("accepts nullable visibility from GitHub", () => {
const result = githubEmailListSchema.safeParse([
{ email: "user@example.com", primary: true, verified: true, visibility: null },
]);

expect(result.success).toBe(true);
});

it("rejects malformed or partial email responses", () => {
expect(githubEmailListSchema.safeParse({ email: "user@example.com" }).success).toBe(false);
expect(
githubEmailListSchema.safeParse([
{ email: "user@example.com", primary: true, verified: true },
]).success
).toBe(false);
expect(
githubEmailListSchema.safeParse([
{ email: "user@example.com", primary: true, verified: "yes", visibility: null },
]).success
).toBe(false);
});
});
12 changes: 12 additions & 0 deletions packages/web/src/lib/github-email-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { z } from "zod";

export const githubEmailSchema = z.object({
email: z.string(),
primary: z.boolean(),
verified: z.boolean(),
visibility: z.string().nullable(),
});

export const githubEmailListSchema = z.array(githubEmailSchema);

export type GitHubEmail = z.infer<typeof githubEmailSchema>;
Loading