@supatype/client 0.1.4 → 0.1.6
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 +20 -18
- package/.turbo/turbo-typecheck.log +1 -1
- package/dist/auth.d.ts +62 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +267 -17
- package/dist/auth.js.map +1 -1
- package/dist/index.d.ts +20 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +34 -6
- package/dist/index.js.map +1 -1
- package/dist/pkce.d.ts +11 -0
- package/dist/pkce.d.ts.map +1 -0
- package/dist/pkce.js +28 -0
- package/dist/pkce.js.map +1 -0
- package/dist/query.d.ts +11 -2
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +59 -5
- package/dist/query.js.map +1 -1
- package/dist/types.d.ts +24 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/auth.ts +305 -26
- package/src/index.ts +61 -4
- package/src/pkce.ts +32 -0
- package/src/query.ts +70 -5
- package/src/types.ts +27 -0
- package/tests/auth.test.ts +207 -0
- package/tests/pkce.test.ts +30 -0
- package/tests/query.test.ts +55 -1
- package/tsconfig.tsbuildinfo +1 -1
package/src/query.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { QueryCache, QueryCacheOptions, CacheStatus } from "./query-cache.js"
|
|
2
2
|
import { buildCacheKey, defaultQueryCache } from "./query-cache.js"
|
|
3
|
-
import type { QueryResult, SupatypeError } from "./types.js"
|
|
3
|
+
import type { QueryResult, SelectQueryOptions, SupatypeError } from "./types.js"
|
|
4
4
|
|
|
5
5
|
const DEBUG_AUTH =
|
|
6
6
|
(typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1") ||
|
|
@@ -72,6 +72,8 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
72
72
|
private readonly params: URLSearchParams
|
|
73
73
|
private readonly queryCache: QueryCache
|
|
74
74
|
private cacheOptions: QueryCacheOptions | undefined
|
|
75
|
+
private readonly countMode: SelectQueryOptions["count"]
|
|
76
|
+
private readonly head: boolean
|
|
75
77
|
|
|
76
78
|
constructor(
|
|
77
79
|
baseUrl: string,
|
|
@@ -80,6 +82,7 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
80
82
|
columns?: string | undefined,
|
|
81
83
|
queryCache: QueryCache = defaultQueryCache,
|
|
82
84
|
onUnauthorized?: (() => Promise<void>) | undefined,
|
|
85
|
+
selectOptions?: SelectQueryOptions | undefined,
|
|
83
86
|
) {
|
|
84
87
|
this.baseUrl = baseUrl
|
|
85
88
|
this.path = path
|
|
@@ -88,9 +91,14 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
88
91
|
this.extraHeaders = {}
|
|
89
92
|
this.params = new URLSearchParams()
|
|
90
93
|
this.queryCache = queryCache
|
|
94
|
+
this.countMode = selectOptions?.count
|
|
95
|
+
this.head = selectOptions?.head === true
|
|
91
96
|
if (columns !== undefined) {
|
|
92
97
|
this.params.set("select", columns)
|
|
93
98
|
}
|
|
99
|
+
if (this.countMode !== undefined) {
|
|
100
|
+
this.extraHeaders["Prefer"] = `count=${this.countMode}`
|
|
101
|
+
}
|
|
94
102
|
}
|
|
95
103
|
|
|
96
104
|
/** Enable GET caching. Use `{ server: true }` for Valkey-backed server cache. */
|
|
@@ -169,6 +177,12 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
169
177
|
return this
|
|
170
178
|
}
|
|
171
179
|
|
|
180
|
+
/** PostgREST OR filter — pass conditions in PostgREST syntax, e.g. `"status.eq.active,owner_id.eq.123"`. */
|
|
181
|
+
or(filters: string): this {
|
|
182
|
+
this.params.append("or", `(${filters})`)
|
|
183
|
+
return this
|
|
184
|
+
}
|
|
185
|
+
|
|
172
186
|
order(
|
|
173
187
|
column: string,
|
|
174
188
|
opts?: { ascending?: boolean | undefined; nullsFirst?: boolean | undefined } | undefined,
|
|
@@ -239,15 +253,28 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
239
253
|
}
|
|
240
254
|
}
|
|
241
255
|
|
|
256
|
+
private mergePreferHeader(
|
|
257
|
+
headers: Record<string, string>,
|
|
258
|
+
extra: Record<string, string>,
|
|
259
|
+
): Record<string, string> {
|
|
260
|
+
const merged = { ...headers, ...extra }
|
|
261
|
+
const preferParts = [headers["Prefer"], extra["Prefer"]].filter(Boolean)
|
|
262
|
+
if (preferParts.length > 0) {
|
|
263
|
+
merged["Prefer"] = preferParts.join(",")
|
|
264
|
+
}
|
|
265
|
+
return merged
|
|
266
|
+
}
|
|
267
|
+
|
|
242
268
|
private async _fetch(fetchHeaders: Record<string, string>): Promise<QueryResult<TRow[]>> {
|
|
243
|
-
const mergedExtra =
|
|
269
|
+
const mergedExtra = this.mergePreferHeader(this.extraHeaders, fetchHeaders)
|
|
244
270
|
const url = this.buildRequestUrl()
|
|
271
|
+
const method = this.head ? "HEAD" : "GET"
|
|
245
272
|
const resolveRequestHeaders = async (): Promise<Record<string, string>> => {
|
|
246
273
|
const authHeaders = await this.getHeaders()
|
|
247
274
|
return this.applyServerCacheHeader({ ...authHeaders, ...mergedExtra })
|
|
248
275
|
}
|
|
249
276
|
|
|
250
|
-
if (this.cacheOptions) {
|
|
277
|
+
if (this.cacheOptions && !this.head) {
|
|
251
278
|
const requestHeaders = await resolveRequestHeaders()
|
|
252
279
|
const cacheKey = buildCacheKey("GET", url, requestHeaders, {
|
|
253
280
|
partition: this.cacheOptions.key,
|
|
@@ -263,7 +290,7 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
263
290
|
try {
|
|
264
291
|
res = await fetchWithOptional401Retry(
|
|
265
292
|
url,
|
|
266
|
-
{},
|
|
293
|
+
{ method },
|
|
267
294
|
resolveRequestHeaders,
|
|
268
295
|
this.onUnauthorized,
|
|
269
296
|
)
|
|
@@ -315,6 +342,13 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
315
342
|
)
|
|
316
343
|
}
|
|
317
344
|
|
|
345
|
+
if (method === "HEAD" || res.status === 204) {
|
|
346
|
+
return withCacheMeta<TRow[]>(
|
|
347
|
+
{ data: null, error: null, count },
|
|
348
|
+
cacheStatus,
|
|
349
|
+
)
|
|
350
|
+
}
|
|
351
|
+
|
|
318
352
|
const json = await res.json() as TRow[]
|
|
319
353
|
const result: QueryResult<TRow[]> = { data: json, error: null, count }
|
|
320
354
|
|
|
@@ -387,6 +421,36 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
387
421
|
return this
|
|
388
422
|
}
|
|
389
423
|
|
|
424
|
+
/** Limit returned columns on the mutation response (requires `return=representation`). */
|
|
425
|
+
select(columns?: string): this {
|
|
426
|
+
this.params.set("select", columns ?? "*")
|
|
427
|
+
return this
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async single(): Promise<QueryResult<TRow>> {
|
|
431
|
+
const { data, error, count, meta } = await this._execute({
|
|
432
|
+
Accept: "application/vnd.pgrst.object+json",
|
|
433
|
+
})
|
|
434
|
+
if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
|
|
435
|
+
const row = data !== null && data.length > 0 ? (data[0] as TRow) : null
|
|
436
|
+
if (row === null) {
|
|
437
|
+
return {
|
|
438
|
+
data: null,
|
|
439
|
+
error: { message: "JSON object requested, multiple (or no) rows returned" },
|
|
440
|
+
count: null,
|
|
441
|
+
...(meta && { meta }),
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
return { data: row, error: null, count: 1, ...(meta && { meta }) }
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
async maybeSingle(): Promise<QueryResult<TRow | null>> {
|
|
448
|
+
const { data, error, count, meta } = await this._execute({})
|
|
449
|
+
if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
|
|
450
|
+
const row = data !== null && data.length > 0 ? (data[0] ?? null) : null
|
|
451
|
+
return { data: row, error: null, count, ...(meta && { meta }) }
|
|
452
|
+
}
|
|
453
|
+
|
|
390
454
|
then<R1 = QueryResult<TRow[]>, R2 = never>(
|
|
391
455
|
onfulfilled?: ((value: QueryResult<TRow[]>) => R1 | PromiseLike<R1>) | null | undefined,
|
|
392
456
|
onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
|
|
@@ -394,12 +458,13 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
394
458
|
return this._execute().then(onfulfilled, onrejected)
|
|
395
459
|
}
|
|
396
460
|
|
|
397
|
-
private async _execute(): Promise<QueryResult<TRow[]>> {
|
|
461
|
+
private async _execute(fetchHeaders: Record<string, string> = {}): Promise<QueryResult<TRow[]>> {
|
|
398
462
|
const qs = this.params.toString()
|
|
399
463
|
const url = `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
|
|
400
464
|
const resolveRequestHeaders = async (): Promise<Record<string, string>> => ({
|
|
401
465
|
...(await this.getHeaders()),
|
|
402
466
|
...this.extraHeaders,
|
|
467
|
+
...fetchHeaders,
|
|
403
468
|
})
|
|
404
469
|
const init: RequestInit = {
|
|
405
470
|
method: this.method,
|
package/src/types.ts
CHANGED
|
@@ -52,6 +52,16 @@ export type AuthChangeEvent =
|
|
|
52
52
|
| "PASSWORD_RECOVERY"
|
|
53
53
|
| "MFA_CHALLENGE_VERIFIED"
|
|
54
54
|
|
|
55
|
+
/**
|
|
56
|
+
* OAuth / magic-link redirect flow.
|
|
57
|
+
* - `pkce` — authorize with code_challenge; app exchanges `?code=` via `exchangeCodeForSession`.
|
|
58
|
+
* - `implicit` — tokens returned in the URL hash (`#access_token=…`).
|
|
59
|
+
*
|
|
60
|
+
* Web `signInWithOAuth` defaults to `implicit` for backward compatibility.
|
|
61
|
+
* React Native helpers should pass `pkce` (recommended default for mobile).
|
|
62
|
+
*/
|
|
63
|
+
export type AuthFlowType = "pkce" | "implicit"
|
|
64
|
+
|
|
55
65
|
// ─── MFA types ──────────────────────────────────────────────────────────────
|
|
56
66
|
|
|
57
67
|
export interface AuthMFAEnrollResponse {
|
|
@@ -225,6 +235,18 @@ export interface AnyDatabase {
|
|
|
225
235
|
|
|
226
236
|
// ─── Client config ────────────────────────────────────────────────────────────
|
|
227
237
|
|
|
238
|
+
/** Sync or async key-value store for auth session persistence (e.g. AsyncStorage in React Native). */
|
|
239
|
+
export interface AuthStorage {
|
|
240
|
+
getItem(key: string): string | null | Promise<string | null>
|
|
241
|
+
setItem(key: string, value: string): void | Promise<void>
|
|
242
|
+
removeItem(key: string): void | Promise<void>
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export interface SelectQueryOptions {
|
|
246
|
+
count?: "exact" | "planned" | "estimated" | undefined
|
|
247
|
+
head?: boolean | undefined
|
|
248
|
+
}
|
|
249
|
+
|
|
228
250
|
export interface SupatypeClientConfig {
|
|
229
251
|
/** Base URL of the Supatype gateway (e.g. http://localhost:18473) */
|
|
230
252
|
url: string
|
|
@@ -247,6 +269,11 @@ export interface SupatypeClientConfig {
|
|
|
247
269
|
* Default: `"st"`.
|
|
248
270
|
*/
|
|
249
271
|
cookiePrefix?: string | undefined
|
|
272
|
+
/**
|
|
273
|
+
* Custom session store. When set, replaces browser localStorage/cookie persistence.
|
|
274
|
+
* React Native: pass an AsyncStorage or expo-secure-store adapter.
|
|
275
|
+
*/
|
|
276
|
+
storage?: AuthStorage | undefined
|
|
250
277
|
} | undefined
|
|
251
278
|
/**
|
|
252
279
|
* Disable automatic retry for transient errors.
|
package/tests/auth.test.ts
CHANGED
|
@@ -373,6 +373,213 @@ describe("AuthClient.refreshSession()", () => {
|
|
|
373
373
|
})
|
|
374
374
|
})
|
|
375
375
|
|
|
376
|
+
describe("AuthClient custom storage", () => {
|
|
377
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
378
|
+
|
|
379
|
+
const VALID_SESSION = {
|
|
380
|
+
accessToken: "stored-access",
|
|
381
|
+
refreshToken: "stored-refresh",
|
|
382
|
+
tokenType: "bearer",
|
|
383
|
+
expiresIn: 3600,
|
|
384
|
+
expiresAt: Math.floor(Date.now() / 1000) + 3600,
|
|
385
|
+
user: {
|
|
386
|
+
id: "user-1",
|
|
387
|
+
email: "test@example.com",
|
|
388
|
+
appMetadata: { provider: "email" },
|
|
389
|
+
userMetadata: { name: "Test" },
|
|
390
|
+
createdAt: "2024-01-01T00:00:00Z",
|
|
391
|
+
updatedAt: "2024-01-01T00:00:00Z",
|
|
392
|
+
},
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
it("hydrates session from async storage and emits SIGNED_IN", async () => {
|
|
396
|
+
const storage = {
|
|
397
|
+
getItem: vi.fn().mockResolvedValue(JSON.stringify(VALID_SESSION)),
|
|
398
|
+
setItem: vi.fn().mockResolvedValue(undefined),
|
|
399
|
+
removeItem: vi.fn().mockResolvedValue(undefined),
|
|
400
|
+
}
|
|
401
|
+
const events: string[] = []
|
|
402
|
+
const client = new AuthClient(GOTRUE_URL, HEADERS, { storage })
|
|
403
|
+
client.onAuthStateChange((event) => events.push(event))
|
|
404
|
+
|
|
405
|
+
await client.whenReady()
|
|
406
|
+
const { data } = await client.getSession()
|
|
407
|
+
|
|
408
|
+
expect(data.session?.accessToken).toBe("stored-access")
|
|
409
|
+
expect(events).toContain("SIGNED_IN")
|
|
410
|
+
})
|
|
411
|
+
|
|
412
|
+
it("persists session to custom storage on sign in", async () => {
|
|
413
|
+
const storage = {
|
|
414
|
+
getItem: vi.fn().mockResolvedValue(null),
|
|
415
|
+
setItem: vi.fn().mockResolvedValue(undefined),
|
|
416
|
+
removeItem: vi.fn().mockResolvedValue(undefined),
|
|
417
|
+
}
|
|
418
|
+
const client = new AuthClient(GOTRUE_URL, HEADERS, { storage })
|
|
419
|
+
await client.whenReady()
|
|
420
|
+
|
|
421
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
422
|
+
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
423
|
+
|
|
424
|
+
expect(storage.setItem).toHaveBeenCalled()
|
|
425
|
+
const [key, value] = storage.setItem.mock.calls[0] as [string, string]
|
|
426
|
+
expect(key).toBe("supatype.auth.session")
|
|
427
|
+
expect(JSON.parse(value).accessToken).toBe("access-token-123")
|
|
428
|
+
})
|
|
429
|
+
|
|
430
|
+
it("survives corrupt async storage without throwing", async () => {
|
|
431
|
+
const storage = {
|
|
432
|
+
getItem: vi.fn().mockRejectedValue(new Error("storage unavailable")),
|
|
433
|
+
setItem: vi.fn(),
|
|
434
|
+
removeItem: vi.fn(),
|
|
435
|
+
}
|
|
436
|
+
const client = new AuthClient(GOTRUE_URL, HEADERS, { storage })
|
|
437
|
+
|
|
438
|
+
await expect(client.whenReady()).resolves.toBeUndefined()
|
|
439
|
+
const { data } = await client.getSession()
|
|
440
|
+
expect(data.session).toBeNull()
|
|
441
|
+
})
|
|
442
|
+
|
|
443
|
+
it("does not read storage when persistSession is false", async () => {
|
|
444
|
+
const storage = {
|
|
445
|
+
getItem: vi.fn().mockResolvedValue(JSON.stringify(VALID_SESSION)),
|
|
446
|
+
setItem: vi.fn(),
|
|
447
|
+
removeItem: vi.fn(),
|
|
448
|
+
}
|
|
449
|
+
const client = new AuthClient(GOTRUE_URL, HEADERS, { storage, persistSession: false })
|
|
450
|
+
await client.whenReady()
|
|
451
|
+
|
|
452
|
+
expect(storage.getItem).not.toHaveBeenCalled()
|
|
453
|
+
const { data } = await client.getSession()
|
|
454
|
+
expect(data.session).toBeNull()
|
|
455
|
+
})
|
|
456
|
+
})
|
|
457
|
+
|
|
458
|
+
describe("AuthClient OAuth session completion", () => {
|
|
459
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
460
|
+
|
|
461
|
+
it("signInWithOAuth defaults to implicit (no PKCE params)", async () => {
|
|
462
|
+
const { data, error } = await freshClient().signInWithOAuth({ provider: "google" })
|
|
463
|
+
expect(error).toBeNull()
|
|
464
|
+
const url = new URL(data.url)
|
|
465
|
+
expect(url.searchParams.get("provider")).toBe("google")
|
|
466
|
+
expect(url.searchParams.get("code_challenge")).toBeNull()
|
|
467
|
+
expect(url.searchParams.get("code_challenge_method")).toBeNull()
|
|
468
|
+
})
|
|
469
|
+
|
|
470
|
+
it("signInWithOAuth pkce appends challenge and persists verifier", async () => {
|
|
471
|
+
const storage = {
|
|
472
|
+
getItem: vi.fn().mockResolvedValue(null),
|
|
473
|
+
setItem: vi.fn().mockResolvedValue(undefined),
|
|
474
|
+
removeItem: vi.fn().mockResolvedValue(undefined),
|
|
475
|
+
}
|
|
476
|
+
const client = new AuthClient(GOTRUE_URL, HEADERS, { storage })
|
|
477
|
+
await client.whenReady()
|
|
478
|
+
|
|
479
|
+
const { data, error } = await client.signInWithOAuth({
|
|
480
|
+
provider: "github",
|
|
481
|
+
options: { flowType: "pkce", redirectTo: "myapp://auth/callback" },
|
|
482
|
+
})
|
|
483
|
+
|
|
484
|
+
expect(error).toBeNull()
|
|
485
|
+
const url = new URL(data.url)
|
|
486
|
+
expect(url.searchParams.get("code_challenge_method")).toBe("s256")
|
|
487
|
+
expect(url.searchParams.get("code_challenge")).toMatch(/^[A-Za-z0-9\-._~]+$/)
|
|
488
|
+
expect(url.searchParams.get("redirect_to")).toBe("myapp://auth/callback")
|
|
489
|
+
expect(storage.setItem).toHaveBeenCalledWith(
|
|
490
|
+
"supatype.auth.session-code-verifier",
|
|
491
|
+
expect.stringMatching(/^[A-Za-z0-9\-._~]+$/),
|
|
492
|
+
)
|
|
493
|
+
})
|
|
494
|
+
|
|
495
|
+
it("exchangeCodeForSession posts auth_code + code_verifier", async () => {
|
|
496
|
+
const storage = {
|
|
497
|
+
getItem: vi.fn().mockResolvedValue(null),
|
|
498
|
+
setItem: vi.fn().mockResolvedValue(undefined),
|
|
499
|
+
removeItem: vi.fn().mockResolvedValue(undefined),
|
|
500
|
+
}
|
|
501
|
+
const client = new AuthClient(GOTRUE_URL, HEADERS, { storage })
|
|
502
|
+
await client.whenReady()
|
|
503
|
+
await client.signInWithOAuth({ provider: "google", options: { flowType: "pkce" } })
|
|
504
|
+
|
|
505
|
+
const fetch = mockFetch(TOKEN_RESPONSE)
|
|
506
|
+
vi.stubGlobal("fetch", fetch)
|
|
507
|
+
|
|
508
|
+
const { data, error } = await client.exchangeCodeForSession("auth-code-xyz")
|
|
509
|
+
|
|
510
|
+
expect(error).toBeNull()
|
|
511
|
+
expect(data.session?.accessToken).toBe("access-token-123")
|
|
512
|
+
expect(fetch).toHaveBeenCalledWith(
|
|
513
|
+
`${GOTRUE_URL}/token?grant_type=pkce`,
|
|
514
|
+
expect.objectContaining({ method: "POST" }),
|
|
515
|
+
)
|
|
516
|
+
const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
|
|
517
|
+
const body = JSON.parse(opts.body as string) as Record<string, unknown>
|
|
518
|
+
expect(body["auth_code"]).toBe("auth-code-xyz")
|
|
519
|
+
expect(typeof body["code_verifier"]).toBe("string")
|
|
520
|
+
expect(storage.removeItem).toHaveBeenCalledWith("supatype.auth.session-code-verifier")
|
|
521
|
+
})
|
|
522
|
+
|
|
523
|
+
it("getSessionFromUrl exchanges PKCE code from query", async () => {
|
|
524
|
+
const storage = {
|
|
525
|
+
getItem: vi.fn().mockResolvedValue(null),
|
|
526
|
+
setItem: vi.fn().mockResolvedValue(undefined),
|
|
527
|
+
removeItem: vi.fn().mockResolvedValue(undefined),
|
|
528
|
+
}
|
|
529
|
+
const client = new AuthClient(GOTRUE_URL, HEADERS, { storage })
|
|
530
|
+
await client.whenReady()
|
|
531
|
+
await client.signInWithOAuth({ provider: "google", options: { flowType: "pkce" } })
|
|
532
|
+
|
|
533
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
534
|
+
const { data, error } = await client.getSessionFromUrl(
|
|
535
|
+
"myapp://auth/callback?code=returned-auth-code",
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
expect(error).toBeNull()
|
|
539
|
+
expect(data.session?.accessToken).toBe("access-token-123")
|
|
540
|
+
})
|
|
541
|
+
|
|
542
|
+
it("getSessionFromUrl sets session from implicit hash tokens", async () => {
|
|
543
|
+
const client = freshClient()
|
|
544
|
+
// Minimal JWT-ish payload with exp so setSession can decode (header.payload.sig)
|
|
545
|
+
const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString(
|
|
546
|
+
"base64url",
|
|
547
|
+
)
|
|
548
|
+
const accessToken = `eyJhbGciOiJub25lIn0.${payload}.sig`
|
|
549
|
+
|
|
550
|
+
vi.stubGlobal(
|
|
551
|
+
"fetch",
|
|
552
|
+
mockFetch({
|
|
553
|
+
...RAW_USER,
|
|
554
|
+
id: "user-1",
|
|
555
|
+
}),
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
const { data, error } = await client.getSessionFromUrl(
|
|
559
|
+
`https://app.example/#access_token=${accessToken}&refresh_token=rt-1&token_type=bearer&expires_in=3600`,
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
expect(error).toBeNull()
|
|
563
|
+
expect(data.session?.accessToken).toBe(accessToken)
|
|
564
|
+
expect(data.session?.refreshToken).toBe("rt-1")
|
|
565
|
+
expect(data.user?.id).toBe("user-1")
|
|
566
|
+
})
|
|
567
|
+
|
|
568
|
+
it("getSessionFromUrl returns error from redirect query", async () => {
|
|
569
|
+
const { data, error } = await freshClient().getSessionFromUrl(
|
|
570
|
+
"myapp://auth/callback?error=access_denied&error_description=User+denied",
|
|
571
|
+
)
|
|
572
|
+
expect(data.session).toBeNull()
|
|
573
|
+
expect(error?.message).toBe("User denied")
|
|
574
|
+
})
|
|
575
|
+
|
|
576
|
+
it("exchangeCodeForSession errors when verifier is missing", async () => {
|
|
577
|
+
const { data, error } = await freshClient().exchangeCodeForSession("code")
|
|
578
|
+
expect(data.session).toBeNull()
|
|
579
|
+
expect(error?.message).toMatch(/code_verifier/)
|
|
580
|
+
})
|
|
581
|
+
})
|
|
582
|
+
|
|
376
583
|
describe("AuthClient stale persisted session", () => {
|
|
377
584
|
let store: Map<string, string>
|
|
378
585
|
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest"
|
|
2
|
+
import {
|
|
3
|
+
bytesToBase64Url,
|
|
4
|
+
createCodeChallengeS256,
|
|
5
|
+
generateCodeVerifier,
|
|
6
|
+
PKCE_METHOD_S256,
|
|
7
|
+
} from "../src/pkce.js"
|
|
8
|
+
|
|
9
|
+
describe("pkce helpers", () => {
|
|
10
|
+
it("exports s256 method constant", () => {
|
|
11
|
+
expect(PKCE_METHOD_S256).toBe("s256")
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it("generates a 43-char unreserved code_verifier", () => {
|
|
15
|
+
const verifier = generateCodeVerifier()
|
|
16
|
+
expect(verifier.length).toBe(43)
|
|
17
|
+
expect(verifier).toMatch(/^[A-Za-z0-9\-._~]+$/)
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
it("creates a stable S256 challenge", () => {
|
|
21
|
+
// Known vector: SHA256("test") base64url
|
|
22
|
+
const challenge = createCodeChallengeS256("test")
|
|
23
|
+
expect(challenge).toBe("n4bQgYhMfWWaL-qgxVrQFaO_TxsrC4Is0V1sFbDwCgg")
|
|
24
|
+
expect(challenge).toMatch(/^[A-Za-z0-9\-._~]+$/)
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it("bytesToBase64Url strips padding", () => {
|
|
28
|
+
expect(bytesToBase64Url(new Uint8Array([0xff, 0xee, 0xdd]))).toBe("_-7d")
|
|
29
|
+
})
|
|
30
|
+
})
|
package/tests/query.test.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
|
-
import { QueryBuilder, MutationBuilder } from "../src/query.js"
|
|
2
|
+
import { QueryBuilder, MutationBuilder, defaultQueryCache } from "../src/query.js"
|
|
3
3
|
|
|
4
4
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
5
5
|
|
|
@@ -152,6 +152,41 @@ describe("QueryBuilder — URL construction", () => {
|
|
|
152
152
|
expect(u).toContain("order=created_at.desc.nullslast")
|
|
153
153
|
expect(u).toContain("limit=10")
|
|
154
154
|
})
|
|
155
|
+
|
|
156
|
+
it(".or() appends PostgREST or filter", async () => {
|
|
157
|
+
const { url } = captureUrl()
|
|
158
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS).or("status.eq.active,owner_id.eq.123")
|
|
159
|
+
expect(decodeURIComponent(url())).toContain("or=(status.eq.active,owner_id.eq.123)")
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
it("select with count sends Prefer: count=exact header", async () => {
|
|
163
|
+
const fetch = mockFetch([], { contentRange: "0-0/99" })
|
|
164
|
+
vi.stubGlobal("fetch", fetch)
|
|
165
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS, "*", defaultQueryCache, undefined, {
|
|
166
|
+
count: "exact",
|
|
167
|
+
})
|
|
168
|
+
const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
|
|
169
|
+
expect((opts.headers as Record<string, string>)["Prefer"]).toBe("count=exact")
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
it("select with head issues HEAD request and returns count only", async () => {
|
|
173
|
+
const fetch = mockFetch(null, { contentRange: "0-0/42" })
|
|
174
|
+
vi.stubGlobal("fetch", fetch)
|
|
175
|
+
const { data, error, count } = await new QueryBuilder<Post>(
|
|
176
|
+
BASE,
|
|
177
|
+
PATH,
|
|
178
|
+
HEADERS,
|
|
179
|
+
"*",
|
|
180
|
+
defaultQueryCache,
|
|
181
|
+
undefined,
|
|
182
|
+
{ count: "exact", head: true },
|
|
183
|
+
)
|
|
184
|
+
const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
|
|
185
|
+
expect(opts.method).toBe("HEAD")
|
|
186
|
+
expect(data).toBeNull()
|
|
187
|
+
expect(error).toBeNull()
|
|
188
|
+
expect(count).toBe(42)
|
|
189
|
+
})
|
|
155
190
|
})
|
|
156
191
|
|
|
157
192
|
describe("QueryBuilder — results", () => {
|
|
@@ -283,4 +318,23 @@ describe("MutationBuilder — update / delete", () => {
|
|
|
283
318
|
const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
|
|
284
319
|
expect((opts.headers as Record<string, string>)["Prefer"]).toContain("merge-duplicates")
|
|
285
320
|
})
|
|
321
|
+
|
|
322
|
+
it("update().eq().select().maybeSingle() returns first row", async () => {
|
|
323
|
+
const fetch = mockFetch([{ id: "1", title: "Updated", status: "published" }])
|
|
324
|
+
vi.stubGlobal("fetch", fetch)
|
|
325
|
+
const { data, error } = await new MutationBuilder<Post>(
|
|
326
|
+
BASE,
|
|
327
|
+
PATH,
|
|
328
|
+
HEADERS,
|
|
329
|
+
"PATCH",
|
|
330
|
+
{ title: "Updated" },
|
|
331
|
+
)
|
|
332
|
+
.eq("id", "1")
|
|
333
|
+
.select()
|
|
334
|
+
.maybeSingle()
|
|
335
|
+
expect(error).toBeNull()
|
|
336
|
+
expect(data).toEqual({ id: "1", title: "Updated", status: "published" })
|
|
337
|
+
const [url] = fetch.mock.calls[0] as [string, RequestInit]
|
|
338
|
+
expect(url).toContain("select=*")
|
|
339
|
+
})
|
|
286
340
|
})
|