@supatype/client 0.3.5 → 0.7.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 +58 -31
- 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 +78 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +373 -274
- 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 +153 -157
- 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 +20 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +105 -12
- 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 +129 -37
- 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 +84 -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 +421 -280
- 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 +272 -201
- 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 +116 -13
- package/src/select-types.ts +184 -0
- package/src/storage.ts +214 -43
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +90 -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 +122 -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 +139 -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-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-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 +139 -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 +3 -2
- 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 +12 -22
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +13 -13
- 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
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,42 @@ 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
|
+
})
|
|
@@ -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
|
+
})
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
6
6
|
import { createClient } from "../src/index.js"
|
|
7
|
+
import { fetchCalls, header, jsonResponse, requestUrl } from "./support/fetch-mock.js"
|
|
7
8
|
|
|
8
9
|
const BASE = "http://localhost:18473"
|
|
9
10
|
const ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiJ9.test"
|
|
@@ -67,29 +68,18 @@ describe("createClient data plane auth", () => {
|
|
|
67
68
|
}
|
|
68
69
|
store.set("supatype.auth.session", JSON.stringify(expiredSession))
|
|
69
70
|
|
|
70
|
-
const fetchSpy = vi.fn(async (
|
|
71
|
-
if (
|
|
72
|
-
return {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
expires_at: Math.floor(Date.now() / 1000) + 3600,
|
|
81
|
-
user: RAW_USER,
|
|
82
|
-
}),
|
|
83
|
-
headers: { get: (): string | null => null },
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
return {
|
|
87
|
-
ok: true,
|
|
88
|
-
status: 200,
|
|
89
|
-
json: async () => [{ id: "1", title: "Hello" }],
|
|
90
|
-
text: async () => JSON.stringify([{ id: "1", title: "Hello" }]),
|
|
91
|
-
headers: { get: (): string | null => null },
|
|
71
|
+
const fetchSpy = vi.fn<typeof fetch>(async (input) => {
|
|
72
|
+
if (requestUrl(input).includes("/auth/v1/token")) {
|
|
73
|
+
return jsonResponse({
|
|
74
|
+
access_token: freshAccess,
|
|
75
|
+
refresh_token: "rotated-refresh",
|
|
76
|
+
token_type: "bearer",
|
|
77
|
+
expires_in: 3600,
|
|
78
|
+
expires_at: Math.floor(Date.now() / 1000) + 3600,
|
|
79
|
+
user: RAW_USER,
|
|
80
|
+
})
|
|
92
81
|
}
|
|
82
|
+
return jsonResponse([{ id: "1", title: "Hello" }])
|
|
93
83
|
})
|
|
94
84
|
vi.stubGlobal("fetch", fetchSpy)
|
|
95
85
|
|
|
@@ -99,14 +89,12 @@ describe("createClient data plane auth", () => {
|
|
|
99
89
|
expect(error).toBeNull()
|
|
100
90
|
expect(data).toEqual([{ id: "1", title: "Hello" }])
|
|
101
91
|
|
|
102
|
-
const restCall = fetchSpy.
|
|
103
|
-
String(url).includes("/rest/v1/post"),
|
|
104
|
-
) as [string, RequestInit] | undefined
|
|
92
|
+
const restCall = fetchCalls(fetchSpy).find(({ url }) => url.includes("/rest/v1/post"))
|
|
105
93
|
expect(restCall).toBeDefined()
|
|
106
|
-
expect((restCall
|
|
94
|
+
expect(header(restCall?.init ?? {}, "Authorization")).toBe(
|
|
107
95
|
`Bearer ${freshAccess}`,
|
|
108
96
|
)
|
|
109
|
-
expect(fetchSpy.
|
|
97
|
+
expect(fetchCalls(fetchSpy).some(({ url }) => url.includes(`${AUTH}/token`))).toBe(true)
|
|
110
98
|
})
|
|
111
99
|
|
|
112
100
|
it("falls back to anon headers after refresh fails", async () => {
|
|
@@ -125,22 +113,11 @@ describe("createClient data plane auth", () => {
|
|
|
125
113
|
}
|
|
126
114
|
store.set("supatype.auth.session", JSON.stringify(expiredSession))
|
|
127
115
|
|
|
128
|
-
const fetchSpy = vi.fn(async (
|
|
129
|
-
if (
|
|
130
|
-
return {
|
|
131
|
-
ok: false,
|
|
132
|
-
status: 400,
|
|
133
|
-
json: async () => ({ error_description: "Invalid Refresh Token" }),
|
|
134
|
-
headers: { get: (): string | null => null },
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
return {
|
|
138
|
-
ok: true,
|
|
139
|
-
status: 200,
|
|
140
|
-
json: async () => [{ id: "1", title: "Anon ok" }],
|
|
141
|
-
text: async () => JSON.stringify([{ id: "1", title: "Anon ok" }]),
|
|
142
|
-
headers: { get: (): string | null => null },
|
|
116
|
+
const fetchSpy = vi.fn<typeof fetch>(async (input) => {
|
|
117
|
+
if (requestUrl(input).includes("/auth/v1/token")) {
|
|
118
|
+
return jsonResponse({ error_description: "Invalid Refresh Token" }, 400)
|
|
143
119
|
}
|
|
120
|
+
return jsonResponse([{ id: "1", title: "Anon ok" }])
|
|
144
121
|
})
|
|
145
122
|
vi.stubGlobal("fetch", fetchSpy)
|
|
146
123
|
|
|
@@ -150,10 +127,8 @@ describe("createClient data plane auth", () => {
|
|
|
150
127
|
expect(error).toBeNull()
|
|
151
128
|
expect(data).toEqual([{ id: "1", title: "Anon ok" }])
|
|
152
129
|
|
|
153
|
-
const restCall = fetchSpy.
|
|
154
|
-
|
|
155
|
-
) as [string, RequestInit] | undefined
|
|
156
|
-
expect((restCall![1].headers as Record<string, string>)["Authorization"]).toBe(
|
|
130
|
+
const restCall = fetchCalls(fetchSpy).find(({ url }) => url.includes("/rest/v1/post"))
|
|
131
|
+
expect(header(restCall?.init ?? {}, "Authorization")).toBe(
|
|
157
132
|
`Bearer ${ANON_KEY}`,
|
|
158
133
|
)
|
|
159
134
|
expect(store.get("supatype.auth.session")).toBeUndefined()
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto"
|
|
2
|
+
import { createServer, request, type IncomingMessage, type Server, type ServerResponse } from "node:http"
|
|
3
|
+
import type { AddressInfo } from "node:net"
|
|
4
|
+
import { afterAll, beforeAll, describe, expect, it } from "vitest"
|
|
5
|
+
import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase } from "../src/index.js"
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* An editor's insert on a drafts model whose read rule hides unpublished records, against a real
|
|
9
|
+
* PostgREST and Postgres.
|
|
10
|
+
*
|
|
11
|
+
* The model is `posts` from the engine's `versioned_blog` fixture with the access rules of a real
|
|
12
|
+
* blog: read `published_at <= now()`, create and update for the `editor` role. The caller is an API
|
|
13
|
+
* editor (the `authenticated` role with `app_metadata.role = "editor"`) with no Studio membership, so
|
|
14
|
+
* nothing shows them every draft. A plain insert asking for the row back is refused for them with
|
|
15
|
+
* `42501`, since Postgres checks the returned row against the read rule before anything has made it
|
|
16
|
+
* visible to its author; the client's insert goes through `supatype.create_record` instead.
|
|
17
|
+
*
|
|
18
|
+
* Needs `SUPATYPE_DRAFTS_REST_URL` (PostgREST's root, exposing `public`, `draft` and `supatype`)
|
|
19
|
+
* and `SUPATYPE_DRAFTS_JWT_SECRET` (its JWT secret), with that schema pushed by the engine. Skips
|
|
20
|
+
* otherwise. PostgREST serves at its root, so a small proxy here strips `/rest/v1` as the gateway
|
|
21
|
+
* does.
|
|
22
|
+
*/
|
|
23
|
+
const restUrl = process.env["SUPATYPE_DRAFTS_REST_URL"]
|
|
24
|
+
const jwtSecret = process.env["SUPATYPE_DRAFTS_JWT_SECRET"]
|
|
25
|
+
const EDITOR = "11111111-1111-1111-1111-111111111111"
|
|
26
|
+
|
|
27
|
+
/** An HS256 token carrying `claims`, signed as the auth server signs one. */
|
|
28
|
+
function token(claims: Record<string, unknown>): string {
|
|
29
|
+
const part = (value: object): string => Buffer.from(JSON.stringify(value)).toString("base64url")
|
|
30
|
+
const unsigned = `${part({ alg: "HS256", typ: "JWT" })}.${part({ ...claims, exp: Math.floor(Date.now() / 1000) + 600 })}`
|
|
31
|
+
return `${unsigned}.${createHmac("sha256", jwtSecret ?? "").update(unsigned).digest("base64url")}`
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const ANON_KEY = (): string => token({ role: "anon" })
|
|
35
|
+
const EDITOR_SESSION = (): string => token({ sub: EDITOR, role: "authenticated", app_metadata: { role: "editor" } })
|
|
36
|
+
|
|
37
|
+
/** Forward `/rest/v1/<rest>` to PostgREST's `/<rest>`, as the gateway mounts it. */
|
|
38
|
+
function forward(upstream: URL) {
|
|
39
|
+
return (req: IncomingMessage, res: ServerResponse): void => {
|
|
40
|
+
const path = (req.url ?? "/").replace(/^\/rest\/v1/, "")
|
|
41
|
+
const out = request(new URL(path, upstream), { method: req.method, headers: { ...req.headers, host: upstream.host } }, (answer) => {
|
|
42
|
+
res.writeHead(answer.statusCode ?? 502, answer.headers)
|
|
43
|
+
answer.pipe(res)
|
|
44
|
+
})
|
|
45
|
+
out.on("error", () => res.writeHead(502).end())
|
|
46
|
+
req.pipe(out)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
describe.skipIf(restUrl === undefined || jwtSecret === undefined)("an API editor's insert on a drafts model", () => {
|
|
51
|
+
let proxy: Server
|
|
52
|
+
let base = ""
|
|
53
|
+
|
|
54
|
+
beforeAll(async () => {
|
|
55
|
+
proxy = createServer(forward(new URL(restUrl ?? "")))
|
|
56
|
+
await new Promise<void>((resolve) => proxy.listen(0, "127.0.0.1", resolve))
|
|
57
|
+
const address: AddressInfo | string | null = proxy.address()
|
|
58
|
+
base = typeof address === "object" && address !== null ? `http://127.0.0.1:${address.port}` : ""
|
|
59
|
+
registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
afterAll(async () => {
|
|
63
|
+
forgetRegisteredDraftModels()
|
|
64
|
+
await new Promise<void>((resolve) => proxy.close(() => resolve()))
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
const editor = () =>
|
|
68
|
+
createClient<AnyDatabase>({ url: base, anonKey: ANON_KEY(), headers: { Authorization: `Bearer ${EDITOR_SESSION()}` } })
|
|
69
|
+
const reader = () => createClient<AnyDatabase>({ url: base, anonKey: ANON_KEY() })
|
|
70
|
+
|
|
71
|
+
it("creates the record and returns the row an insert returns", async () => {
|
|
72
|
+
const title = `Written by the client ${Date.now()}`
|
|
73
|
+
const { data, error } = await editor()
|
|
74
|
+
.from("posts")
|
|
75
|
+
.insert({ title, body: { en: "Hello" } })
|
|
76
|
+
.select()
|
|
77
|
+
.single()
|
|
78
|
+
|
|
79
|
+
expect(error).toBeNull()
|
|
80
|
+
expect(data).toMatchObject({ title, body: { en: "Hello" }, published_at: null })
|
|
81
|
+
expect(typeof data?.["id"]).toBe("string")
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
it("leaves the record an unpublished draft: its author reads it, the public does not", async () => {
|
|
85
|
+
const title = `Still a draft ${Date.now()}`
|
|
86
|
+
const { data } = await editor().from("posts").insert({ title }).select("id").single()
|
|
87
|
+
const id = String(data?.["id"])
|
|
88
|
+
|
|
89
|
+
const drafted = await editor().from("posts").draft().select("title").eq("id", id)
|
|
90
|
+
const publicly = await reader().from("posts").select("id").eq("id", id)
|
|
91
|
+
expect(drafted.data).toEqual([{ title }])
|
|
92
|
+
expect(publicly).toMatchObject({ data: [], error: null })
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
it("creates several records in one insert and returns them in the order sent", async () => {
|
|
96
|
+
const stamp = Date.now()
|
|
97
|
+
const titles = [`Batch first ${stamp}`, `Batch second ${stamp}`]
|
|
98
|
+
const { data, error } = await editor()
|
|
99
|
+
.from("posts")
|
|
100
|
+
.insert(titles.map((title) => ({ title, body: { en: title } })))
|
|
101
|
+
.select("title, body")
|
|
102
|
+
|
|
103
|
+
expect(error).toBeNull()
|
|
104
|
+
expect(data).toEqual(titles.map((title) => ({ title, body: { en: title } })))
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
it("creates none of them when one is refused", async () => {
|
|
108
|
+
const first = `Refused batch ${Date.now()}`
|
|
109
|
+
const { data, error } = await editor()
|
|
110
|
+
.from("posts")
|
|
111
|
+
.insert([{ title: first }, { title: null }])
|
|
112
|
+
|
|
113
|
+
expect(data).toBeNull()
|
|
114
|
+
expect(error).toMatchObject({ code: "23502" })
|
|
115
|
+
const drafted = await editor().from("posts").draft().select("title").eq("title", first)
|
|
116
|
+
expect(drafted).toMatchObject({ data: [], error: null })
|
|
117
|
+
})
|
|
118
|
+
})
|