-
Notifications
You must be signed in to change notification settings - Fork 514
Add useCliAuthConfirmation hook and customizable cliAuthConfirm URL target #1388
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
2 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
200 changes: 200 additions & 0 deletions
200
packages/template/src/components-page/cli-auth-confirm.test.tsx
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,200 @@ | ||
| // @vitest-environment jsdom | ||
|
|
||
| import { runAsynchronously } from "@stackframe/stack-shared/dist/utils/promises"; | ||
| import React, { act } from "react"; | ||
| import { createRoot, type Root } from "react-dom/client"; | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | ||
| import type { StackClientApp } from "../lib/stack-app/apps/interfaces/client-app"; | ||
| import { stackAppInternalsSymbol } from "../lib/stack-app/common"; | ||
| import { StackContext } from "../providers/stack-context"; | ||
| import { useCliAuthConfirmation } from "./cli-auth-confirm"; | ||
|
|
||
| const previousActEnvironment = Reflect.get(globalThis, "IS_REACT_ACT_ENVIRONMENT"); | ||
|
|
||
| function responseJson(data: unknown, init?: ResponseInit) { | ||
| return new Response(JSON.stringify(data), { | ||
| status: init?.status ?? 200, | ||
| headers: { "Content-Type": "application/json" }, | ||
| }); | ||
| } | ||
|
|
||
| function createAppTestDouble(options: { | ||
| user: unknown, | ||
| sendRequest: (path: string, requestOptions: RequestInit) => Promise<Response>, | ||
| signInWithTokens?: (tokens: { accessToken: string, refreshToken: string }) => Promise<void>, | ||
| redirectToSignIn?: (options: { replace: true }) => Promise<void>, | ||
| redirectToSignUp?: (options: { replace: true }) => Promise<void>, | ||
| }) { | ||
| const app = { | ||
| useUser: () => options.user, | ||
| redirectToSignIn: options.redirectToSignIn ?? vi.fn(async () => {}), | ||
| redirectToSignUp: options.redirectToSignUp ?? vi.fn(async () => {}), | ||
| [stackAppInternalsSymbol]: { | ||
| sendRequest: options.sendRequest, | ||
| signInWithTokens: options.signInWithTokens ?? vi.fn(async () => {}), | ||
| }, | ||
| }; | ||
|
|
||
| // This test double intentionally implements only the StackClientApp surface | ||
| // that useCliAuthConfirmation touches. | ||
| return app as unknown as StackClientApp<true>; | ||
| } | ||
|
|
||
| function HookProbe() { | ||
| const cliAuth = useCliAuthConfirmation(); | ||
| return ( | ||
| <> | ||
| <div data-testid="status">{cliAuth.status}</div> | ||
| <div data-testid="error">{cliAuth.error?.message}</div> | ||
| <button type="button" onClick={() => runAsynchronously(cliAuth.authorize)}>authorize</button> | ||
| <button onClick={cliAuth.retry}>retry</button> | ||
| </> | ||
| ); | ||
| } | ||
|
|
||
| let root: Root | null = null; | ||
| let container: HTMLDivElement | null = null; | ||
|
|
||
| async function renderWithApp(app: StackClientApp<true>) { | ||
| container = document.createElement("div"); | ||
| document.body.append(container); | ||
| root = createRoot(container); | ||
| await act(async () => { | ||
| root?.render( | ||
| <StackContext.Provider value={{ app }}> | ||
| <HookProbe /> | ||
| </StackContext.Provider> | ||
| ); | ||
| }); | ||
| } | ||
|
|
||
| function getByTestId(testId: string): HTMLElement { | ||
| const element = container?.querySelector(`[data-testid="${testId}"]`); | ||
| if (!(element instanceof HTMLElement)) { | ||
| throw new Error(`Could not find test element ${testId}`); | ||
| } | ||
| return element; | ||
| } | ||
|
|
||
| function getButton(label: string): HTMLButtonElement { | ||
| const button = [...container?.querySelectorAll("button") ?? []] | ||
| .find((element) => element.textContent === label); | ||
| if (!(button instanceof HTMLButtonElement)) { | ||
| throw new Error(`Could not find button ${label}`); | ||
| } | ||
| return button; | ||
| } | ||
|
|
||
| describe("useCliAuthConfirmation", () => { | ||
| beforeEach(() => { | ||
| Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| act(() => { | ||
| root?.unmount(); | ||
| }); | ||
| container?.remove(); | ||
| root = null; | ||
| container = null; | ||
| vi.restoreAllMocks(); | ||
| window.history.replaceState({}, "", "/"); | ||
| Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", previousActEnvironment); | ||
| }); | ||
|
|
||
| it("completes CLI auth with the current user's refresh token", async () => { | ||
| window.history.replaceState({}, "", "/handler/cli-auth-confirm?login_code=login-code"); | ||
| const getTokens = vi.fn(async () => ({ refreshToken: "refresh-token" })); | ||
| const sendRequest = vi.fn(async (_path: string, _requestOptions: RequestInit) => new Response(null, { status: 200 })); | ||
| const app = createAppTestDouble({ | ||
| user: { currentSession: { getTokens } }, | ||
| sendRequest, | ||
| }); | ||
|
|
||
| await renderWithApp(app); | ||
| await act(async () => { | ||
| getButton("authorize").click(); | ||
| }); | ||
|
|
||
| expect(getByTestId("status").textContent).toBe("success"); | ||
| expect(getTokens).toHaveBeenCalledOnce(); | ||
| expect(sendRequest).toHaveBeenCalledOnce(); | ||
| expect(sendRequest.mock.calls[0][0]).toBe("/auth/cli/complete"); | ||
| expect(JSON.parse(String(sendRequest.mock.calls[0][1].body))).toMatchInlineSnapshot(` | ||
| { | ||
| "login_code": "login-code", | ||
| "refresh_token": "refresh-token", | ||
| } | ||
| `); | ||
| }); | ||
|
|
||
| it("ignores duplicate authorize clicks before React re-renders", async () => { | ||
| window.history.replaceState({}, "", "/handler/cli-auth-confirm?login_code=login-code"); | ||
| const getTokens = vi.fn(async () => ({ refreshToken: "refresh-token" })); | ||
| const sendRequest = vi.fn(async (_path: string, _requestOptions: RequestInit) => new Response(null, { status: 200 })); | ||
| const app = createAppTestDouble({ | ||
| user: { currentSession: { getTokens } }, | ||
| sendRequest, | ||
| }); | ||
|
|
||
| await renderWithApp(app); | ||
| await act(async () => { | ||
| const authorizeButton = getButton("authorize"); | ||
| authorizeButton.click(); | ||
| authorizeButton.click(); | ||
| }); | ||
|
|
||
| expect(sendRequest).toHaveBeenCalledOnce(); | ||
| }); | ||
|
|
||
| it("claims anonymous CLI sessions before redirecting to sign-up", async () => { | ||
| window.history.replaceState({}, "", "/handler/cli-auth-confirm?login_code=login-code"); | ||
| const signInWithTokens = vi.fn(async (_tokens: { accessToken: string, refreshToken: string }) => {}); | ||
| const redirectToSignUp = vi.fn(async (_options: { replace: true }) => {}); | ||
| const sendRequest = vi.fn(async (_path: string, _requestOptions: RequestInit) => new Response(null, { status: 200 })) | ||
| .mockResolvedValueOnce(responseJson({ cli_session_state: "anonymous" })) | ||
| .mockResolvedValueOnce(responseJson({ access_token: "access-token", refresh_token: "refresh-token" })); | ||
| const app = createAppTestDouble({ | ||
| user: null, | ||
| sendRequest, | ||
| signInWithTokens, | ||
| redirectToSignUp, | ||
| }); | ||
|
|
||
| await renderWithApp(app); | ||
| await act(async () => { | ||
| getButton("authorize").click(); | ||
| }); | ||
|
|
||
| expect(redirectToSignUp).toHaveBeenCalledWith({ replace: true }); | ||
| expect(signInWithTokens).toHaveBeenCalledWith({ | ||
| accessToken: "access-token", | ||
| refreshToken: "refresh-token", | ||
| }); | ||
| expect(new URL(window.location.href).searchParams.get("confirmed")).toBe("true"); | ||
| expect(sendRequest.mock.calls.map(call => JSON.parse(String(call[1].body)))).toMatchInlineSnapshot(` | ||
| [ | ||
| { | ||
| "login_code": "login-code", | ||
| "mode": "check", | ||
| }, | ||
| { | ||
| "login_code": "login-code", | ||
| "mode": "claim-anon-session", | ||
| }, | ||
| ] | ||
| `); | ||
| }); | ||
|
|
||
| it("reports invalid when the login code is missing", async () => { | ||
| window.history.replaceState({}, "", "/handler/cli-auth-confirm"); | ||
| const app = createAppTestDouble({ | ||
| user: null, | ||
| sendRequest: vi.fn(async (_path: string, _requestOptions: RequestInit) => new Response(null, { status: 200 })), | ||
| }); | ||
|
|
||
| await renderWithApp(app); | ||
|
|
||
| expect(getByTestId("status").textContent).toBe("invalid"); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.