@supatype/react-auth 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ import { useEffect, useRef } from "react"
2
+ import type { AuthRedirectError } from "@supatype/client"
3
+ import { useAuth } from "@supatype/react"
4
+
5
+ /**
6
+ * The sign-in the auth server refused and sent back in the page's URL, when `provider` started it,
7
+ * else null. `onError` hears it once, through a ref so an inline handler does not hear it again on
8
+ * every render.
9
+ */
10
+ export function useRedirectError(
11
+ provider: string,
12
+ onError: ((error: AuthRedirectError) => void) | undefined,
13
+ ): AuthRedirectError | null {
14
+ const { error } = useAuth()
15
+ const onErrorRef = useRef(onError)
16
+ onErrorRef.current = onError
17
+ const mine = error !== null && error.provider === provider ? error : null
18
+ useEffect(() => {
19
+ if (mine !== null) onErrorRef.current?.(mine)
20
+ }, [mine])
21
+ return mine
22
+ }
@@ -15,7 +15,7 @@ import {
15
15
  UpdatePasswordForm,
16
16
  type AuthFormClassNames,
17
17
  } from "../src/index.js"
18
- import { classesOf, render, submit, textOf, type } from "./helpers.js"
18
+ import { classesOf, render, stubFetch, submit, textOf, type } from "./helpers.js"
19
19
 
