@supatype/client 0.1.1 → 0.1.3
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 +19 -16
- package/.turbo/turbo-typecheck.log +1 -1
- package/dist/auth.d.ts +2 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +1 -0
- package/dist/auth.js.map +1 -1
- package/dist/index.d.ts +12 -15
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +61 -32
- package/dist/index.js.map +1 -1
- package/dist/query-cache.d.ts +29 -0
- package/dist/query-cache.d.ts.map +1 -0
- package/dist/query-cache.js +78 -0
- package/dist/query-cache.js.map +1 -0
- package/dist/query.d.ts +20 -5
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +123 -34
- package/dist/query.js.map +1 -1
- package/dist/sha256-hex.d.ts +3 -0
- package/dist/sha256-hex.d.ts.map +1 -0
- package/dist/sha256-hex.js +7 -0
- package/dist/sha256-hex.js.map +1 -0
- package/dist/types.d.ts +7 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +4 -1
- package/src/auth.ts +2 -1
- package/src/index.ts +97 -36
- package/src/query-cache.ts +111 -0
- package/src/query.ts +170 -40
- package/src/sha256-hex.ts +7 -0
- package/src/types.ts +7 -0
- package/tests/data-plane-auth.test.ts +159 -0
- package/tests/query-cache.test.ts +112 -0
- package/tests/sha256-hex.test.ts +10 -0
- package/tsconfig.json +1 -2
- package/tsconfig.tsbuildinfo +1 -1
package/src/query.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { QueryCache, QueryCacheOptions, CacheStatus } from "./query-cache.js"
|
|
2
|
+
import { buildCacheKey, defaultQueryCache } from "./query-cache.js"
|
|
1
3
|
import type { QueryResult, SupatypeError } from "./types.js"
|
|
2
4
|
|
|
3
5
|
const DEBUG_AUTH =
|
|
@@ -22,29 +24,81 @@ function decodeJwtRoleFromAuthHeader(headers: Record<string, string>): string |
|
|
|
22
24
|
}
|
|
23
25
|
}
|
|
24
26
|
|
|
27
|
+
function withCacheMeta<T>(
|
|
28
|
+
result: QueryResult<T>,
|
|
29
|
+
cacheStatus?: CacheStatus,
|
|
30
|
+
): QueryResult<T> {
|
|
31
|
+
if (cacheStatus === undefined) return result
|
|
32
|
+
return {
|
|
33
|
+
...result,
|
|
34
|
+
meta: { ...(result.meta ?? {}), cacheStatus },
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Resolves auth (and other) headers at request time so token refresh can run first. */
|
|
39
|
+
export type HeadersProvider = () => Promise<Record<string, string>>
|
|
40
|
+
|
|
41
|
+
function asHeadersProvider(
|
|
42
|
+
headers: Record<string, string> | HeadersProvider,
|
|
43
|
+
): HeadersProvider {
|
|
44
|
+
if (typeof headers === "function") return headers
|
|
45
|
+
return () => Promise.resolve(headers)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function fetchWithOptional401Retry(
|
|
49
|
+
url: string,
|
|
50
|
+
init: RequestInit,
|
|
51
|
+
resolveHeaders: () => Promise<Record<string, string>>,
|
|
52
|
+
onUnauthorized?: (() => Promise<void>) | undefined,
|
|
53
|
+
): Promise<Response> {
|
|
54
|
+
let headers = await resolveHeaders()
|
|
55
|
+
let res = await fetch(url, { ...init, headers })
|
|
56
|
+
if (res.status === 401 && onUnauthorized !== undefined) {
|
|
57
|
+
await onUnauthorized()
|
|
58
|
+
headers = await resolveHeaders()
|
|
59
|
+
res = await fetch(url, { ...init, headers })
|
|
60
|
+
}
|
|
61
|
+
return res
|
|
62
|
+
}
|
|
63
|
+
|
|
25
64
|
// ─── QueryBuilder ─────────────────────────────────────────────────────────────
|
|
26
65
|
|
|
27
66
|
export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
28
67
|
private readonly baseUrl: string
|
|
29
68
|
private readonly path: string
|
|
30
|
-
private readonly
|
|
69
|
+
private readonly getHeaders: HeadersProvider
|
|
70
|
+
private readonly onUnauthorized: (() => Promise<void>) | undefined
|
|
71
|
+
private readonly extraHeaders: Record<string, string>
|
|
31
72
|
private readonly params: URLSearchParams
|
|
73
|
+
private readonly queryCache: QueryCache
|
|
74
|
+
private cacheOptions: QueryCacheOptions | undefined
|
|
32
75
|
|
|
33
76
|
constructor(
|
|
34
77
|
baseUrl: string,
|
|
35
78
|
path: string,
|
|
36
|
-
headers: Record<string, string
|
|
79
|
+
headers: Record<string, string> | HeadersProvider,
|
|
37
80
|
columns?: string | undefined,
|
|
81
|
+
queryCache: QueryCache = defaultQueryCache,
|
|
82
|
+
onUnauthorized?: (() => Promise<void>) | undefined,
|
|
38
83
|
) {
|
|
39
84
|
this.baseUrl = baseUrl
|
|
40
85
|
this.path = path
|
|
41
|
-
this.
|
|
86
|
+
this.getHeaders = asHeadersProvider(headers)
|
|
87
|
+
this.onUnauthorized = onUnauthorized
|
|
88
|
+
this.extraHeaders = {}
|
|
42
89
|
this.params = new URLSearchParams()
|
|
90
|
+
this.queryCache = queryCache
|
|
43
91
|
if (columns !== undefined) {
|
|
44
92
|
this.params.set("select", columns)
|
|
45
93
|
}
|
|
46
94
|
}
|
|
47
95
|
|
|
96
|
+
/** Enable GET caching. Use `{ server: true }` for Valkey-backed server cache. */
|
|
97
|
+
cache(options: QueryCacheOptions): this {
|
|
98
|
+
this.cacheOptions = options
|
|
99
|
+
return this
|
|
100
|
+
}
|
|
101
|
+
|
|
48
102
|
select(columns: string): this {
|
|
49
103
|
this.params.set("select", columns)
|
|
50
104
|
return this
|
|
@@ -132,49 +186,87 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
132
186
|
|
|
133
187
|
/** Set the locale for resolving localized fields. */
|
|
134
188
|
locale(code: string): this {
|
|
135
|
-
this.
|
|
189
|
+
this.extraHeaders["Accept-Language"] = code
|
|
136
190
|
return this
|
|
137
191
|
}
|
|
138
192
|
|
|
139
193
|
range(from: number, to: number): this {
|
|
140
|
-
this.
|
|
141
|
-
this.
|
|
194
|
+
this.extraHeaders["Range"] = `${from}-${to}`
|
|
195
|
+
this.extraHeaders["Range-Unit"] = "items"
|
|
142
196
|
return this
|
|
143
197
|
}
|
|
144
198
|
|
|
145
199
|
/** Return a single row (errors if none or many found). */
|
|
146
200
|
async single(): Promise<QueryResult<TRow>> {
|
|
147
|
-
const
|
|
148
|
-
...this.headers,
|
|
201
|
+
const { data, error, meta } = await this._fetch({
|
|
149
202
|
Accept: "application/vnd.pgrst.object+json",
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
return { data: data as unknown as TRow, error: null, count: 1 }
|
|
203
|
+
})
|
|
204
|
+
if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
|
|
205
|
+
return { data: data as unknown as TRow, error: null, count: 1, ...(meta && { meta }) }
|
|
154
206
|
}
|
|
155
207
|
|
|
156
208
|
/** Return a single row or null (errors if many found). */
|
|
157
209
|
async maybeSingle(): Promise<QueryResult<TRow | null>> {
|
|
158
|
-
const { data, error, count } = await this._fetch(
|
|
159
|
-
if (error !== null) return { data: null, error, count: null }
|
|
210
|
+
const { data, error, count, meta } = await this._fetch({})
|
|
211
|
+
if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
|
|
160
212
|
const rows = data as TRow[]
|
|
161
213
|
const row = rows.length > 0 ? (rows[0] ?? null) : null
|
|
162
|
-
return { data: row, error: null, count }
|
|
214
|
+
return { data: row, error: null, count, ...(meta && { meta }) }
|
|
163
215
|
}
|
|
164
216
|
|
|
165
217
|
then<R1 = QueryResult<TRow[]>, R2 = never>(
|
|
166
218
|
onfulfilled?: ((value: QueryResult<TRow[]>) => R1 | PromiseLike<R1>) | null | undefined,
|
|
167
219
|
onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
|
|
168
220
|
): PromiseLike<R1 | R2> {
|
|
169
|
-
return this._fetch(
|
|
221
|
+
return this._fetch({}).then(onfulfilled, onrejected)
|
|
170
222
|
}
|
|
171
223
|
|
|
172
|
-
private
|
|
224
|
+
private buildRequestUrl(): string {
|
|
173
225
|
const qs = this.params.toString()
|
|
174
|
-
|
|
226
|
+
return `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
private applyServerCacheHeader(headers: Record<string, string>): Record<string, string> {
|
|
230
|
+
if (!this.cacheOptions?.server) return headers
|
|
231
|
+
const seconds = Math.max(1, Math.floor(this.cacheOptions.ttl / 1000))
|
|
232
|
+
const cacheDirective =
|
|
233
|
+
this.cacheOptions.public === true
|
|
234
|
+
? `max-age=${seconds}, public`
|
|
235
|
+
: `max-age=${seconds}`
|
|
236
|
+
return {
|
|
237
|
+
...headers,
|
|
238
|
+
"X-Supatype-Cache": cacheDirective,
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private async _fetch(fetchHeaders: Record<string, string>): Promise<QueryResult<TRow[]>> {
|
|
243
|
+
const mergedExtra = { ...this.extraHeaders, ...fetchHeaders }
|
|
244
|
+
const url = this.buildRequestUrl()
|
|
245
|
+
const resolveRequestHeaders = async (): Promise<Record<string, string>> => {
|
|
246
|
+
const authHeaders = await this.getHeaders()
|
|
247
|
+
return this.applyServerCacheHeader({ ...authHeaders, ...mergedExtra })
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (this.cacheOptions) {
|
|
251
|
+
const requestHeaders = await resolveRequestHeaders()
|
|
252
|
+
const cacheKey = buildCacheKey("GET", url, requestHeaders, {
|
|
253
|
+
partition: this.cacheOptions.key,
|
|
254
|
+
public: this.cacheOptions.public,
|
|
255
|
+
})
|
|
256
|
+
const cached = this.queryCache.get<TRow[]>(cacheKey)
|
|
257
|
+
if (cached) {
|
|
258
|
+
return withCacheMeta(cached, "HIT")
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
175
262
|
let res: Response
|
|
176
263
|
try {
|
|
177
|
-
res = await
|
|
264
|
+
res = await fetchWithOptional401Retry(
|
|
265
|
+
url,
|
|
266
|
+
{},
|
|
267
|
+
resolveRequestHeaders,
|
|
268
|
+
this.onUnauthorized,
|
|
269
|
+
)
|
|
178
270
|
} catch (e) {
|
|
179
271
|
return {
|
|
180
272
|
data: null,
|
|
@@ -189,30 +281,52 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
189
281
|
? parseInt(contentRange.split("/")[1] ?? "0", 10)
|
|
190
282
|
: null
|
|
191
283
|
|
|
284
|
+
const serverCacheStatus = res.headers.get("X-Supatype-Cache-Status") as CacheStatus | null
|
|
285
|
+
const cacheStatus: CacheStatus =
|
|
286
|
+
serverCacheStatus === "HIT" || serverCacheStatus === "MISS" || serverCacheStatus === "BYPASS"
|
|
287
|
+
? serverCacheStatus
|
|
288
|
+
: this.cacheOptions
|
|
289
|
+
? "MISS"
|
|
290
|
+
: undefined
|
|
291
|
+
|
|
192
292
|
if (!res.ok) {
|
|
193
293
|
const err = await res.json().catch(() => ({ message: "Error" })) as Record<string, unknown>
|
|
294
|
+
const debugHeaders = await resolveRequestHeaders()
|
|
194
295
|
if (DEBUG_AUTH) {
|
|
195
296
|
console.log("[supatype:query] request failed", {
|
|
196
297
|
url,
|
|
197
298
|
status: res.status,
|
|
198
|
-
role: decodeJwtRoleFromAuthHeader(
|
|
299
|
+
role: decodeJwtRoleFromAuthHeader(debugHeaders),
|
|
199
300
|
message: String(err["message"] ?? err["hint"] ?? "Request failed"),
|
|
200
301
|
code: typeof err["code"] === "string" ? err["code"] : null,
|
|
201
302
|
})
|
|
202
303
|
}
|
|
203
|
-
return
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
304
|
+
return withCacheMeta<TRow[]>(
|
|
305
|
+
{
|
|
306
|
+
data: null,
|
|
307
|
+
error: {
|
|
308
|
+
message: String(err["message"] ?? err["hint"] ?? "Request failed"),
|
|
309
|
+
status: res.status,
|
|
310
|
+
...(err["code"] !== undefined && { code: String(err["code"]) }),
|
|
311
|
+
},
|
|
312
|
+
count: null,
|
|
209
313
|
},
|
|
210
|
-
|
|
211
|
-
|
|
314
|
+
cacheStatus,
|
|
315
|
+
)
|
|
212
316
|
}
|
|
213
317
|
|
|
214
318
|
const json = await res.json() as TRow[]
|
|
215
|
-
|
|
319
|
+
const result: QueryResult<TRow[]> = { data: json, error: null, count }
|
|
320
|
+
|
|
321
|
+
if (this.cacheOptions) {
|
|
322
|
+
const cacheKey = buildCacheKey("GET", url, await resolveRequestHeaders(), {
|
|
323
|
+
partition: this.cacheOptions.key,
|
|
324
|
+
public: this.cacheOptions.public,
|
|
325
|
+
})
|
|
326
|
+
this.queryCache.set(cacheKey, result, this.cacheOptions.ttl)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
return withCacheMeta(result, cacheStatus)
|
|
216
330
|
}
|
|
217
331
|
}
|
|
218
332
|
|
|
@@ -223,7 +337,9 @@ type HttpMethod = "POST" | "PATCH" | "DELETE"
|
|
|
223
337
|
export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
224
338
|
private readonly baseUrl: string
|
|
225
339
|
private readonly path: string
|
|
226
|
-
private readonly
|
|
340
|
+
private readonly getHeaders: HeadersProvider
|
|
341
|
+
private readonly onUnauthorized: (() => Promise<void>) | undefined
|
|
342
|
+
private readonly extraHeaders: Record<string, string>
|
|
227
343
|
private readonly method: HttpMethod
|
|
228
344
|
private readonly body: unknown
|
|
229
345
|
private readonly params: URLSearchParams
|
|
@@ -231,25 +347,28 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
231
347
|
constructor(
|
|
232
348
|
baseUrl: string,
|
|
233
349
|
path: string,
|
|
234
|
-
headers: Record<string, string
|
|
350
|
+
headers: Record<string, string> | HeadersProvider,
|
|
235
351
|
method: HttpMethod,
|
|
236
352
|
body?: unknown,
|
|
237
353
|
opts?: { upsert?: boolean | undefined } | undefined,
|
|
354
|
+
onUnauthorized?: (() => Promise<void>) | undefined,
|
|
238
355
|
) {
|
|
239
356
|
this.baseUrl = baseUrl
|
|
240
357
|
this.path = path
|
|
241
|
-
this.
|
|
358
|
+
this.getHeaders = asHeadersProvider(headers)
|
|
359
|
+
this.onUnauthorized = onUnauthorized
|
|
360
|
+
this.extraHeaders = {}
|
|
242
361
|
this.method = method
|
|
243
362
|
this.body = body
|
|
244
363
|
this.params = new URLSearchParams()
|
|
245
364
|
|
|
246
365
|
if (opts?.upsert === true) {
|
|
247
|
-
this.
|
|
366
|
+
this.extraHeaders["Prefer"] = "resolution=merge-duplicates"
|
|
248
367
|
}
|
|
249
368
|
|
|
250
369
|
// Return inserted/updated rows
|
|
251
370
|
if (method !== "DELETE") {
|
|
252
|
-
this.
|
|
371
|
+
this.extraHeaders["Prefer"] = (this.extraHeaders["Prefer"] ?? "") + ",return=representation"
|
|
253
372
|
}
|
|
254
373
|
}
|
|
255
374
|
|
|
@@ -278,13 +397,22 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
278
397
|
private async _execute(): Promise<QueryResult<TRow[]>> {
|
|
279
398
|
const qs = this.params.toString()
|
|
280
399
|
const url = `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
|
|
400
|
+
const resolveRequestHeaders = async (): Promise<Record<string, string>> => ({
|
|
401
|
+
...(await this.getHeaders()),
|
|
402
|
+
...this.extraHeaders,
|
|
403
|
+
})
|
|
404
|
+
const init: RequestInit = {
|
|
405
|
+
method: this.method,
|
|
406
|
+
...(this.body !== undefined && { body: JSON.stringify(this.body) }),
|
|
407
|
+
}
|
|
281
408
|
let res: Response
|
|
282
409
|
try {
|
|
283
|
-
res = await
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
410
|
+
res = await fetchWithOptional401Retry(
|
|
411
|
+
url,
|
|
412
|
+
init,
|
|
413
|
+
resolveRequestHeaders,
|
|
414
|
+
this.onUnauthorized,
|
|
415
|
+
)
|
|
288
416
|
} catch (e) {
|
|
289
417
|
return {
|
|
290
418
|
data: null,
|
|
@@ -300,7 +428,7 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
300
428
|
url,
|
|
301
429
|
method: this.method,
|
|
302
430
|
status: res.status,
|
|
303
|
-
role: decodeJwtRoleFromAuthHeader(
|
|
431
|
+
role: decodeJwtRoleFromAuthHeader(await resolveRequestHeaders()),
|
|
304
432
|
message: String(err["message"] ?? err["hint"] ?? "Request failed"),
|
|
305
433
|
code: typeof err["code"] === "string" ? err["code"] : null,
|
|
306
434
|
})
|
|
@@ -329,3 +457,5 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
329
457
|
// ─── StorageError ─────────────────────────────────────────────────────────────
|
|
330
458
|
|
|
331
459
|
export type { SupatypeError }
|
|
460
|
+
export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
|
|
461
|
+
export { QueryCache, defaultQueryCache } from "./query-cache.js"
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { sha256 } from "@noble/hashes/sha2.js"
|
|
2
|
+
import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js"
|
|
3
|
+
|
|
4
|
+
/** UTF-8 string → lowercase hex SHA-256 (browser + Node). */
|
|
5
|
+
export function sha256Hex(input: string): string {
|
|
6
|
+
return bytesToHex(sha256(utf8ToBytes(input)))
|
|
7
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -126,6 +126,9 @@ export interface QueryResult<TData> {
|
|
|
126
126
|
data: TData | null
|
|
127
127
|
error: SupatypeError | null
|
|
128
128
|
count: number | null
|
|
129
|
+
meta?: {
|
|
130
|
+
cacheStatus?: "HIT" | "MISS" | "BYPASS" | undefined
|
|
131
|
+
} | undefined
|
|
129
132
|
}
|
|
130
133
|
|
|
131
134
|
// ─── RPC result ──────────────────────────────────────────────────────────────
|
|
@@ -255,6 +258,10 @@ export interface SupatypeClientConfig {
|
|
|
255
258
|
* Applied to every HTTP request made by the client.
|
|
256
259
|
*/
|
|
257
260
|
timeout?: number | undefined
|
|
261
|
+
/**
|
|
262
|
+
* In-memory GET query cache. When omitted, a shared default cache is used.
|
|
263
|
+
*/
|
|
264
|
+
queryCache?: import("./query-cache.js").QueryCache | undefined
|
|
258
265
|
/**
|
|
259
266
|
* Pre-load a session at construction time (SSR use case).
|
|
260
267
|
* Used by `@supatype/ssr` to inject a cookie-parsed session into the client
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Data plane waits for session refresh before attaching JWTs to REST requests.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
6
|
+
import { createClient } from "../src/index.js"
|
|
7
|
+
|
|
8
|
+
const BASE = "http://localhost:18473"
|
|
9
|
+
const ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiJ9.test"
|
|
10
|
+
const GOTRUE = `${BASE}/auth/v1`
|
|
11
|
+
|
|
12
|
+
function fakeJwt(payload: Record<string, unknown>): string {
|
|
13
|
+
const header = btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }))
|
|
14
|
+
const body = btoa(JSON.stringify(payload))
|
|
15
|
+
return `${header}.${body}.sig`
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const RAW_USER = {
|
|
19
|
+
id: "user-1",
|
|
20
|
+
email: "a@b.com",
|
|
21
|
+
role: "authenticated",
|
|
22
|
+
app_metadata: {},
|
|
23
|
+
user_metadata: {},
|
|
24
|
+
created_at: "2024-01-01T00:00:00Z",
|
|
25
|
+
updated_at: "2024-01-01T00:00:00Z",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
describe("createClient data plane auth", () => {
|
|
30
|
+
let store: Map<string, string>
|
|
31
|
+
|
|
32
|
+
beforeEach(() => {
|
|
33
|
+
vi.restoreAllMocks()
|
|
34
|
+
store = new Map<string, string>()
|
|
35
|
+
const localStorage = {
|
|
36
|
+
getItem: (key: string) => store.get(key) ?? null,
|
|
37
|
+
setItem: (key: string, value: string) => {
|
|
38
|
+
store.set(key, value)
|
|
39
|
+
},
|
|
40
|
+
removeItem: (key: string) => {
|
|
41
|
+
store.delete(key)
|
|
42
|
+
},
|
|
43
|
+
}
|
|
44
|
+
vi.stubGlobal("localStorage", localStorage)
|
|
45
|
+
vi.stubGlobal("window", { localStorage, location: { protocol: "http:" } })
|
|
46
|
+
vi.stubGlobal("document", { cookie: "" })
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it("refreshes expired session before REST request and uses new access token", async () => {
|
|
50
|
+
const expiredAccess = fakeJwt({
|
|
51
|
+
role: "authenticated",
|
|
52
|
+
sub: "user-1",
|
|
53
|
+
exp: Math.floor(Date.now() / 1000) - 60,
|
|
54
|
+
})
|
|
55
|
+
const freshAccess = fakeJwt({
|
|
56
|
+
role: "authenticated",
|
|
57
|
+
sub: "user-1",
|
|
58
|
+
exp: Math.floor(Date.now() / 1000) + 3600,
|
|
59
|
+
})
|
|
60
|
+
const expiredSession = {
|
|
61
|
+
access_token: expiredAccess,
|
|
62
|
+
refresh_token: "valid-refresh",
|
|
63
|
+
token_type: "bearer",
|
|
64
|
+
expires_in: 3600,
|
|
65
|
+
expires_at: Math.floor(Date.now() / 1000) - 60,
|
|
66
|
+
user: RAW_USER,
|
|
67
|
+
}
|
|
68
|
+
store.set("supatype.auth.session", JSON.stringify(expiredSession))
|
|
69
|
+
|
|
70
|
+
const fetchSpy = vi.fn(async (url: string, init?: RequestInit) => {
|
|
71
|
+
if (url.includes("/auth/v1/token")) {
|
|
72
|
+
return {
|
|
73
|
+
ok: true,
|
|
74
|
+
status: 200,
|
|
75
|
+
json: async () => ({
|
|
76
|
+
access_token: freshAccess,
|
|
77
|
+
refresh_token: "rotated-refresh",
|
|
78
|
+
token_type: "bearer",
|
|
79
|
+
expires_in: 3600,
|
|
80
|
+
expires_at: Math.floor(Date.now() / 1000) + 3600,
|
|
81
|
+
user: RAW_USER,
|
|
82
|
+
}),
|
|
83
|
+
headers: { get: () => null },
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
ok: true,
|
|
88
|
+
status: 200,
|
|
89
|
+
json: async () => [{ id: "1", title: "Hello" }],
|
|
90
|
+
headers: { get: () => null },
|
|
91
|
+
}
|
|
92
|
+
})
|
|
93
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
94
|
+
|
|
95
|
+
const client = createClient({ url: BASE, anonKey: ANON_KEY })
|
|
96
|
+
const { data, error } = await client.from("post").select("id,title")
|
|
97
|
+
|
|
98
|
+
expect(error).toBeNull()
|
|
99
|
+
expect(data).toEqual([{ id: "1", title: "Hello" }])
|
|
100
|
+
|
|
101
|
+
const restCall = fetchSpy.mock.calls.find(([url]) =>
|
|
102
|
+
String(url).includes("/rest/v1/post"),
|
|
103
|
+
) as [string, RequestInit] | undefined
|
|
104
|
+
expect(restCall).toBeDefined()
|
|
105
|
+
expect((restCall![1].headers as Record<string, string>)["Authorization"]).toBe(
|
|
106
|
+
`Bearer ${freshAccess}`,
|
|
107
|
+
)
|
|
108
|
+
expect(fetchSpy.mock.calls.some(([url]) => String(url).includes(`${GOTRUE}/token`))).toBe(true)
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
it("falls back to anon headers after refresh fails", async () => {
|
|
112
|
+
const expiredAccess = fakeJwt({
|
|
113
|
+
role: "authenticated",
|
|
114
|
+
sub: "user-1",
|
|
115
|
+
exp: Math.floor(Date.now() / 1000) - 60,
|
|
116
|
+
})
|
|
117
|
+
const expiredSession = {
|
|
118
|
+
access_token: expiredAccess,
|
|
119
|
+
refresh_token: "dead-refresh",
|
|
120
|
+
token_type: "bearer",
|
|
121
|
+
expires_in: 3600,
|
|
122
|
+
expires_at: Math.floor(Date.now() / 1000) - 60,
|
|
123
|
+
user: RAW_USER,
|
|
124
|
+
}
|
|
125
|
+
store.set("supatype.auth.session", JSON.stringify(expiredSession))
|
|
126
|
+
|
|
127
|
+
const fetchSpy = vi.fn(async (url: string) => {
|
|
128
|
+
if (url.includes("/auth/v1/token")) {
|
|
129
|
+
return {
|
|
130
|
+
ok: false,
|
|
131
|
+
status: 400,
|
|
132
|
+
json: async () => ({ error_description: "Invalid Refresh Token" }),
|
|
133
|
+
headers: { get: () => null },
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
ok: true,
|
|
138
|
+
status: 200,
|
|
139
|
+
json: async () => [{ id: "1", title: "Anon ok" }],
|
|
140
|
+
headers: { get: () => null },
|
|
141
|
+
}
|
|
142
|
+
})
|
|
143
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
144
|
+
|
|
145
|
+
const client = createClient({ url: BASE, anonKey: ANON_KEY })
|
|
146
|
+
const { data, error } = await client.from("post").select("id,title")
|
|
147
|
+
|
|
148
|
+
expect(error).toBeNull()
|
|
149
|
+
expect(data).toEqual([{ id: "1", title: "Anon ok" }])
|
|
150
|
+
|
|
151
|
+
const restCall = fetchSpy.mock.calls.find(([url]) =>
|
|
152
|
+
String(url).includes("/rest/v1/post"),
|
|
153
|
+
) as [string, RequestInit] | undefined
|
|
154
|
+
expect((restCall![1].headers as Record<string, string>)["Authorization"]).toBe(
|
|
155
|
+
`Bearer ${ANON_KEY}`,
|
|
156
|
+
)
|
|
157
|
+
expect(store.get("supatype.auth.session")).toBeUndefined()
|
|
158
|
+
})
|
|
159
|
+
})
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach, vi, afterEach } from "vitest"
|
|
2
|
+
import { QueryBuilder } from "../src/query.js"
|
|
3
|
+
import { QueryCache, buildCacheKey, identityFingerprint } from "../src/query-cache.js"
|
|
4
|
+
|
|
5
|
+
describe("query-cache", () => {
|
|
6
|
+
it("identityFingerprint differs for different subs", () => {
|
|
7
|
+
const payloadA = btoa(JSON.stringify({ sub: "a", role: "authenticated" }))
|
|
8
|
+
const payloadB = btoa(JSON.stringify({ sub: "b", role: "authenticated" }))
|
|
9
|
+
const a = identityFingerprint({ Authorization: `Bearer x.${payloadA}.y` }, "user")
|
|
10
|
+
const b = identityFingerprint({ Authorization: `Bearer x.${payloadB}.y` }, "user")
|
|
11
|
+
expect(a).not.toBe(b)
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it("identityFingerprint stable for same sub across token strings", () => {
|
|
15
|
+
const payload = btoa(JSON.stringify({ sub: "user-1", role: "authenticated" }))
|
|
16
|
+
const a = identityFingerprint({ Authorization: `Bearer aaa.${payload}.sig1` }, "user")
|
|
17
|
+
const b = identityFingerprint({ Authorization: `Bearer bbb.${payload}.sig2` }, "user")
|
|
18
|
+
expect(a).toBe(b)
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
it("public scope uses global fingerprint", () => {
|
|
22
|
+
expect(identityFingerprint({ Authorization: "Bearer x" }, "public")).toBe("global")
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it("buildCacheKey is stable", () => {
|
|
26
|
+
const h = { Authorization: "Bearer x" }
|
|
27
|
+
const k1 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
|
|
28
|
+
const k2 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
|
|
29
|
+
expect(k1).toBe(k2)
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it("QueryCache expires entries", () => {
|
|
33
|
+
vi.useFakeTimers()
|
|
34
|
+
const cache = new QueryCache()
|
|
35
|
+
cache.set("k", { data: [{ id: 1 }], error: null, count: 1 }, 1000)
|
|
36
|
+
expect(cache.get("k")?.data).toEqual([{ id: 1 }])
|
|
37
|
+
vi.advanceTimersByTime(1001)
|
|
38
|
+
expect(cache.get("k")).toBeNull()
|
|
39
|
+
vi.useRealTimers()
|
|
40
|
+
})
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
describe("QueryBuilder.cache", () => {
|
|
44
|
+
const fetchMock = vi.fn()
|
|
45
|
+
|
|
46
|
+
beforeEach(() => {
|
|
47
|
+
fetchMock.mockReset()
|
|
48
|
+
vi.stubGlobal("fetch", fetchMock)
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
afterEach(() => {
|
|
52
|
+
vi.unstubAllGlobals()
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it("returns cached result without second fetch", async () => {
|
|
56
|
+
fetchMock.mockResolvedValue(
|
|
57
|
+
new Response(JSON.stringify([{ id: 1 }]), {
|
|
58
|
+
status: 200,
|
|
59
|
+
headers: { "Content-Type": "application/json" },
|
|
60
|
+
}),
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
const cache = new QueryCache()
|
|
64
|
+
const qb = new QueryBuilder<{ id: number }>(
|
|
65
|
+
"http://localhost:9999",
|
|
66
|
+
"/rest/v1/posts",
|
|
67
|
+
{ Authorization: "Bearer anon" },
|
|
68
|
+
"*",
|
|
69
|
+
cache,
|
|
70
|
+
).cache({ ttl: 60_000 })
|
|
71
|
+
|
|
72
|
+
const r1 = await qb
|
|
73
|
+
expect(r1.data).toEqual([{ id: 1 }])
|
|
74
|
+
expect(fetchMock).toHaveBeenCalledTimes(1)
|
|
75
|
+
|
|
76
|
+
const r2 = await qb
|
|
77
|
+
expect(r2.data).toEqual([{ id: 1 }])
|
|
78
|
+
expect(r2.meta?.cacheStatus).toBe("HIT")
|
|
79
|
+
expect(fetchMock).toHaveBeenCalledTimes(1)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it("sends X-Supatype-Cache when server: true", async () => {
|
|
83
|
+
fetchMock.mockResolvedValue(
|
|
84
|
+
new Response(JSON.stringify([]), {
|
|
85
|
+
status: 200,
|
|
86
|
+
headers: {
|
|
87
|
+
"Content-Type": "application/json",
|
|
88
|
+
"X-Supatype-Cache-Status": "MISS",
|
|
89
|
+
},
|
|
90
|
+
}),
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
|
|
94
|
+
.cache({ ttl: 30_000, server: true })
|
|
95
|
+
|
|
96
|
+
const init = fetchMock.mock.calls[0]?.[1] as RequestInit
|
|
97
|
+
expect(init.headers).toMatchObject({ "X-Supatype-Cache": "max-age=30" })
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
it("sends public directive when server and public", async () => {
|
|
101
|
+
fetchMock.mockResolvedValue(
|
|
102
|
+
new Response(JSON.stringify([]), { status: 200, headers: { "Content-Type": "application/json" } }),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
|
|
106
|
+
.cache({ ttl: 30_000, server: true, public: true })
|
|
107
|
+
|
|
108
|
+
const init = fetchMock.mock.calls[0]?.[1] as RequestInit
|
|
109
|
+
expect(init.headers).toMatchObject({ "X-Supatype-Cache": "max-age=30, public" })
|
|
110
|
+
})
|
|
111
|
+
})
|
|
112
|
+
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest"
|
|
2
|
+
import { sha256Hex } from "../src/sha256-hex.js"
|
|
3
|
+
|
|
4
|
+
describe("sha256Hex", () => {
|
|
5
|
+
it("matches known test vector", () => {
|
|
6
|
+
expect(sha256Hex("abc")).toBe(
|
|
7
|
+
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
|
|
8
|
+
)
|
|
9
|
+
})
|
|
10
|
+
})
|