-
Notifications
You must be signed in to change notification settings - Fork 2.5k
fix(extension): keep auth handoff private #1273
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
Open
GautamSharma99
wants to merge
1
commit into
supermemoryai:main
Choose a base branch
from
GautamSharma99:fix/extension-private-auth-handoff
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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
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,119 @@ | ||
| import { describe, expect, it } from "bun:test" | ||
| import { readFileSync } from "node:fs" | ||
| import { | ||
| getExtensionAuthCredentials, | ||
| getSessionToken, | ||
| isExtensionAuthUrl, | ||
| } from "./extension-auth" | ||
|
|
||
| describe("extension auth", () => { | ||
| it("accepts only flagged Supermemory auth pages", () => { | ||
| expect( | ||
| isExtensionAuthUrl( | ||
| "https://app.supermemory.ai/?extension-auth-success=true", | ||
| ), | ||
| ).toBe(true) | ||
| expect( | ||
| isExtensionAuthUrl("http://localhost:3000/?extension-auth-success=true"), | ||
| ).toBe(true) | ||
| expect(isExtensionAuthUrl("https://app.supermemory.ai/")).toBe(false) | ||
| expect( | ||
| isExtensionAuthUrl( | ||
| "https://app.supermemory.ai.evil.example/?extension-auth-success=true", | ||
| ), | ||
| ).toBe(false) | ||
| expect( | ||
| isExtensionAuthUrl( | ||
| "http://app.supermemory.ai/?extension-auth-success=true", | ||
| ), | ||
| ).toBe(false) | ||
| }) | ||
|
|
||
| it("finds production and development Better Auth cookies", () => { | ||
| expect( | ||
| getSessionToken([ | ||
| { name: "__Secure-better-auth.session_token", value: "production" }, | ||
| ]), | ||
| ).toBe("production") | ||
| expect( | ||
| getSessionToken([ | ||
| { name: "better-auth-dev.session_token", value: "development" }, | ||
| ]), | ||
| ).toBe("development") | ||
| expect(getSessionToken([{ name: "unrelated", value: "token" }])).toBeNull() | ||
| }) | ||
|
|
||
| it("validates the cookie before returning credentials", async () => { | ||
| const requests: Array<{ url: string; authorization: string | null }> = [] | ||
| const fetchSession = async ( | ||
| input: string | URL | Request, | ||
| init?: RequestInit, | ||
| ) => { | ||
| const headers = new Headers(init?.headers) | ||
| requests.push({ | ||
| url: input.toString(), | ||
| authorization: headers.get("authorization"), | ||
| }) | ||
| return Response.json({ | ||
| user: { | ||
| id: "user-1", | ||
| email: "user@example.com", | ||
| name: "Test User", | ||
| }, | ||
| }) | ||
| } | ||
|
|
||
| const credentials = await getExtensionAuthCredentials( | ||
| "https://app.supermemory.ai/?extension-auth-success=true", | ||
| [{ name: "better-auth.session_token", value: "session-token" }], | ||
| "https://api.supermemory.ai", | ||
| fetchSession, | ||
| ) | ||
|
|
||
| expect(requests).toEqual([ | ||
| { | ||
| url: "https://api.supermemory.ai/v3/session", | ||
| authorization: "Bearer session-token", | ||
| }, | ||
| ]) | ||
| expect(credentials).toEqual({ | ||
| token: "session-token", | ||
| user: { | ||
| userId: "user-1", | ||
| email: "user@example.com", | ||
| name: "Test User", | ||
| }, | ||
| }) | ||
| }) | ||
|
|
||
| it("rejects untrusted callers and invalid sessions", async () => { | ||
| const validResponse = async () => Response.json({ user: { id: "user-1" } }) | ||
| const invalidResponse = async () => new Response(null, { status: 401 }) | ||
|
|
||
| await expect( | ||
| getExtensionAuthCredentials( | ||
| "https://evil.example/?extension-auth-success=true", | ||
| [{ name: "better-auth.session_token", value: "session-token" }], | ||
| "https://api.supermemory.ai", | ||
| validResponse, | ||
| ), | ||
| ).rejects.toThrow("Extension auth is not allowed from this page") | ||
| await expect( | ||
| getExtensionAuthCredentials( | ||
| "https://app.supermemory.ai/?extension-auth-success=true", | ||
| [{ name: "better-auth.session_token", value: "session-token" }], | ||
| "https://api.supermemory.ai", | ||
| invalidResponse, | ||
| ), | ||
| ).rejects.toThrow("Session validation failed") | ||
| }) | ||
|
|
||
| it("does not publish credentials through the page message bus", () => { | ||
| const appExperience = readFileSync( | ||
| new URL("../../web/components/app-experience.tsx", import.meta.url), | ||
| "utf8", | ||
| ) | ||
| expect(appExperience).not.toContain("window.postMessage") | ||
| expect(appExperience).not.toContain("session?.token") | ||
| }) | ||
| }) |
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,90 @@ | ||
| import type { UserData } from "./storage" | ||
|
|
||
| const EXTENSION_AUTH_HOSTS = new Set([ | ||
| "localhost", | ||
| "127.0.0.1", | ||
| "supermemory.ai", | ||
| "app.supermemory.ai", | ||
| ]) | ||
|
|
||
| const SESSION_COOKIE_NAMES = [ | ||
| "__Secure-better-auth.session_token", | ||
| "better-auth.session_token", | ||
| "__Secure-better-auth-session_token", | ||
| "better-auth-session_token", | ||
| "__Secure-better-auth-dev.session_token", | ||
| "better-auth-dev.session_token", | ||
| "__Secure-better-auth-dev-session_token", | ||
| "better-auth-dev-session_token", | ||
| ] | ||
|
|
||
| interface ExtensionAuthCookie { | ||
| name: string | ||
| value: string | ||
| } | ||
|
|
||
| interface ExtensionSessionResponse { | ||
| user?: { | ||
| id?: string | ||
| email?: string | ||
| name?: string | ||
| } | ||
| } | ||
|
|
||
| export function isExtensionAuthUrl(rawUrl: string): boolean { | ||
| try { | ||
| const url = new URL(rawUrl) | ||
| const allowedProtocol = | ||
| url.protocol === "https:" || | ||
| (url.protocol === "http:" && | ||
| (url.hostname === "localhost" || url.hostname === "127.0.0.1")) | ||
| return ( | ||
| allowedProtocol && | ||
| EXTENSION_AUTH_HOSTS.has(url.hostname) && | ||
| url.searchParams.get("extension-auth-success") === "true" | ||
| ) | ||
| } catch { | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| export function getSessionToken(cookies: ExtensionAuthCookie[]): string | null { | ||
| for (const name of SESSION_COOKIE_NAMES) { | ||
| const cookie = cookies.find((candidate) => candidate.name === name) | ||
| if (cookie?.value) return cookie.value | ||
| } | ||
| return null | ||
| } | ||
|
|
||
| export async function getExtensionAuthCredentials( | ||
| pageUrl: string, | ||
| cookies: ExtensionAuthCookie[], | ||
| apiUrl: string, | ||
| fetchSession: typeof fetch = fetch, | ||
| ): Promise<{ token: string; user: UserData }> { | ||
| if (!isExtensionAuthUrl(pageUrl)) { | ||
| throw new Error("Extension auth is not allowed from this page") | ||
| } | ||
|
|
||
| const token = getSessionToken(cookies) | ||
| if (!token) throw new Error("Session cookie not found") | ||
|
|
||
| const response = await fetchSession(`${apiUrl}/v3/session`, { | ||
| headers: { | ||
| Authorization: `Bearer ${token}`, | ||
| }, | ||
| }) | ||
| if (!response.ok) throw new Error("Session validation failed") | ||
|
|
||
| const session = (await response.json()) as ExtensionSessionResponse | ||
| if (!session.user?.id) throw new Error("Session user not found") | ||
|
|
||
| return { | ||
| token, | ||
| user: { | ||
| userId: session.user.id, | ||
| email: session.user.email, | ||
| name: session.user.name, | ||
| }, | ||
| } | ||
| } | ||
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This line uses a type assertion (
as ExtensionSessionResponse) on the result ofresponse.json(). According to the style guide rule 'Use type annotations instead of assertions for object literals', type assertions should be avoided when a type annotation can be used instead. While this is not an object literal, the broader rule 'Avoid unnecessary type assertions' applies here. Sinceresponse.json()returnsPromise<any>, a cleaner approach would be to define a typed wrapper or use a type annotation on the variable declaration:const session: ExtensionSessionResponse = await response.json()instead of casting withas.Spotted by Graphite (based on custom rule: TypeScript style guide (Google))

Is this helpful? React 👍 or 👎 to let us know.