@supatype/client 0.3.6 → 0.8.0
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.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +69 -30
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/auth-redirect.d.ts +48 -0
- package/dist/auth-redirect.d.ts.map +1 -0
- package/dist/auth-redirect.js +70 -0
- package/dist/auth-redirect.js.map +1 -0
- package/dist/auth.d.ts +86 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +383 -275
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +16 -0
- package/dist/bindings.d.ts.map +1 -0
- package/dist/bindings.js +13 -0
- package/dist/bindings.js.map +1 -0
- package/dist/caller-types.d.ts +18 -0
- package/dist/caller-types.d.ts.map +1 -0
- package/dist/caller-types.js +22 -0
- package/dist/caller-types.js.map +1 -0
- package/dist/draft-create.d.ts +12 -0
- package/dist/draft-create.d.ts.map +1 -0
- package/dist/draft-create.js +47 -0
- package/dist/draft-create.js.map +1 -0
- package/dist/draft-models-registry.d.ts +27 -0
- package/dist/draft-models-registry.d.ts.map +1 -0
- package/dist/draft-models-registry.js +61 -0
- package/dist/draft-models-registry.js.map +1 -0
- package/dist/error-codes-doc.d.ts +1 -1
- package/dist/error-codes-doc.d.ts.map +1 -1
- package/dist/error-codes-doc.js +42 -34
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +102 -60
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +69 -28
- package/dist/errors.js.map +1 -1
- package/dist/exact-response.d.ts.map +1 -1
- package/dist/exact-response.js +2 -1
- package/dist/exact-response.js.map +1 -1
- package/dist/exact-values.d.ts +2 -0
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +12 -10
- package/dist/exact-values.js.map +1 -1
- package/dist/fetch-with-retry.d.ts +21 -6
- package/dist/fetch-with-retry.d.ts.map +1 -1
- package/dist/fetch-with-retry.js +67 -53
- package/dist/fetch-with-retry.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +11 -3
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +10 -6
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/filters.d.ts +51 -0
- package/dist/filters.d.ts.map +1 -0
- package/dist/filters.js +117 -0
- package/dist/filters.js.map +1 -0
- package/dist/generated-client.d.ts +7 -0
- package/dist/generated-client.d.ts.map +1 -0
- package/dist/generated-client.js +7 -0
- package/dist/generated-client.js.map +1 -0
- package/dist/graphql-document.d.ts +39 -0
- package/dist/graphql-document.d.ts.map +1 -0
- package/dist/graphql-document.js +228 -0
- package/dist/graphql-document.js.map +1 -0
- package/dist/graphql-json.d.ts +56 -0
- package/dist/graphql-json.d.ts.map +1 -0
- package/dist/graphql-json.js +220 -0
- package/dist/graphql-json.js.map +1 -0
- package/dist/graphql-transport.d.ts +28 -0
- package/dist/graphql-transport.d.ts.map +1 -0
- package/dist/graphql-transport.js +77 -0
- package/dist/graphql-transport.js.map +1 -0
- package/dist/index.d.ts +103 -40
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +170 -165
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +61 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +83 -0
- package/dist/json.js.map +1 -0
- package/dist/jwt.d.ts +16 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +37 -0
- package/dist/jwt.js.map +1 -0
- package/dist/live-preview.d.ts +23 -0
- package/dist/live-preview.d.ts.map +1 -0
- package/dist/live-preview.js +28 -0
- package/dist/live-preview.js.map +1 -0
- package/dist/mutation-request.d.ts +17 -0
- package/dist/mutation-request.d.ts.map +1 -0
- package/dist/mutation-request.js +41 -0
- package/dist/mutation-request.js.map +1 -0
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +8 -6
- package/dist/preview.js.map +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +19 -13
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +108 -29
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +294 -224
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +57 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +300 -88
- package/dist/realtime.js.map +1 -1
- package/dist/select-types.d.ts +99 -0
- package/dist/select-types.d.ts.map +1 -0
- package/dist/select-types.js +2 -0
- package/dist/select-types.js.map +1 -0
- package/dist/storage.d.ts +81 -11
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +137 -38
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +69 -0
- package/dist/table-subscription.d.ts.map +1 -0
- package/dist/table-subscription.js +93 -0
- package/dist/table-subscription.js.map +1 -0
- package/dist/types.d.ts +98 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth-redirect.ts +90 -0
- package/src/auth.ts +434 -281
- package/src/bindings.ts +22 -0
- package/src/caller-types.ts +27 -0
- package/src/draft-create.ts +51 -0
- package/src/draft-models-registry.ts +81 -0
- package/src/error-codes-doc.ts +44 -35
- package/src/errors.ts +72 -28
- package/src/exact-response.ts +2 -1
- package/src/exact-values.ts +16 -9
- package/src/fetch-with-retry.ts +80 -70
- package/src/field-kinds-registry.ts +22 -9
- package/src/filters.ts +133 -0
- package/src/generated-client.ts +6 -0
- package/src/graphql-document.ts +234 -0
- package/src/graphql-json.ts +243 -0
- package/src/graphql-transport.ts +97 -0
- package/src/index.ts +289 -208
- package/src/json.ts +117 -0
- package/src/jwt.ts +37 -0
- package/src/live-preview.ts +37 -0
- package/src/mutation-request.ts +66 -0
- package/src/preview.ts +9 -11
- package/src/query-cache.ts +19 -16
- package/src/query.ts +389 -270
- package/src/realtime.ts +333 -90
- package/src/select-types.ts +184 -0
- package/src/storage.ts +223 -44
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +104 -5
- package/tests/auth-error-codes.test.ts +53 -0
- package/tests/auth-errors.test.ts +84 -0
- package/tests/auth-events.test.ts +136 -0
- package/tests/auth-url-session.test.ts +204 -0
- package/tests/auth.test.ts +187 -26
- package/tests/count.test.ts +60 -0
- package/tests/data-plane-auth.test.ts +21 -46
- package/tests/draft-insert.integration.test.ts +118 -0
- package/tests/draft-insert.test.ts +225 -0
- package/tests/draft-profile.test.ts +55 -84
- package/tests/draft-update.integration.test.ts +122 -0
- package/tests/draft-update.test.ts +174 -0
- package/tests/dynamic-headers.test.ts +45 -0
- package/tests/entry-points.test.ts +42 -0
- package/tests/exact-response.test.ts +4 -4
- package/tests/exact-values.test.ts +14 -25
- package/tests/field-kinds-registry.test.ts +3 -3
- package/tests/filters.test.ts +146 -0
- package/tests/graphql-json.test.ts +199 -0
- package/tests/helpers/mock-websocket.ts +44 -11
- package/tests/helpers/oauth-binding.ts +92 -0
- package/tests/helpers/signup-binding.ts +73 -0
- package/tests/helpers/socket-swap.ts +142 -0
- package/tests/mfa-totp-integration.test.ts +13 -20
- package/tests/postgrest-error-codes.test.ts +85 -0
- package/tests/query-cache.test.ts +116 -117
- package/tests/query.test.ts +29 -31
- package/tests/rate-limit-integration.test.ts +4 -12
- package/tests/realtime-ack-ref.test.ts +112 -0
- package/tests/realtime-exact-values.test.ts +2 -4
- package/tests/realtime-presence.test.ts +75 -0
- package/tests/realtime-session-auth.test.ts +2 -4
- package/tests/realtime-shared-channel.test.ts +209 -0
- package/tests/realtime-swap-status.test.ts +62 -0
- package/tests/retry-integration.test.ts +3 -8
- package/tests/retry-policy.test.ts +166 -0
- package/tests/rpc-resend.test.ts +24 -0
- package/tests/server-bodies.test.ts +187 -0
- package/tests/serverless.test.ts +2 -2
- package/tests/signed-url-absolute.test.ts +2 -5
- package/tests/storage-object-shape.test.ts +101 -0
- package/tests/storage-quota-integration.test.ts +7 -9
- package/tests/storage-reference-url.test.ts +51 -0
- package/tests/storage-upload-browser.test.ts +71 -0
- package/tests/storage-upload-limit-integration.test.ts +17 -31
- package/tests/storage-url-encoding.test.ts +52 -0
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/blob.ts +10 -0
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +41 -14
- package/tests/table-subscription.test.ts +105 -0
- package/tests/table-transport.test.ts +94 -0
- package/tests/tsconfig.json +1 -1
- package/tests/types.test.ts +153 -1
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { describe, it, expect, vi, afterEach } from "vitest"
|
|
2
|
+
import { AuthClient } from "../src/auth.js"
|
|
3
|
+
import { createClient } from "../src/index.js"
|
|
4
|
+
import type { AuthChangeEvent } from "../src/types.js"
|
|
5
|
+
import { fetchCall, fetchReturning, jsonBody } from "./support/fetch-mock.js"
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The OAuth return: the auth server sends the browser back with the session in the URL, as tokens in
|
|
9
|
+
* the fragment (implicit) or a `code` in the query (PKCE). The client finishes the sign-in itself on
|
|
10
|
+
* start, as supabase-js does with `detectSessionInUrl`, so no app has to read the URL.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const AUTH_URL = "http://localhost:9999/auth/v1"
|
|
14
|
+
const HEADERS = { apikey: "anon", "Content-Type": "application/json" }
|
|
15
|
+
const VERIFIER_KEY = "supatype.auth.session-code-verifier"
|
|
16
|
+
const PROVIDER_KEY = "supatype.auth.session-oauth-provider"
|
|
17
|
+
|
|
18
|
+
const RAW_USER = {
|
|
19
|
+
id: "user-1",
|
|
20
|
+
email: "ada@example.com",
|
|
21
|
+
created_at: "2024-01-01T00:00:00Z",
|
|
22
|
+
updated_at: "2024-01-01T00:00:00Z",
|
|
23
|
+
app_metadata: { provider: "github" },
|
|
24
|
+
user_metadata: { full_name: "Ada Lovelace" },
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function jsonResponse(body: unknown, status = 200): Response {
|
|
28
|
+
return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } })
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function accessToken(): string {
|
|
32
|
+
const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString("base64url")
|
|
33
|
+
return `eyJhbGciOiJub25lIn0.${payload}.sig`
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A browser at `href`, with a localStorage holding `stored`. */
|
|
37
|
+
function stubBrowser(href: string, stored: Record<string, string> = {}) {
|
|
38
|
+
const store = new Map(Object.entries(stored))
|
|
39
|
+
const replaceState = vi.fn<(state: unknown, unused: string, url: string) => void>()
|
|
40
|
+
vi.stubGlobal("window", {
|
|
41
|
+
location: { href, protocol: "https:" },
|
|
42
|
+
history: { state: null, replaceState },
|
|
43
|
+
localStorage: {
|
|
44
|
+
getItem: (k: string) => store.get(k) ?? null,
|
|
45
|
+
setItem: (k: string, v: string) => { store.set(k, v) },
|
|
46
|
+
removeItem: (k: string) => { store.delete(k) },
|
|
47
|
+
},
|
|
48
|
+
})
|
|
49
|
+
return { replaceState, store }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function recordEvents(client: AuthClient): AuthChangeEvent[] {
|
|
53
|
+
const events: AuthChangeEvent[] = []
|
|
54
|
+
client.onAuthStateChange((event) => { events.push(event) })
|
|
55
|
+
return events
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
afterEach(() => {
|
|
59
|
+
vi.unstubAllGlobals()
|
|
60
|
+
vi.restoreAllMocks()
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
describe("detectSessionInUrl", () => {
|
|
64
|
+
it("signs in from implicit-grant tokens in the fragment and cleans the URL", async () => {
|
|
65
|
+
const token = accessToken()
|
|
66
|
+
const { replaceState } = stubBrowser(
|
|
67
|
+
`https://app.example/welcome?tab=1#access_token=${token}&refresh_token=rt-1&expires_in=3600&token_type=bearer&provider_token=gh&sb=`,
|
|
68
|
+
)
|
|
69
|
+
const fetch = vi.fn().mockResolvedValue(jsonResponse(RAW_USER))
|
|
70
|
+
vi.stubGlobal("fetch", fetch)
|
|
71
|
+
|
|
72
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
73
|
+
const events = recordEvents(client)
|
|
74
|
+
const { error } = await client.initialize()
|
|
75
|
+
|
|
76
|
+
expect(error).toBeNull()
|
|
77
|
+
expect(fetch.mock.calls[0]?.[0]).toBe(`${AUTH_URL}/user`)
|
|
78
|
+
const { data } = await client.getSession()
|
|
79
|
+
expect(data.session?.accessToken).toBe(token)
|
|
80
|
+
expect(data.session?.user.userMetadata["full_name"]).toBe("Ada Lovelace")
|
|
81
|
+
expect(events).toEqual(["SIGNED_OUT", "SIGNED_IN"])
|
|
82
|
+
expect(replaceState).toHaveBeenCalledWith(null, "", "https://app.example/welcome?tab=1")
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
it("exchanges a PKCE code from the query and keeps the app's own parameters", async () => {
|
|
86
|
+
const { replaceState, store } = stubBrowser("https://app.example/cb?next=%2Fhome&code=auth-code-1", {
|
|
87
|
+
[VERIFIER_KEY]: "verifier-1",
|
|
88
|
+
})
|
|
89
|
+
const fetch = fetchReturning({ access_token: accessToken(), refresh_token: "rt-2", expires_in: 3600, token_type: "bearer", user: RAW_USER })
|
|
90
|
+
vi.stubGlobal("fetch", fetch)
|
|
91
|
+
|
|
92
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
93
|
+
const events = recordEvents(client)
|
|
94
|
+
const { error } = await client.initialize()
|
|
95
|
+
|
|
96
|
+
expect(error).toBeNull()
|
|
97
|
+
const { url, init } = fetchCall(fetch)
|
|
98
|
+
expect(url).toBe(`${AUTH_URL}/token?grant_type=pkce`)
|
|
99
|
+
expect(jsonBody(init)).toEqual({ auth_code: "auth-code-1", code_verifier: "verifier-1" })
|
|
100
|
+
expect(events).toEqual(["SIGNED_OUT", "SIGNED_IN"])
|
|
101
|
+
expect(store.has(VERIFIER_KEY)).toBe(false)
|
|
102
|
+
expect(replaceState).toHaveBeenCalledWith(null, "", "https://app.example/cb?next=%2Fhome")
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
it("leaves a `code` alone when this client started no PKCE flow", async () => {
|
|
106
|
+
const { replaceState } = stubBrowser("https://app.example/invite?code=team-42")
|
|
107
|
+
const fetch = vi.fn()
|
|
108
|
+
vi.stubGlobal("fetch", fetch)
|
|
109
|
+
|
|
110
|
+
const { error } = await new AuthClient(AUTH_URL, HEADERS).initialize()
|
|
111
|
+
|
|
112
|
+
expect(error).toBeNull()
|
|
113
|
+
expect(fetch).not.toHaveBeenCalled()
|
|
114
|
+
expect(replaceState).not.toHaveBeenCalled()
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
it("reports a refused sign-in from the URL, naming the provider that was started, and cleans it", async () => {
|
|
118
|
+
const { replaceState } = stubBrowser(
|
|
119
|
+
"https://app.example/?error=access_denied&error_code=signup_disabled&error_description=Signups+not+allowed#error=access_denied&error_code=signup_disabled&error_description=Signups+not+allowed&sb=",
|
|
120
|
+
{ [PROVIDER_KEY]: "github" },
|
|
121
|
+
)
|
|
122
|
+
vi.stubGlobal("fetch", vi.fn())
|
|
123
|
+
|
|
124
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
125
|
+
const { error } = await client.initialize()
|
|
126
|
+
|
|
127
|
+
expect(error?.message).toBe("Signups not allowed")
|
|
128
|
+
expect(error?.code).toBe("signup_disabled")
|
|
129
|
+
expect(error?.provider).toBe("github")
|
|
130
|
+
expect((await client.getSession()).data.session).toBeNull()
|
|
131
|
+
expect(replaceState).toHaveBeenCalledWith(null, "", "https://app.example/")
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
it("does nothing when the app opts out", async () => {
|
|
135
|
+
const { replaceState } = stubBrowser(`https://app.example/#access_token=${accessToken()}&refresh_token=rt-1`)
|
|
136
|
+
const fetch = vi.fn()
|
|
137
|
+
vi.stubGlobal("fetch", fetch)
|
|
138
|
+
|
|
139
|
+
const client = createClient({ url: "http://localhost:9999", anonKey: "anon", auth: { detectSessionInUrl: false } })
|
|
140
|
+
const { error } = await client.auth.initialize()
|
|
141
|
+
|
|
142
|
+
expect(error).toBeNull()
|
|
143
|
+
expect(fetch).not.toHaveBeenCalled()
|
|
144
|
+
expect(replaceState).not.toHaveBeenCalled()
|
|
145
|
+
expect((await client.auth.getSession()).data.session).toBeNull()
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
it("is on by default through createClient", async () => {
|
|
149
|
+
stubBrowser(`https://app.example/#access_token=${accessToken()}&refresh_token=rt-1`)
|
|
150
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(RAW_USER)))
|
|
151
|
+
|
|
152
|
+
const client = createClient({ url: "http://localhost:9999", anonKey: "anon" })
|
|
153
|
+
|
|
154
|
+
expect((await client.auth.getSession()).data.session?.user.id).toBe("user-1")
|
|
155
|
+
})
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
describe("signInWithOAuth checks the provider is enabled", () => {
|
|
159
|
+
const settings = (external: Record<string, boolean>) => jsonResponse({ external, disable_signup: false })
|
|
160
|
+
|
|
161
|
+
it("refuses a provider the server has not enabled, before any redirect", async () => {
|
|
162
|
+
const fetch = vi.fn().mockResolvedValue(settings({ github: false, google: true }))
|
|
163
|
+
vi.stubGlobal("fetch", fetch)
|
|
164
|
+
|
|
165
|
+
const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "github" })
|
|
166
|
+
|
|
167
|
+
expect(fetch.mock.calls[0]?.[0]).toBe(`${AUTH_URL}/settings`)
|
|
168
|
+
expect(error?.code).toBe("provider_disabled")
|
|
169
|
+
expect(error?.message).toBe("Sign-in with github is not enabled for this project.")
|
|
170
|
+
expect(data.url).toBe("")
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
it("returns the authorize URL for an enabled provider and remembers which one was started", async () => {
|
|
174
|
+
const { store } = stubBrowser("https://app.example/")
|
|
175
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(settings({ github: true })))
|
|
176
|
+
|
|
177
|
+
const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "github" })
|
|
178
|
+
|
|
179
|
+
expect(error).toBeNull()
|
|
180
|
+
expect(data.url).toBe(`${AUTH_URL}/authorize?provider=github`)
|
|
181
|
+
expect(store.get(PROVIDER_KEY)).toBe("github")
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
it("matches the provider as the server does, whatever its case", async () => {
|
|
185
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(settings({ github: false, google: true })))
|
|
186
|
+
|
|
187
|
+
const off = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "GitHub" })
|
|
188
|
+
expect(off.error?.code).toBe("provider_disabled")
|
|
189
|
+
|
|
190
|
+
const on = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "Google" })
|
|
191
|
+
expect(on.error).toBeNull()
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
it("lets the server decide when the settings cannot be read or do not list the provider", async () => {
|
|
195
|
+
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("offline")))
|
|
196
|
+
const offline = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "github" })
|
|
197
|
+
expect(offline.error).toBeNull()
|
|
198
|
+
|
|
199
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(settings({ github: false })))
|
|
200
|
+
const custom = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "custom:acme" })
|
|
201
|
+
expect(custom.error).toBeNull()
|
|
202
|
+
expect(custom.data.url).toContain("provider=custom%3Aacme")
|
|
203
|
+
})
|
|
204
|
+
})
|
package/tests/auth.test.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
2
|
import { AuthClient } from "../src/auth.js"
|
|
3
|
+
import type { AuthStorage } from "../src/types.js"
|
|
4
|
+
import { fetchCall, fetchReturning, header, jsonBody, type FetchMock } from "./support/fetch-mock.js"
|
|
3
5
|
|
|
4
6
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
5
7
|
|
|
@@ -24,13 +26,8 @@ const TOKEN_RESPONSE = {
|
|
|
24
26
|
user: RAW_USER,
|
|
25
27
|
}
|
|
26
28
|
|
|
27
|
-
function mockFetch(body: unknown, ok = true, status?: number):
|
|
28
|
-
return
|
|
29
|
-
ok,
|
|
30
|
-
status: status ?? (ok ? 200 : 400),
|
|
31
|
-
json: vi.fn().mockResolvedValue(body),
|
|
32
|
-
headers: { get: () => null },
|
|
33
|
-
})
|
|
29
|
+
function mockFetch(body: unknown, ok = true, status?: number): FetchMock {
|
|
30
|
+
return fetchReturning(body, status ?? (ok ? 200 : 400))
|
|
34
31
|
}
|
|
35
32
|
|
|
36
33
|
function freshClient(): AuthClient {
|
|
@@ -61,8 +58,7 @@ describe("AuthClient.signUp()", () => {
|
|
|
61
58
|
|
|
62
59
|
await freshClient().signUp({ email: "a@b.com", password: "s", options: { data: { name: "Alice" } } })
|
|
63
60
|
|
|
64
|
-
const
|
|
65
|
-
const body = JSON.parse(opts.body as string) as Record<string, unknown>
|
|
61
|
+
const body = jsonBody(fetchCall(fetch).init)
|
|
66
62
|
expect(body["data"]).toEqual({ name: "Alice" })
|
|
67
63
|
})
|
|
68
64
|
|
|
@@ -89,6 +85,52 @@ describe("AuthClient.signUp()", () => {
|
|
|
89
85
|
})
|
|
90
86
|
})
|
|
91
87
|
|
|
88
|
+
describe("AuthClient.signUp() waiting for email confirmation", () => {
|
|
89
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
90
|
+
|
|
91
|
+
// With confirmation on, /signup answers with the bare user and no tokens.
|
|
92
|
+
const PENDING_USER = { ...RAW_USER, id: "user-pending", confirmation_sent_at: "2024-01-01T00:00:00Z" }
|
|
93
|
+
|
|
94
|
+
it("returns the user with a null session", async () => {
|
|
95
|
+
vi.stubGlobal("fetch", mockFetch(PENDING_USER))
|
|
96
|
+
|
|
97
|
+
const { data, error } = await freshClient().signUp({ email: "a@b.com", password: "s" })
|
|
98
|
+
|
|
99
|
+
expect(error).toBeNull()
|
|
100
|
+
expect(data.session).toBeNull()
|
|
101
|
+
expect(data.user?.id).toBe("user-pending")
|
|
102
|
+
expect(data.user?.email).toBe("test@example.com")
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
it("stores nothing and emits no SIGNED_IN", async () => {
|
|
106
|
+
const storage = {
|
|
107
|
+
getItem: vi.fn().mockResolvedValue(null),
|
|
108
|
+
setItem: vi.fn().mockResolvedValue(undefined),
|
|
109
|
+
removeItem: vi.fn().mockResolvedValue(undefined),
|
|
110
|
+
}
|
|
111
|
+
const client = new AuthClient(SUPATYPE_URL, HEADERS, { storage })
|
|
112
|
+
await client.whenReady()
|
|
113
|
+
const events: string[] = []
|
|
114
|
+
client.onAuthStateChange((event) => events.push(event))
|
|
115
|
+
vi.stubGlobal("fetch", mockFetch(PENDING_USER))
|
|
116
|
+
|
|
117
|
+
await client.signUp({ email: "a@b.com", password: "s" })
|
|
118
|
+
|
|
119
|
+
expect(storage.setItem).not.toHaveBeenCalled()
|
|
120
|
+
expect(events).not.toContain("SIGNED_IN")
|
|
121
|
+
expect((await client.getSession()).data.session).toBeNull()
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
it("keeps the empty identities of the answer for an address already registered", async () => {
|
|
125
|
+
vi.stubGlobal("fetch", mockFetch({ ...PENDING_USER, identities: [] }))
|
|
126
|
+
|
|
127
|
+
const { data } = await freshClient().signUp({ email: "a@b.com", password: "s" })
|
|
128
|
+
|
|
129
|
+
expect(data.session).toBeNull()
|
|
130
|
+
expect(data.user?.identities).toEqual([])
|
|
131
|
+
})
|
|
132
|
+
})
|
|
133
|
+
|
|
92
134
|
describe("AuthClient.signInAnonymously()", () => {
|
|
93
135
|
beforeEach(() => vi.restoreAllMocks())
|
|
94
136
|
|
|
@@ -114,8 +156,7 @@ describe("AuthClient.signInAnonymously()", () => {
|
|
|
114
156
|
`${SUPATYPE_URL}/signup`,
|
|
115
157
|
expect.objectContaining({ method: "POST" }),
|
|
116
158
|
)
|
|
117
|
-
const
|
|
118
|
-
const body = JSON.parse(opts.body as string) as Record<string, unknown>
|
|
159
|
+
const body = jsonBody(fetchCall(fetch).init)
|
|
119
160
|
expect(body["email"]).toBeUndefined()
|
|
120
161
|
expect(body["password"]).toBeUndefined()
|
|
121
162
|
})
|
|
@@ -128,8 +169,7 @@ describe("AuthClient.signInAnonymously()", () => {
|
|
|
128
169
|
options: { data: { guest: true }, captchaToken: "captcha-123" },
|
|
129
170
|
})
|
|
130
171
|
|
|
131
|
-
const
|
|
132
|
-
const body = JSON.parse(opts.body as string) as Record<string, unknown>
|
|
172
|
+
const body = jsonBody(fetchCall(fetch).init)
|
|
133
173
|
expect(body["data"]).toEqual({ guest: true })
|
|
134
174
|
expect(body["supatype_meta_security"]).toEqual({ captcha_token: "captcha-123" })
|
|
135
175
|
})
|
|
@@ -167,7 +207,7 @@ describe("AuthClient.signInWithPassword()", () => {
|
|
|
167
207
|
|
|
168
208
|
await freshClient().signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
169
209
|
|
|
170
|
-
const
|
|
210
|
+
const { url } = fetchCall(fetch)
|
|
171
211
|
expect(url).toBe(`${SUPATYPE_URL}/token?grant_type=password`)
|
|
172
212
|
})
|
|
173
213
|
|
|
@@ -192,13 +232,13 @@ describe("AuthClient.signInWithPassword()", () => {
|
|
|
192
232
|
})
|
|
193
233
|
|
|
194
234
|
describe("AuthClient.signInWithOAuth()", () => {
|
|
195
|
-
it("returns redirect URL
|
|
235
|
+
it("returns redirect URL after reading only the provider settings", async () => {
|
|
196
236
|
const fetchSpy = vi.fn()
|
|
197
237
|
vi.stubGlobal("fetch", fetchSpy)
|
|
198
238
|
|
|
199
239
|
const { data, error } = await freshClient().signInWithOAuth({ provider: "google" })
|
|
200
240
|
|
|
201
|
-
expect(fetchSpy
|
|
241
|
+
expect(fetchSpy.mock.calls.map(([url]) => String(url))).toEqual([`${SUPATYPE_URL}/settings`])
|
|
202
242
|
expect(error).toBeNull()
|
|
203
243
|
expect(data.url).toContain("authorize")
|
|
204
244
|
expect(data.url).toContain("provider=google")
|
|
@@ -215,6 +255,24 @@ describe("AuthClient.signInWithOAuth()", () => {
|
|
|
215
255
|
|
|
216
256
|
expect(data.url).toContain("redirect_to=")
|
|
217
257
|
})
|
|
258
|
+
|
|
259
|
+
it("adds queryParams to /authorize without letting them replace the flow's own", async () => {
|
|
260
|
+
vi.stubGlobal("fetch", vi.fn())
|
|
261
|
+
|
|
262
|
+
const { data } = await freshClient().signInWithOAuth({
|
|
263
|
+
provider: "keycloak",
|
|
264
|
+
options: {
|
|
265
|
+
flowType: "pkce",
|
|
266
|
+
queryParams: { studio: "1", provider: "github", code_challenge: "forged" },
|
|
267
|
+
},
|
|
268
|
+
})
|
|
269
|
+
|
|
270
|
+
const query = new URL(data.url).searchParams
|
|
271
|
+
expect(query.get("studio")).toBe("1")
|
|
272
|
+
expect(query.getAll("provider")).toEqual(["keycloak"])
|
|
273
|
+
expect(query.getAll("code_challenge")).toHaveLength(1)
|
|
274
|
+
expect(query.get("code_challenge")).not.toBe("forged")
|
|
275
|
+
})
|
|
218
276
|
})
|
|
219
277
|
|
|
220
278
|
describe("AuthClient.signOut()", () => {
|
|
@@ -225,13 +283,13 @@ describe("AuthClient.signOut()", () => {
|
|
|
225
283
|
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
226
284
|
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
227
285
|
|
|
228
|
-
const logoutFetch =
|
|
286
|
+
const logoutFetch = fetchReturning(null, 204)
|
|
229
287
|
vi.stubGlobal("fetch", logoutFetch)
|
|
230
288
|
await client.signOut()
|
|
231
289
|
|
|
232
|
-
const
|
|
290
|
+
const { url, init } = fetchCall(logoutFetch)
|
|
233
291
|
expect(url).toBe(`${SUPATYPE_URL}/logout`)
|
|
234
|
-
expect(
|
|
292
|
+
expect(init.method).toBe("POST")
|
|
235
293
|
})
|
|
236
294
|
|
|
237
295
|
it("clears session after sign out", async () => {
|
|
@@ -345,8 +403,7 @@ describe("AuthClient.getSession() / getUser()", () => {
|
|
|
345
403
|
|
|
346
404
|
expect(error).toBeNull()
|
|
347
405
|
expect(data.user?.id).toBe("user-1")
|
|
348
|
-
|
|
349
|
-
expect((opts.headers as Record<string, string>)["Authorization"]).toContain("Bearer access-token-123")
|
|
406
|
+
expect(header(fetchCall(userFetch).init, "Authorization")).toContain("Bearer access-token-123")
|
|
350
407
|
})
|
|
351
408
|
})
|
|
352
409
|
|
|
@@ -412,7 +469,7 @@ describe("AuthClient custom storage", () => {
|
|
|
412
469
|
it("persists session to custom storage on sign in", async () => {
|
|
413
470
|
const storage = {
|
|
414
471
|
getItem: vi.fn().mockResolvedValue(null),
|
|
415
|
-
setItem: vi.fn().mockResolvedValue(undefined),
|
|
472
|
+
setItem: vi.fn<AuthStorage["setItem"]>().mockResolvedValue(undefined),
|
|
416
473
|
removeItem: vi.fn().mockResolvedValue(undefined),
|
|
417
474
|
}
|
|
418
475
|
const client = new AuthClient(SUPATYPE_URL, HEADERS, { storage })
|
|
@@ -422,9 +479,10 @@ describe("AuthClient custom storage", () => {
|
|
|
422
479
|
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
423
480
|
|
|
424
481
|
expect(storage.setItem).toHaveBeenCalled()
|
|
425
|
-
const [key, value] = storage.setItem.mock.calls[0]
|
|
482
|
+
const [key, value] = storage.setItem.mock.calls[0] ?? []
|
|
426
483
|
expect(key).toBe("supatype.auth.session")
|
|
427
|
-
|
|
484
|
+
const stored = JSON.parse(value ?? "null")
|
|
485
|
+
expect(stored).toHaveProperty("accessToken", "access-token-123")
|
|
428
486
|
})
|
|
429
487
|
|
|
430
488
|
it("survives corrupt async storage without throwing", async () => {
|
|
@@ -513,8 +571,7 @@ describe("AuthClient OAuth session completion", () => {
|
|
|
513
571
|
`${SUPATYPE_URL}/token?grant_type=pkce`,
|
|
514
572
|
expect.objectContaining({ method: "POST" }),
|
|
515
573
|
)
|
|
516
|
-
const
|
|
517
|
-
const body = JSON.parse(opts.body as string) as Record<string, unknown>
|
|
574
|
+
const body = jsonBody(fetchCall(fetch).init)
|
|
518
575
|
expect(body["auth_code"]).toBe("auth-code-xyz")
|
|
519
576
|
expect(typeof body["code_verifier"]).toBe("string")
|
|
520
577
|
expect(storage.removeItem).toHaveBeenCalledWith("supatype.auth.session-code-verifier")
|
|
@@ -623,3 +680,107 @@ describe("AuthClient stale persisted session", () => {
|
|
|
623
680
|
expect(events).toContain("SIGNED_OUT")
|
|
624
681
|
})
|
|
625
682
|
})
|
|
683
|
+
|
|
684
|
+
// The server reads `redirect_to` from the query string (or a header), never from a JSON body. A
|
|
685
|
+
// redirect sent anywhere else is dropped without an error, and the email links to SITE_URL instead,
|
|
686
|
+
// which on a phone is not the deep link the app listens for.
|
|
687
|
+
describe("email links carry the caller's redirect", () => {
|
|
688
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
689
|
+
|
|
690
|
+
function calledUrl(fetchSpy: FetchMock): URL {
|
|
691
|
+
return new URL(fetchCall(fetchSpy).url)
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
it("signInWithOtp sends emailRedirectTo as the redirect_to query parameter", async () => {
|
|
695
|
+
const fetchSpy = mockFetch({})
|
|
696
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
697
|
+
await freshClient().signInWithOtp({
|
|
698
|
+
email: "test@example.com",
|
|
699
|
+
options: { emailRedirectTo: "myapp://auth/callback" },
|
|
700
|
+
})
|
|
701
|
+
const url = calledUrl(fetchSpy)
|
|
702
|
+
expect(url.pathname).toBe("/otp")
|
|
703
|
+
expect(url.searchParams.get("redirect_to")).toBe("myapp://auth/callback")
|
|
704
|
+
})
|
|
705
|
+
|
|
706
|
+
it("signInWithOtp sends no redirect_to when none is given", async () => {
|
|
707
|
+
const fetchSpy = mockFetch({})
|
|
708
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
709
|
+
await freshClient().signInWithOtp({ email: "test@example.com" })
|
|
710
|
+
expect(calledUrl(fetchSpy).searchParams.has("redirect_to")).toBe(false)
|
|
711
|
+
})
|
|
712
|
+
|
|
713
|
+
it("resetPasswordForEmail sends redirectTo as the redirect_to query parameter", async () => {
|
|
714
|
+
const fetchSpy = mockFetch({})
|
|
715
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
716
|
+
await freshClient().resetPasswordForEmail("test@example.com", { redirectTo: "myapp://auth/callback" })
|
|
717
|
+
const url = calledUrl(fetchSpy)
|
|
718
|
+
expect(url.pathname).toBe("/recover")
|
|
719
|
+
expect(url.searchParams.get("redirect_to")).toBe("myapp://auth/callback")
|
|
720
|
+
})
|
|
721
|
+
})
|
|
722
|
+
|
|
723
|
+
// ─── autoRefreshToken ────────────────────────────────────────────────────────
|
|
724
|
+
|
|
725
|
+
describe("AuthClient autoRefreshToken", () => {
|
|
726
|
+
/** A session whose access token expired a minute ago. */
|
|
727
|
+
const expired = {
|
|
728
|
+
accessToken: "expired-token",
|
|
729
|
+
refreshToken: "refresh-token-abc",
|
|
730
|
+
tokenType: "bearer",
|
|
731
|
+
expiresIn: 3600,
|
|
732
|
+
expiresAt: Math.floor(Date.now() / 1000) - 60,
|
|
733
|
+
user: { id: "user-1", appMetadata: {}, userMetadata: {}, createdAt: "", updatedAt: "" },
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
it("schedules a refresh timer by default", () => {
|
|
737
|
+
vi.useFakeTimers()
|
|
738
|
+
try {
|
|
739
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
740
|
+
new AuthClient(SUPATYPE_URL, HEADERS, { initialSession: { ...expired, expiresAt: expired.expiresAt + 7200 } })
|
|
741
|
+
expect(vi.getTimerCount()).toBe(1)
|
|
742
|
+
} finally {
|
|
743
|
+
vi.useRealTimers()
|
|
744
|
+
vi.unstubAllGlobals()
|
|
745
|
+
}
|
|
746
|
+
})
|
|
747
|
+
|
|
748
|
+
it("schedules nothing and refreshes nothing on its own when off", async () => {
|
|
749
|
+
vi.useFakeTimers()
|
|
750
|
+
const fetchSpy = mockFetch(TOKEN_RESPONSE)
|
|
751
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
752
|
+
try {
|
|
753
|
+
const client = new AuthClient(SUPATYPE_URL, HEADERS, { initialSession: expired, autoRefreshToken: false })
|
|
754
|
+
await vi.runAllTimersAsync()
|
|
755
|
+
expect(vi.getTimerCount()).toBe(0)
|
|
756
|
+
expect(fetchSpy).not.toHaveBeenCalled()
|
|
757
|
+
|
|
758
|
+
// A caller that needs a valid token still gets one, and refreshing schedules nothing either.
|
|
759
|
+
await client.ensureValidSession()
|
|
760
|
+
expect(client.currentAccessToken).toBe("access-token-123")
|
|
761
|
+
expect(vi.getTimerCount()).toBe(0)
|
|
762
|
+
} finally {
|
|
763
|
+
vi.useRealTimers()
|
|
764
|
+
vi.unstubAllGlobals()
|
|
765
|
+
}
|
|
766
|
+
})
|
|
767
|
+
|
|
768
|
+
it("leaves an expired session as it is when refreshExpiredToken is off", async () => {
|
|
769
|
+
const fetchSpy = mockFetch(TOKEN_RESPONSE)
|
|
770
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
771
|
+
try {
|
|
772
|
+
const client = new AuthClient(SUPATYPE_URL, HEADERS, {
|
|
773
|
+
initialSession: expired,
|
|
774
|
+
autoRefreshToken: false,
|
|
775
|
+
refreshExpiredToken: false,
|
|
776
|
+
})
|
|
777
|
+
await client.ensureValidSession()
|
|
778
|
+
const { data } = await client.getSession()
|
|
779
|
+
expect(fetchSpy).not.toHaveBeenCalled()
|
|
780
|
+
expect(client.currentAccessToken).toBe("expired-token")
|
|
781
|
+
expect(data.session?.refreshToken).toBe("refresh-token-abc")
|
|
782
|
+
} finally {
|
|
783
|
+
vi.unstubAllGlobals()
|
|
784
|
+
}
|
|
785
|
+
})
|
|
786
|
+
})
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
|
+
import { QueryBuilder, parseContentRangeTotal } from "../src/query.js"
|
|
3
|
+
|
|
4
|
+
const BASE = "http://localhost:18473"
|
|
5
|
+
const PATH = "/rest/v1/posts"
|
|
6
|
+
const HEADERS: Record<string, string> = { apikey: "anon-key" }
|
|
7
|
+
|
|
8
|
+
/** PostgREST's answer, with the Content-Range it sends on every read. */
|
|
9
|
+
function stubRange(contentRange: string, rows: unknown[] = [{ id: 1 }, { id: 2 }], status = 200): void {
|
|
10
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
|
11
|
+
ok: true,
|
|
12
|
+
status,
|
|
13
|
+
json: vi.fn().mockResolvedValue(rows),
|
|
14
|
+
text: vi.fn().mockResolvedValue(JSON.stringify(rows)),
|
|
15
|
+
headers: { get: (key: string) => (key.toLowerCase() === "content-range" ? contentRange : null) },
|
|
16
|
+
}))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
describe("count", () => {
|
|
20
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
21
|
+
|
|
22
|
+
it("is null when no count was asked for, though PostgREST sends `0-1/*`", async () => {
|
|
23
|
+
stubRange("0-1/*")
|
|
24
|
+
const { count, error } = await new QueryBuilder(BASE, PATH, HEADERS)
|
|
25
|
+
expect(error).toBeNull()
|
|
26
|
+
expect(count).toBeNull()
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it("is null from maybeSingle when no count was asked for", async () => {
|
|
30
|
+
stubRange("0-0/*", [{ id: 1 }])
|
|
31
|
+
const { count } = await new QueryBuilder(BASE, PATH, HEADERS).maybeSingle()
|
|
32
|
+
expect(count).toBeNull()
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it("is the total when a count was asked for", async () => {
|
|
36
|
+
stubRange("0-1/42", [{ id: 1 }, { id: 2 }], 206)
|
|
37
|
+
const { count } = await new QueryBuilder(BASE, PATH, HEADERS, "*", undefined, undefined, { count: "exact" })
|
|
38
|
+
expect(count).toBe(42)
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it("is the total for an empty page, `*/0`", async () => {
|
|
42
|
+
stubRange("*/0", [])
|
|
43
|
+
const { count } = await new QueryBuilder(BASE, PATH, HEADERS, "*", undefined, undefined, { count: "exact" })
|
|
44
|
+
expect(count).toBe(0)
|
|
45
|
+
})
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
describe("parseContentRangeTotal", () => {
|
|
49
|
+
it.each([
|
|
50
|
+
["0-24/3573458", 3573458],
|
|
51
|
+
["*/42", 42],
|
|
52
|
+
["0-1/*", null],
|
|
53
|
+
["*/*", null],
|
|
54
|
+
["garbage", null],
|
|
55
|
+
["0-1/12abc", null],
|
|
56
|
+
[null, null],
|
|
57
|
+
])("%s -> %s", (header, expected) => {
|
|
58
|
+
expect(parseContentRangeTotal(header)).toBe(expected)
|
|
59
|
+
})
|
|
60
|
+
})
|