20
20
  const USER = {
21
21
  id: "user-1",
@@ -44,29 +44,6 @@ const CLASS_NAMES: AuthFormClassNames = {
44
44
  message: "t-message",
45
45
  }
46
46
 
47
- interface SentRequest {
48
- url: URL
49
- method: string
50
- body: unknown
51
- authorization: string | null
52
- }
53
-
54
- /** Stub `fetch` with one answer and record every request the client sends. */
55
- function stubFetch(status: number, body: unknown): SentRequest[] {
56
- const sent: SentRequest[] = []
57
- vi.stubGlobal("fetch", vi.fn(async (input: string, init?: RequestInit) => {
58
- const headers = new Headers(init?.headers)
59
- sent.push({
60
- url: new URL(input),
61
- method: init?.method ?? "GET",
62
- body: typeof init?.body === "string" ? JSON.parse(init.body) as unknown : null,
63
- authorization: headers.get("Authorization"),
64
- })
65
- return new Response(JSON.stringify(body), { status })
66
- }))
67
- return sent
68
- }
69
-
70
47
  afterEach(() => {
71
48
  vi.unstubAllGlobals()
72
49
  })
package/tests/helpers.tsx CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import React from "react"
6
6
  import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer"
7
+ import { vi, type Mock } from "vitest"
7
8
  import { createClient, type Session } from "@supatype/client"
8
9
  import { SupatypeProvider } from "@supatype/react"
9
10
  import { fire, stringProp } from "./props.js"
@@ -35,6 +36,45 @@ export function textOf(node: ReactTestInstance): string {
35
36
  return node.children.map((child) => (typeof child === "string" ? child : textOf(child))).join("")
36
37
  }
37
38
 
39
+ export interface SentRequest {
40
+ url: URL
41
+ method: string
42
+ body: unknown
43
+ authorization: string | null
44
+ }
45
+
46
+ /** Stub `fetch` with one answer and record every request the client sends. */
47
+ export function stubFetch(status: number, body: unknown): SentRequest[] {
48
+ const sent: SentRequest[] = []
49
+ vi.stubGlobal("fetch", vi.fn(async (input: string, init?: RequestInit) => {
50
+ const headers = new Headers(init?.headers)
51
+ sent.push({
52
+ url: new URL(input),
53
+ method: init?.method ?? "GET",
54
+ body: typeof init?.body === "string" ? JSON.parse(init.body) as unknown : null,
55
+ authorization: headers.get("Authorization"),
56
+ })
57
+ return new Response(JSON.stringify(body), { status })
58
+ }))
59
+ return sent
60
+ }
61
+
62
+ /** A browser at `href` whose navigations are recorded, with a localStorage holding `stored`. */
63
+ export function stubBrowser(href = "https://app.example/login", stored: Record<string, string> = {}): { assign: Mock<(url: string) => void> } {
64
+ const store = new Map(Object.entries(stored))
65
+ const assign = vi.fn<(url: string) => void>()
66
+ vi.stubGlobal("window", {
67
+ location: { href, protocol: "https:", assign },
68
+ history: { state: null, replaceState: vi.fn() },
69
+ localStorage: {
70
+ getItem: (k: string) => store.get(k) ?? null,
71
+ setItem: (k: string, v: string) => { store.set(k, v) },
72
+ removeItem: (k: string) => { store.delete(k) },
73
+ },
74
+ })
75
+ return { assign }
76
+ }
77
+
38
78
  /** The class on each element of this type, in order. */
39
79
  export function classesOf(root: ReactTestInstance, type: keyof React.JSX.IntrinsicElements): Array<string | undefined> {
40
80
  return root.findAllByType(type).map((node) => stringProp(node, "className"))
@@ -1,7 +1,7 @@
1
1
  import React from "react"
2
2
  import { afterEach, describe, expect, it, vi } from "vitest"
3
3
  import { act, create, type ReactTestInstance } from "react-test-renderer"
4
- import type { AuthRedirectError, SupatypeError } from "@supatype/client"
4
+ import { AuthRedirectError, SupatypeError } from "@supatype/client"
5
5
  import { OAuthButton } from "../src/index.js"
6
6
  import { fire, stringProp } from "./props.js"
7
7
 
@@ -45,7 +45,7 @@ describe("OAuthButton errors", () => {
45
45
  it("calls onError and stays on the page when the provider is not enabled", async () => {
46
46
  const location = { href: "https://app.example/" }
47
47
  vi.stubGlobal("window", { location })
48
- const error = { message: "Sign-in with github is not enabled for this project.", code: "provider_disabled" }
48
+ const error = new SupatypeError({ message: "Sign-in with github is not enabled for this project.", code: "provider_disabled" })
49
49
  auth.signInWithOAuth.mockResolvedValue({ data: { url: "", provider: "github" }, error })
50
50
  const onError = vi.fn()
51
51
 
@@ -57,7 +57,7 @@ describe("OAuthButton errors", () => {
57
57
  })
58
58
 
59
59
  it("reports a refusal the server sent back in the URL to the button that started it", async () => {
60
- auth.error = { message: "Signups not allowed", code: "signup_disabled", provider: "github" }
60
+ auth.error = new AuthRedirectError({ message: "Signups not allowed", code: "signup_disabled", provider: "github" })
61
61
  const onGitHub = vi.fn()
62
62
  const onGoogle = vi.fn()
63
63
 
@@ -49,6 +49,14 @@ describe("usePasswordRecovery", () => {
49
49
  expect(latest().active).toBe(false)
50
50
  })
51
51
 
52
+ it("hands out the same finish on every render, so an effect can depend on it", async () => {
53
+ const { client, latest } = mount()
54
+ const before = latest().finish
55
+ await act(async () => { await client.auth.verifyOtp({ type: "recovery", token: "", tokenHash: "hash" }) })
56
+ expect(latest().active).toBe(true)
57
+ expect(latest().finish).toBe(before)
58
+ })
59
+
52
60
  it("stays off for an ordinary sign-in and ends on sign-out", async () => {
53
61
  const { client, latest } = mount()
54
62
  await act(async () => { await client.auth.signInWithPassword({ email: "ada@example.com", password: "x" }) })
@@ -0,0 +1,65 @@
1
+ /**
2
+ * An auth form over a client that has no API address or anon key.
3
+ *
4
+ * The client throws `MissingClientValuesError` from the request rather than turning it into a
5
+ * result, so an app that reads only `data` cannot miss it. A form must still show it and stop
6
+ * loading: it used to hang on its spinner, with the error only as an unhandled rejection.
7
+ */
8
+
9
+ import React from "react"
10
+ import { act, create, type ReactTestRenderer } from "react-test-renderer"
11
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
12
+ import { createClient, MissingClientValuesError, type SupatypeError } from "@supatype/client"
13
+ import { SupatypeProvider } from "@supatype/react"
14
+ import { LoginForm, SignUpForm } from "../src/index.js"
15
+ import { submit, textOf, type } from "./helpers.js"
16
+
17
+ const unhandled: unknown[] = []
18
+ const record = (reason: unknown): void => { unhandled.push(reason) }
19
+
20
+ beforeEach(() => {
21
+ unhandled.length = 0
22
+ process.on("unhandledRejection", record)
23
+ })
24
+
25
+ afterEach(() => {
26
+ process.off("unhandledRejection", record)
27
+ vi.unstubAllGlobals()
28
+ })
29
+
30
+ /** Render `ui` over a client given neither value, on a page that set none. */
31
+ function renderUnconfigured(ui: React.ReactElement): ReactTestRenderer {
32
+ const client = createClient({})
33
+ let renderer: ReactTestRenderer | null = null
34
+ act(() => { renderer = create(<SupatypeProvider client={client}>{ui}</SupatypeProvider>) })
35
+ return renderer!
36
+ }
37
+
38
+ /** Whether every button in the form is enabled again, as it is once loading has ended. */
39
+ function buttonsEnabled(renderer: ReactTestRenderer): boolean {
40
+ return renderer.root.findAllByType("button").every((button) => button.props["disabled"] !== true)
41
+ }
42
+
43
+ describe("an auth form over a client with no address or anon key", () => {
44
+ it.each([
45
+ ["LoginForm", (onError: (e: SupatypeError) => void) => <LoginForm onError={onError} />, "st-login"],
46
+ ["SignUpForm", (onError: (e: SupatypeError) => void) => <SignUpForm onError={onError} />, "st-signup"],
47
+ ])("%s shows the setup error and stops loading", async (_name, form, prefix) => {
48
+ const fetchSpy = vi.fn()
49
+ vi.stubGlobal("fetch", fetchSpy)
50
+ const onError = vi.fn()
51
+ const renderer = renderUnconfigured(form(onError))
52
+
53
+ type(renderer, `${prefix}-email`, "ada@example.com")
54
+ type(renderer, `${prefix}-password`, "secret-pass")
55
+ await submit(renderer)
56
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)) })
57
+
58
+ expect(textOf(renderer.root.findByProps({ role: "alert" }))).toContain("no API address and anon key")
59
+ const reported: unknown = onError.mock.calls[0]?.[0]
60
+ expect(typeof reported === "object" && reported !== null ? Reflect.get(reported, "message") : undefined).toMatch(/SUPATYPE_URL/)
61
+ expect(buttonsEnabled(renderer)).toBe(true)
62
+ expect(fetchSpy).not.toHaveBeenCalled()
63
+ expect(unhandled.filter((reason) => reason instanceof MissingClientValuesError)).toEqual([])
64
+ })
65
+ })
@@ -0,0 +1,109 @@
1
+ /**
2
+ * SSOForm, over the real client: the request the auth server receives for what the user typed, where
3
+ * the browser goes, and what the form shows while it waits and when it is refused.
4
+ */
5
+
6
+ import React from "react"
7
+ import { PKCE_METHOD_S256 } from "@supatype/client"
8
+ import { act } from "react-test-renderer"
9
+ import { afterEach, describe, expect, it, vi } from "vitest"
10
+ import { SSOForm } from "../src/index.js"
11
+ import { render, stubBrowser, stubFetch, submit, textOf, type } from "./helpers.js"
12
+ import { fire } from "./props.js"
13
+
14
+ const IDP_URL = "https://idp.example/sso?SAMLRequest=abc"
15
+ const PROVIDER_KEY = "supatype.auth.session-oauth-provider"
16
+
17
+ /** The challenge fields signInWithSSO adds by default, as it starts a PKCE sign-in. */
18
+ const ANY_STRING: unknown = expect.any(String)
19
+ const PKCE_FIELDS = { code_challenge: ANY_STRING, code_challenge_method: PKCE_METHOD_S256 }
20
+
21
+ afterEach(() => {
22
+ vi.unstubAllGlobals()
23
+ })
24
+
25
+ describe("SSOForm", () => {
26
+ it("starts SSO for the domain of the email typed and sends the browser to the identity provider", async () => {
27
+ const { assign } = stubBrowser()
28
+ const sent = stubFetch(200, { url: IDP_URL })
29
+ const onSuccess = vi.fn()
30
+ const renderer = render(<SSOForm redirectTo="https://app.example/home" onSuccess={onSuccess} />)
31
+ type(renderer, "st-sso-email", " Ada@Acme.COM ")
32
+ await submit(renderer)
33
+
34
+ const sso = sent.find((r) => r.url.pathname === "/auth/v1/sso")
35
+ expect(sso?.method).toBe("POST")
36
+ expect(sso?.body).toEqual({ domain: "acme.com", skip_http_redirect: true, redirect_to: "https://app.example/home", ...PKCE_FIELDS })
37
+ expect(assign).toHaveBeenCalledWith(IDP_URL)
38
+ expect(onSuccess).toHaveBeenCalledWith(IDP_URL)
39
+ expect(textOf(renderer.root.findByProps({ role: "status" }))).toBe("Redirecting to your identity provider…")
40
+ })
41
+
42
+ it("takes a bare domain as it is", async () => {
43
+ stubBrowser()
44
+ const sent = stubFetch(200, { url: IDP_URL })
45
+ const renderer = render(<SSOForm />)
46
+ type(renderer, "st-sso-email", "acme.com")
47
+ await submit(renderer)
48
+
49
+ expect(sent.find((r) => r.url.pathname === "/auth/v1/sso")?.body).toEqual({ domain: "acme.com", skip_http_redirect: true, ...PKCE_FIELDS })
50
+ })
51
+
52
+ it("refuses an address with no domain without asking the server", async () => {
53
+ stubBrowser()
54
+ const sent = stubFetch(200, { url: IDP_URL })
55
+ const onError = vi.fn()
56
+ const renderer = render(<SSOForm onError={onError} />)
57
+ type(renderer, "st-sso-email", "ada@")
58
+ await submit(renderer)
59
+
60
+ expect(sent.filter((r) => r.url.pathname === "/auth/v1/sso")).toHaveLength(0)
61
+ expect(textOf(renderer.root.findByProps({ role: "alert" }))).toBe("Enter your work email address.")
62
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ code: "validation_failed" }))
63
+ })
64
+
65
+ it("shows the server's refusal, calls onError, keeps the form and stays on the page", async () => {
66
+ const { assign } = stubBrowser()
67
+ stubFetch(404, { code: 404, error_code: "sso_provider_not_found", msg: "No SSO provider assigned for this domain" })
68
+ const onError = vi.fn()
69
+ const renderer = render(<SSOForm onError={onError} />)
70
+ type(renderer, "st-sso-email", "ada@nope.com")
71
+ await submit(renderer)
72
+
73
+ expect(textOf(renderer.root.findByProps({ role: "alert" }))).toBe("No SSO provider assigned for this domain")
74
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ code: "sso_provider_not_found" }))
75
+ expect(renderer.root.findAllByType("form")).toHaveLength(1)
76
+ expect(assign).not.toHaveBeenCalled()
77
+ })
78
+
79
+ it("disables the field and button and says it is redirecting while the request runs", async () => {
80
+ stubBrowser()
81
+ let answer: (res: Response) => void = () => undefined
82
+ vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>((resolve) => { answer = resolve })))
83
+ const renderer = render(<SSOForm />)
84
+ type(renderer, "st-sso-email", "ada@acme.com")
85
+ const form = renderer.root.findByType("form")
86
+ act(() => { void fire(form, "onSubmit", { preventDefault: () => undefined }) })
87
+
88
+ const button = renderer.root.findByType("button")
89
+ expect(button.props["disabled"]).toBe(true)
90
+ expect(textOf(button)).toBe("Redirecting…")
91
+ expect(renderer.root.findByType("input").props["disabled"]).toBe(true)
92
+ await act(async () => { answer(new Response(JSON.stringify({ url: IDP_URL }), { status: 200 })) })
93
+ })
94
+
95
+ it("shows an SSO sign-in the auth server refused and sent back in the URL", async () => {
96
+ stubFetch(200, {})
97
+ stubBrowser(
98
+ "https://app.example/login#error=access_denied&error_description=An+account+with+this+email+already+exists",
99
+ { [PROVIDER_KEY]: "sso" },
100
+ )
101
+ const onError = vi.fn()
102
+ const renderer = render(<SSOForm onError={onError} />)
103
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)) })
104
+
105
+ expect(textOf(renderer.root.findByProps({ role: "alert" }))).toBe("An account with this email already exists")
106
+ expect(onError).toHaveBeenCalledTimes(1)
107
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ provider: "sso", code: "access_denied" }))
108
+ })
109
+ })