-
Notifications
You must be signed in to change notification settings - Fork 0
fix: integrate PR #481 auth and payload patch into main #490
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import type { RagAnswer, SearchResult } from "@/lib/types"; | ||
|
|
||
| // Route-boundary trim of the answer payload. The retrieval pipeline carries | ||
| // full chunk text plus server-only context on every source (adjacent_context | ||
| // for generation packing, memory cards, table facts, index-unit matches, | ||
| // document summaries), but the client renders only a snippet | ||
| // (retrieval_synopsis ?? content) plus identity, scoring, governance, and | ||
| // label fields. Trimming at the route boundary — never inside rag.ts — keeps | ||
| // caches, generation inputs, and eval behavior byte-identical while cutting | ||
| // the final SSE/JSON event the user waits on after the prose has streamed. | ||
| // | ||
| // Ordering contract: sourceGovernanceWarnings and logAnswerDiagnostics consume | ||
| // the FULL answer and must run before this trim (both routes do). Full source | ||
| // content remains client-visible because the safety panel scans it for clinical | ||
| // warnings that may occur beyond the display synopsis. | ||
|
|
||
| const sourceFieldPolicy = { | ||
| id: "client", | ||
| document_id: "client", | ||
| title: "client", | ||
| file_name: "client", | ||
| page_number: "client", | ||
| chunk_index: "client", | ||
| section_heading: "client", | ||
| section_path: "client", | ||
| heading_level: "client", | ||
| parent_heading: "client", | ||
| anchor_id: "client", | ||
| content: "client", | ||
| retrieval_synopsis: "client", | ||
| image_ids: "client", | ||
| similarity: "client", | ||
| similarity_origin: "client", | ||
| text_rank: "client", | ||
| hybrid_score: "client", | ||
| lexical_score: "client", | ||
| rrf_score: "client", | ||
| score_explanation: "client", | ||
| source_strength: "client", | ||
| source_metadata: "client", | ||
| document_labels: "client", | ||
| document_summary: "server", | ||
| adjacent_context: "server", | ||
| memory_cards: "server", | ||
| memory_score: "client", | ||
| relevance: "client", | ||
| match_explanation: "client", | ||
| table_facts: "server", | ||
| index_unit: "server", | ||
| indexing_quality: "client", | ||
| images: "client", | ||
| } as const satisfies Record<keyof SearchResult, "client" | "server">; | ||
|
|
||
| function trimSourceForClient(source: SearchResult): SearchResult { | ||
| const trimmed = Object.fromEntries( | ||
| (Object.keys(sourceFieldPolicy) as Array<keyof SearchResult>) | ||
| .filter((key) => sourceFieldPolicy[key] === "client" && key in source) | ||
| .map((key) => [key, source[key]]), | ||
| ) as SearchResult; | ||
| trimmed.content = source.content ?? ""; | ||
| trimmed.images ??= []; | ||
| return trimmed; | ||
| } | ||
|
|
||
| export function toClientAnswerPayload<T extends Pick<RagAnswer, "sources">>(answer: T): T { | ||
| if (!answer.sources?.length) return answer; | ||
| return { ...answer, sources: answer.sources.map(trimSourceForClient) }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
|
|
||
| import { toClientAnswerPayload } from "@/lib/answer-client-payload"; | ||
| import { extractSafetyFindings } from "@/lib/clinical-safety"; | ||
| import type { RagAnswer, SearchResult } from "@/lib/types"; | ||
|
|
||
| function fullSource(overrides: Partial<SearchResult> = {}): SearchResult { | ||
| return { | ||
| id: "chunk-1", | ||
| document_id: "doc-1", | ||
| title: "Clozapine monitoring guideline", | ||
| file_name: "clozapine.pdf", | ||
| page_number: 4, | ||
| chunk_index: 7, | ||
| section_heading: "Monitoring", | ||
| content: "Full blood count weekly for 18 weeks. ".repeat(60), | ||
| retrieval_synopsis: "FBC weekly for 18 weeks, then monthly.", | ||
| image_ids: [], | ||
| similarity: 0.82, | ||
| source_metadata: { document_status: "current" } as SearchResult["source_metadata"], | ||
| adjacent_context: "Preceding paragraph context. ".repeat(20), | ||
| document_summary: "A long document summary. ".repeat(30), | ||
| memory_cards: [{ id: "m1" } as never], | ||
| table_facts: [{ id: "t1" } as never], | ||
| index_unit: { unit_type: "table" } as never, | ||
| ...overrides, | ||
| } as SearchResult; | ||
| } | ||
|
|
||
| function answerWith(sources: SearchResult[]): Pick<RagAnswer, "sources"> { | ||
| return { sources }; | ||
| } | ||
|
|
||
| describe("toClientAnswerPayload", () => { | ||
| it("drops server-only per-source fields the client never renders", () => { | ||
| const trimmed = toClientAnswerPayload(answerWith([fullSource()])).sources![0]; | ||
| expect(trimmed.adjacent_context).toBeUndefined(); | ||
| expect(trimmed.memory_cards).toBeUndefined(); | ||
| expect(trimmed.table_facts).toBeUndefined(); | ||
| expect(trimmed.index_unit).toBeUndefined(); | ||
| expect(trimmed.document_summary).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("does not pass unclassified runtime fields through the route boundary", () => { | ||
| const source = { ...fullSource(), future_server_secret: "private" } as SearchResult; | ||
| const trimmed = toClientAnswerPayload(answerWith([source])).sources![0] as SearchResult & { | ||
| future_server_secret?: string; | ||
| }; | ||
| expect(trimmed.future_server_secret).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("keeps identity, snippet, scoring, and governance fields intact", () => { | ||
| const trimmed = toClientAnswerPayload(answerWith([fullSource()])).sources![0]; | ||
| expect(trimmed.id).toBe("chunk-1"); | ||
| expect(trimmed.title).toBe("Clozapine monitoring guideline"); | ||
| expect(trimmed.retrieval_synopsis).toBe("FBC weekly for 18 weeks, then monthly."); | ||
| expect(trimmed.similarity).toBe(0.82); | ||
| expect(trimmed.source_metadata).toEqual({ document_status: "current" }); | ||
| expect(trimmed.page_number).toBe(4); | ||
| }); | ||
|
|
||
| it("preserves full source content so client-side safety scanning cannot miss later warnings", () => { | ||
| const source = fullSource({ content: `${"Routine context. ".repeat(60)}Contraindicated in severe disease.` }); | ||
| const payload = toClientAnswerPayload({ | ||
| answer: "Review the source.", | ||
| grounded: true, | ||
| confidence: "medium", | ||
| citations: [], | ||
| sources: [source], | ||
| } as RagAnswer); | ||
|
|
||
| expect(payload.sources![0].content).toBe(source.content); | ||
| expect(extractSafetyFindings(payload)).toHaveLength(1); | ||
| }); | ||
|
|
||
| it("leaves short content untouched", () => { | ||
| const short = fullSource({ content: "Short snippet." }); | ||
| expect(toClientAnswerPayload(answerWith([short])).sources![0].content).toBe("Short snippet."); | ||
| }); | ||
|
|
||
| it("does not mutate the original answer (caches keep the full sources)", () => { | ||
| const source = fullSource(); | ||
| const answer = answerWith([source]); | ||
| toClientAnswerPayload(answer); | ||
| expect(answer.sources![0].adjacent_context).toBeTruthy(); | ||
| expect(answer.sources![0].content.length).toBeGreaterThan(700); | ||
| }); | ||
|
|
||
| it("passes through answers without sources", () => { | ||
| const empty = answerWith([]); | ||
| expect(toClientAnswerPayload(empty)).toBe(empty); | ||
| }); | ||
|
|
||
| it("materially shrinks a representative payload", () => { | ||
| const answer = answerWith(Array.from({ length: 8 }, (_, index) => fullSource({ id: `chunk-${index}` }))); | ||
| const fullBytes = JSON.stringify(answer).length; | ||
| const trimmedBytes = JSON.stringify(toClientAnswerPayload(answer)).length; | ||
| expect(trimmedBytes).toBeLessThan(fullBytes * 0.8); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import { beforeEach, describe, expect, it, vi } from "vitest"; | ||
| import { NextRequest } from "next/server"; | ||
|
|
||
| // The proxy's second job (session-cookie refresh via supabase.auth.getUser) | ||
| // must run on page navigations and cookie-authenticated API routes. Route | ||
| // handlers can validate an SSR cookie, but their read-only adapter cannot return | ||
| // rotated Set-Cookie headers to the browser. | ||
|
|
||
| const getUser = vi.fn(async () => ({ data: { user: null }, error: null })); | ||
|
|
||
| vi.mock("@supabase/ssr", async (importOriginal) => { | ||
| const actual = await importOriginal<typeof import("@supabase/ssr")>(); | ||
| return { | ||
| ...actual, | ||
| createServerClient: vi.fn((_url, _key, options: { cookies: { setAll: (cookies: never[]) => void } }) => ({ | ||
| auth: { | ||
| getUser: async () => { | ||
| options.cookies.setAll([ | ||
| { | ||
| name: "sb-unit-test-auth-token", | ||
| value: "rotated-session", | ||
| options: { path: "/", httpOnly: true }, | ||
| }, | ||
| ] as never[]); | ||
| return getUser(); | ||
| }, | ||
| }, | ||
| })), | ||
| }; | ||
| }); | ||
|
|
||
| vi.mock("@/lib/env", async (importOriginal) => { | ||
| const actual = await importOriginal<typeof import("../src/lib/env")>(); | ||
| return { | ||
| ...actual, | ||
| env: { | ||
| ...actual.env, | ||
| NEXT_PUBLIC_SUPABASE_URL: "https://unit-test.supabase.co", | ||
| NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY: "sb_publishable_unit_test", | ||
| }, | ||
| }; | ||
| }); | ||
|
|
||
| function requestWithSessionCookie(path: string): NextRequest { | ||
| const request = new NextRequest(new URL(`http://localhost${path}`)); | ||
| request.cookies.set("sb-unit-test-auth-token", "base64-opaque-session"); | ||
| return request; | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| getUser.mockClear(); | ||
| }); | ||
|
|
||
| describe("proxy session refresh scoping", () => { | ||
| it("refreshes SSR cookies for cookie-authenticated API routes and stamps the CSP", async () => { | ||
| const { proxy } = await import("../src/proxy"); | ||
| const response = await proxy(requestWithSessionCookie("/api/answer")); | ||
|
|
||
| expect(getUser).toHaveBeenCalledTimes(1); | ||
| expect(response.cookies.get("sb-unit-test-auth-token")?.value).toBe("rotated-session"); | ||
| expect(response.headers.get("content-security-policy")).toBeTruthy(); | ||
| }); | ||
|
|
||
| it("refreshes the session on page navigations that carry an sb- cookie", async () => { | ||
| const { proxy } = await import("../src/proxy"); | ||
| const response = await proxy(requestWithSessionCookie("/documents/some-id")); | ||
|
|
||
| expect(getUser).toHaveBeenCalledTimes(1); | ||
| expect(response.cookies.get("sb-unit-test-auth-token")?.value).toBe("rotated-session"); | ||
| expect(response.headers.get("content-security-policy")).toBeTruthy(); | ||
| }); | ||
|
|
||
| it("never calls getUser without an sb- cookie", async () => { | ||
| const { proxy } = await import("../src/proxy"); | ||
| await proxy(new NextRequest(new URL("http://localhost/documents/some-id"))); | ||
|
|
||
| expect(getUser).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.