@supatype/client 0.1.5 → 0.1.7
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 +21 -19
- package/.turbo/turbo-typecheck.log +1 -1
- package/dist/auth.d.ts +49 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +179 -0
- package/dist/auth.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- 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 +9 -1
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +46 -9
- package/dist/query.js.map +1 -1
- package/dist/types.d.ts +37 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/auth.ts +211 -1
- package/src/index.ts +10 -0
- package/src/pkce.ts +32 -0
- package/src/query.ts +49 -12
- package/src/types.ts +39 -0
- package/tests/auth.test.ts +125 -0
- package/tests/masked-fields.test.ts +51 -0
- package/tests/pkce.test.ts +30 -0
- package/tsconfig.tsbuildinfo +1 -1
package/src/auth.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
AuthChangeEvent,
|
|
3
|
+
AuthFlowType,
|
|
3
4
|
AuthMFAChallengeResponse,
|
|
4
5
|
AuthMFAEnrollResponse,
|
|
5
6
|
AuthMFAListFactorsResponse,
|
|
@@ -10,6 +11,11 @@ import type {
|
|
|
10
11
|
SupatypeError,
|
|
11
12
|
User,
|
|
12
13
|
} from "./types.js"
|
|
14
|
+
import {
|
|
15
|
+
createCodeChallengeS256,
|
|
16
|
+
generateCodeVerifier,
|
|
17
|
+
PKCE_METHOD_S256,
|
|
18
|
+
} from "./pkce.js"
|
|
13
19
|
|
|
14
20
|
type AuthListener = (event: AuthChangeEvent, session: Session | null) => void
|
|
15
21
|
|
|
@@ -44,6 +50,8 @@ export class AuthClient {
|
|
|
44
50
|
private refreshTimer: ReturnType<typeof setTimeout> | null = null
|
|
45
51
|
/** Dedupes concurrent refresh attempts (getSession + auto-refresh). */
|
|
46
52
|
private refreshInFlight: Promise<void> | null = null
|
|
53
|
+
/** In-memory PKCE code_verifier for the in-flight OAuth / OTP redirect. */
|
|
54
|
+
private codeVerifier: string | null = null
|
|
47
55
|
|
|
48
56
|
constructor(url: string, baseHeaders: Record<string, string>, opts: AuthClientOptions = {}) {
|
|
49
57
|
this.url = url
|
|
@@ -262,7 +270,12 @@ export class AuthClient {
|
|
|
262
270
|
|
|
263
271
|
async signInWithOAuth(opts: {
|
|
264
272
|
provider: string
|
|
265
|
-
options?: {
|
|
273
|
+
options?: {
|
|
274
|
+
redirectTo?: string | undefined
|
|
275
|
+
/** Default: `implicit` (web-compatible). Pass `pkce` for mobile / RN. */
|
|
276
|
+
flowType?: AuthFlowType | undefined
|
|
277
|
+
scopes?: string | undefined
|
|
278
|
+
} | undefined
|
|
266
279
|
}): Promise<{
|
|
267
280
|
data: { url: string; provider: string }
|
|
268
281
|
error: SupatypeError | null
|
|
@@ -272,9 +285,147 @@ export class AuthClient {
|
|
|
272
285
|
if (opts.options?.redirectTo !== undefined) {
|
|
273
286
|
url.searchParams.set("redirect_to", opts.options.redirectTo)
|
|
274
287
|
}
|
|
288
|
+
if (opts.options?.scopes !== undefined) {
|
|
289
|
+
url.searchParams.set("scopes", opts.options.scopes)
|
|
290
|
+
}
|
|
291
|
+
const flowType = opts.options?.flowType ?? "implicit"
|
|
292
|
+
if (flowType === "pkce") {
|
|
293
|
+
await this.beginPkce()
|
|
294
|
+
url.searchParams.set("code_challenge", createCodeChallengeS256(this.codeVerifier!))
|
|
295
|
+
url.searchParams.set("code_challenge_method", PKCE_METHOD_S256)
|
|
296
|
+
}
|
|
275
297
|
return { data: { url: url.toString(), provider: opts.provider }, error: null }
|
|
276
298
|
}
|
|
277
299
|
|
|
300
|
+
/**
|
|
301
|
+
* Apply tokens from an OAuth / deep-link redirect (implicit grant) or restore a session.
|
|
302
|
+
* Fetches `/user` to hydrate the user object, then persists via the configured storage.
|
|
303
|
+
*/
|
|
304
|
+
async setSession(params: {
|
|
305
|
+
accessToken: string
|
|
306
|
+
refreshToken: string
|
|
307
|
+
}): Promise<{
|
|
308
|
+
data: { session: Session | null; user: User | null }
|
|
309
|
+
error: SupatypeError | null
|
|
310
|
+
}> {
|
|
311
|
+
const res = await fetch(`${this.url}/user`, {
|
|
312
|
+
headers: {
|
|
313
|
+
...this.baseHeaders,
|
|
314
|
+
Authorization: `Bearer ${params.accessToken}`,
|
|
315
|
+
},
|
|
316
|
+
})
|
|
317
|
+
if (!res.ok) {
|
|
318
|
+
return {
|
|
319
|
+
data: { session: null, user: null },
|
|
320
|
+
error: await this._parseError(res),
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
const raw = await res.json() as Record<string, unknown>
|
|
324
|
+
const user = this._parseUser(raw)
|
|
325
|
+
const session: Session = {
|
|
326
|
+
accessToken: params.accessToken,
|
|
327
|
+
refreshToken: params.refreshToken,
|
|
328
|
+
tokenType: "bearer",
|
|
329
|
+
expiresIn: 3600,
|
|
330
|
+
user,
|
|
331
|
+
}
|
|
332
|
+
const exp = this.decodeJwtExp(params.accessToken)
|
|
333
|
+
if (exp !== null) {
|
|
334
|
+
session.expiresAt = exp
|
|
335
|
+
session.expiresIn = Math.max(0, exp - Math.floor(Date.now() / 1000))
|
|
336
|
+
}
|
|
337
|
+
this._setSession(session)
|
|
338
|
+
return { data: { session, user }, error: null }
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Exchange a PKCE auth code for a session (`POST /token?grant_type=pkce`).
|
|
343
|
+
* Requires a prior `signInWithOAuth({ options: { flowType: "pkce" } })` (or OTP with PKCE)
|
|
344
|
+
* so the matching `code_verifier` is available in memory / storage.
|
|
345
|
+
*/
|
|
346
|
+
async exchangeCodeForSession(authCode: string): Promise<{
|
|
347
|
+
data: { session: Session | null; user: User | null }
|
|
348
|
+
error: SupatypeError | null
|
|
349
|
+
}> {
|
|
350
|
+
const verifier = await this.readCodeVerifier()
|
|
351
|
+
if (verifier === null) {
|
|
352
|
+
return {
|
|
353
|
+
data: { session: null, user: null },
|
|
354
|
+
error: {
|
|
355
|
+
message: "Missing PKCE code_verifier. Start OAuth with flowType: \"pkce\" first.",
|
|
356
|
+
status: 400,
|
|
357
|
+
},
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
const res = await fetch(`${this.url}/token?grant_type=pkce`, {
|
|
361
|
+
method: "POST",
|
|
362
|
+
headers: this.baseHeaders,
|
|
363
|
+
body: JSON.stringify({
|
|
364
|
+
auth_code: authCode,
|
|
365
|
+
code_verifier: verifier,
|
|
366
|
+
}),
|
|
367
|
+
})
|
|
368
|
+
await this.clearCodeVerifier()
|
|
369
|
+
return this._parseAuthResponse(res)
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Parse an OAuth / magic-link redirect URL and establish a session.
|
|
374
|
+
* Supports PKCE (`?code=`) and implicit (`#access_token=` / query tokens).
|
|
375
|
+
*/
|
|
376
|
+
async getSessionFromUrl(url: string): Promise<{
|
|
377
|
+
data: { session: Session | null; user: User | null }
|
|
378
|
+
error: SupatypeError | null
|
|
379
|
+
}> {
|
|
380
|
+
let parsed: URL
|
|
381
|
+
try {
|
|
382
|
+
parsed = new URL(url)
|
|
383
|
+
} catch {
|
|
384
|
+
return {
|
|
385
|
+
data: { session: null, user: null },
|
|
386
|
+
error: { message: `Invalid redirect URL: ${url}`, status: 400 },
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const query = parsed.searchParams
|
|
391
|
+
const hashParams = new URLSearchParams(
|
|
392
|
+
parsed.hash.startsWith("#") ? parsed.hash.slice(1) : parsed.hash,
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
const errorDescription =
|
|
396
|
+
query.get("error_description") ??
|
|
397
|
+
hashParams.get("error_description") ??
|
|
398
|
+
query.get("error") ??
|
|
399
|
+
hashParams.get("error")
|
|
400
|
+
if (errorDescription !== null && errorDescription !== "") {
|
|
401
|
+
return {
|
|
402
|
+
data: { session: null, user: null },
|
|
403
|
+
error: { message: errorDescription, status: 400 },
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const code = query.get("code") ?? hashParams.get("code")
|
|
408
|
+
if (code !== null && code !== "") {
|
|
409
|
+
return this.exchangeCodeForSession(code)
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const accessToken =
|
|
413
|
+
hashParams.get("access_token") ?? query.get("access_token")
|
|
414
|
+
const refreshToken =
|
|
415
|
+
hashParams.get("refresh_token") ?? query.get("refresh_token")
|
|
416
|
+
if (accessToken !== null && accessToken !== "" && refreshToken !== null && refreshToken !== "") {
|
|
417
|
+
return this.setSession({ accessToken, refreshToken })
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
return {
|
|
421
|
+
data: { session: null, user: null },
|
|
422
|
+
error: {
|
|
423
|
+
message: "No auth code or tokens found in redirect URL",
|
|
424
|
+
status: 400,
|
|
425
|
+
},
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
278
429
|
async signInWithOtp(opts: {
|
|
279
430
|
email?: string | undefined
|
|
280
431
|
phone?: string | undefined
|
|
@@ -842,6 +993,65 @@ export class AuthClient {
|
|
|
842
993
|
}
|
|
843
994
|
}
|
|
844
995
|
|
|
996
|
+
private codeVerifierStorageKey(): string {
|
|
997
|
+
return `${this.storageKey}-code-verifier`
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
private async beginPkce(): Promise<void> {
|
|
1001
|
+
const verifier = generateCodeVerifier()
|
|
1002
|
+
this.codeVerifier = verifier
|
|
1003
|
+
if (!this.persistSession || this.storage === null) return
|
|
1004
|
+
try {
|
|
1005
|
+
await this.storage.setItem(this.codeVerifierStorageKey(), verifier)
|
|
1006
|
+
} catch {
|
|
1007
|
+
// Ignore storage write failures — in-memory verifier still works for same-process flows.
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
private async readCodeVerifier(): Promise<string | null> {
|
|
1012
|
+
if (this.codeVerifier !== null) return this.codeVerifier
|
|
1013
|
+
if (this.storage === null) return null
|
|
1014
|
+
try {
|
|
1015
|
+
const stored = await this.storage.getItem(this.codeVerifierStorageKey())
|
|
1016
|
+
if (stored !== null && stored !== "") {
|
|
1017
|
+
this.codeVerifier = stored
|
|
1018
|
+
return stored
|
|
1019
|
+
}
|
|
1020
|
+
} catch {
|
|
1021
|
+
// fall through
|
|
1022
|
+
}
|
|
1023
|
+
return null
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
private async clearCodeVerifier(): Promise<void> {
|
|
1027
|
+
this.codeVerifier = null
|
|
1028
|
+
if (this.storage === null) return
|
|
1029
|
+
try {
|
|
1030
|
+
await this.storage.removeItem(this.codeVerifierStorageKey())
|
|
1031
|
+
} catch {
|
|
1032
|
+
// Ignore
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
/** Decode JWT `exp` claim without verifying the signature. */
|
|
1037
|
+
private decodeJwtExp(accessToken: string): number | null {
|
|
1038
|
+
const parts = accessToken.split(".")
|
|
1039
|
+
if (parts.length < 2) return null
|
|
1040
|
+
try {
|
|
1041
|
+
const payload = parts[1]!
|
|
1042
|
+
const padded = payload + "=".repeat((4 - (payload.length % 4)) % 4)
|
|
1043
|
+
const b64 = padded.replace(/-/g, "+").replace(/_/g, "/")
|
|
1044
|
+
const json =
|
|
1045
|
+
typeof atob === "function"
|
|
1046
|
+
? atob(b64)
|
|
1047
|
+
: Buffer.from(b64, "base64").toString("utf8")
|
|
1048
|
+
const claims = JSON.parse(json) as { exp?: unknown }
|
|
1049
|
+
return typeof claims.exp === "number" ? claims.exp : null
|
|
1050
|
+
} catch {
|
|
1051
|
+
return null
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
|
|
845
1055
|
private async readStorageItem(key: string): Promise<string | null> {
|
|
846
1056
|
if (this.storage === null) return null
|
|
847
1057
|
return await this.storage.getItem(key)
|
package/src/index.ts
CHANGED
|
@@ -22,8 +22,10 @@ export type {
|
|
|
22
22
|
User,
|
|
23
23
|
Session,
|
|
24
24
|
AuthChangeEvent,
|
|
25
|
+
AuthFlowType,
|
|
25
26
|
SupatypeError,
|
|
26
27
|
QueryResult,
|
|
28
|
+
MaskedField,
|
|
27
29
|
RpcResult,
|
|
28
30
|
AnyDatabase,
|
|
29
31
|
SupatypeClientConfig,
|
|
@@ -37,6 +39,11 @@ export type {
|
|
|
37
39
|
SupatypeFunctions,
|
|
38
40
|
AugmentedDatabase,
|
|
39
41
|
} from "./types.js"
|
|
42
|
+
export {
|
|
43
|
+
generateCodeVerifier,
|
|
44
|
+
createCodeChallengeS256,
|
|
45
|
+
PKCE_METHOD_S256,
|
|
46
|
+
} from "./pkce.js"
|
|
40
47
|
export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
|
|
41
48
|
export { AuthClient } from "./auth.js"
|
|
42
49
|
export { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
|
|
@@ -425,6 +432,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
425
432
|
apikey: config.anonKey,
|
|
426
433
|
Authorization: `Bearer ${config.anonKey}`,
|
|
427
434
|
"Content-Type": "application/json",
|
|
435
|
+
...config.headers,
|
|
428
436
|
}
|
|
429
437
|
|
|
430
438
|
// Create a retry-aware fetch bound to client-level config
|
|
@@ -448,6 +456,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
448
456
|
apikey: config.serviceRoleKey,
|
|
449
457
|
Authorization: `Bearer ${config.serviceRoleKey}`,
|
|
450
458
|
"Content-Type": "application/json",
|
|
459
|
+
...config.headers,
|
|
451
460
|
}
|
|
452
461
|
: baseHeaders
|
|
453
462
|
const storage = new StorageClient(`${config.url}/storage/v1`, storageHeaders)
|
|
@@ -462,6 +471,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
462
471
|
apikey: config.serviceRoleKey,
|
|
463
472
|
Authorization: `Bearer ${config.serviceRoleKey}`,
|
|
464
473
|
"Content-Type": "application/json",
|
|
474
|
+
...config.headers,
|
|
465
475
|
}
|
|
466
476
|
}
|
|
467
477
|
await auth.ensureValidSession()
|
package/src/pkce.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { sha256 } from "@noble/hashes/sha2.js"
|
|
2
|
+
import { utf8ToBytes } from "@noble/hashes/utils.js"
|
|
3
|
+
|
|
4
|
+
/** RFC 7636 code_challenge_method value expected by GoTrue. */
|
|
5
|
+
export const PKCE_METHOD_S256 = "s256"
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Encode bytes as base64url without padding (RFC 7636).
|
|
9
|
+
*/
|
|
10
|
+
export function bytesToBase64Url(bytes: Uint8Array): string {
|
|
11
|
+
let binary = ""
|
|
12
|
+
for (const byte of bytes) {
|
|
13
|
+
binary += String.fromCharCode(byte)
|
|
14
|
+
}
|
|
15
|
+
const b64 =
|
|
16
|
+
typeof btoa === "function"
|
|
17
|
+
? btoa(binary)
|
|
18
|
+
: Buffer.from(bytes).toString("base64")
|
|
19
|
+
return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Cryptographically random PKCE code_verifier (43 chars, unreserved alphabet). */
|
|
23
|
+
export function generateCodeVerifier(): string {
|
|
24
|
+
const bytes = new Uint8Array(32)
|
|
25
|
+
globalThis.crypto.getRandomValues(bytes)
|
|
26
|
+
return bytesToBase64Url(bytes)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** S256 code_challenge = BASE64URL(SHA256(ASCII(code_verifier))). */
|
|
30
|
+
export function createCodeChallengeS256(verifier: string): string {
|
|
31
|
+
return bytesToBase64Url(sha256(utf8ToBytes(verifier)))
|
|
32
|
+
}
|
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, SelectQueryOptions, SupatypeError } from "./types.js"
|
|
3
|
+
import type { MaskedField, 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") ||
|
|
@@ -24,14 +24,40 @@ function decodeJwtRoleFromAuthHeader(headers: Record<string, string>): string |
|
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
/**
|
|
28
|
+
* Parse `X-Supatype-Masked-Fields: salary=row, ssn=identity`.
|
|
29
|
+
*
|
|
30
|
+
* Unrecognised entries are dropped rather than guessed at: this is advisory decoration, so
|
|
31
|
+
* a header from a newer server saying something this client does not understand should
|
|
32
|
+
* degrade to silence, never to a wrong claim about which columns are masked.
|
|
33
|
+
*/
|
|
34
|
+
export function parseMaskedFields(header: string | null): MaskedField[] | undefined {
|
|
35
|
+
if (header === null || header.trim() === "") return undefined
|
|
36
|
+
|
|
37
|
+
const fields: MaskedField[] = []
|
|
38
|
+
for (const entry of header.split(",")) {
|
|
39
|
+
const [column, scope] = entry.split("=", 2).map((part) => part.trim())
|
|
40
|
+
if (column === undefined || column === "") continue
|
|
41
|
+
if (scope !== "identity" && scope !== "row") continue
|
|
42
|
+
fields.push({ column, scope })
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return fields.length > 0 ? fields : undefined
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function withMeta<T>(
|
|
28
49
|
result: QueryResult<T>,
|
|
29
|
-
cacheStatus?: CacheStatus,
|
|
50
|
+
meta: { cacheStatus?: CacheStatus; maskedFields?: MaskedField[] | undefined },
|
|
30
51
|
): QueryResult<T> {
|
|
31
|
-
|
|
52
|
+
const { cacheStatus, maskedFields } = meta
|
|
53
|
+
if (cacheStatus === undefined && maskedFields === undefined) return result
|
|
32
54
|
return {
|
|
33
55
|
...result,
|
|
34
|
-
meta: {
|
|
56
|
+
meta: {
|
|
57
|
+
...(result.meta ?? {}),
|
|
58
|
+
...(cacheStatus !== undefined && { cacheStatus }),
|
|
59
|
+
...(maskedFields !== undefined && { maskedFields }),
|
|
60
|
+
},
|
|
35
61
|
}
|
|
36
62
|
}
|
|
37
63
|
|
|
@@ -216,7 +242,17 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
216
242
|
Accept: "application/vnd.pgrst.object+json",
|
|
217
243
|
})
|
|
218
244
|
if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
|
|
219
|
-
|
|
245
|
+
// Some proxies drop Accept and return a one-element array — unwrap.
|
|
246
|
+
const row = (Array.isArray(data) ? data[0] : data) as TRow | undefined
|
|
247
|
+
if (row === undefined) {
|
|
248
|
+
return {
|
|
249
|
+
data: null,
|
|
250
|
+
error: { message: "JSON object requested, multiple (or no) rows returned", code: "PGRST116" },
|
|
251
|
+
count: null,
|
|
252
|
+
...(meta && { meta }),
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return { data: row, error: null, count: 1, ...(meta && { meta }) }
|
|
220
256
|
}
|
|
221
257
|
|
|
222
258
|
/** Return a single row or null (errors if many found). */
|
|
@@ -282,7 +318,7 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
282
318
|
})
|
|
283
319
|
const cached = this.queryCache.get<TRow[]>(cacheKey)
|
|
284
320
|
if (cached) {
|
|
285
|
-
return
|
|
321
|
+
return withMeta(cached, { cacheStatus: "HIT" })
|
|
286
322
|
}
|
|
287
323
|
}
|
|
288
324
|
|
|
@@ -308,6 +344,7 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
308
344
|
? parseInt(contentRange.split("/")[1] ?? "0", 10)
|
|
309
345
|
: null
|
|
310
346
|
|
|
347
|
+
const maskedFields = parseMaskedFields(res.headers.get("X-Supatype-Masked-Fields"))
|
|
311
348
|
const serverCacheStatus = res.headers.get("X-Supatype-Cache-Status") as CacheStatus | null
|
|
312
349
|
const cacheStatus: CacheStatus =
|
|
313
350
|
serverCacheStatus === "HIT" || serverCacheStatus === "MISS" || serverCacheStatus === "BYPASS"
|
|
@@ -328,7 +365,7 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
328
365
|
code: typeof err["code"] === "string" ? err["code"] : null,
|
|
329
366
|
})
|
|
330
367
|
}
|
|
331
|
-
return
|
|
368
|
+
return withMeta<TRow[]>(
|
|
332
369
|
{
|
|
333
370
|
data: null,
|
|
334
371
|
error: {
|
|
@@ -338,14 +375,14 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
338
375
|
},
|
|
339
376
|
count: null,
|
|
340
377
|
},
|
|
341
|
-
cacheStatus,
|
|
378
|
+
{ cacheStatus, maskedFields },
|
|
342
379
|
)
|
|
343
380
|
}
|
|
344
381
|
|
|
345
382
|
if (method === "HEAD" || res.status === 204) {
|
|
346
|
-
return
|
|
383
|
+
return withMeta<TRow[]>(
|
|
347
384
|
{ data: null, error: null, count },
|
|
348
|
-
cacheStatus,
|
|
385
|
+
{ cacheStatus, maskedFields },
|
|
349
386
|
)
|
|
350
387
|
}
|
|
351
388
|
|
|
@@ -360,7 +397,7 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
360
397
|
this.queryCache.set(cacheKey, result, this.cacheOptions.ttl)
|
|
361
398
|
}
|
|
362
399
|
|
|
363
|
-
return
|
|
400
|
+
return withMeta(result, { cacheStatus, maskedFields })
|
|
364
401
|
}
|
|
365
402
|
}
|
|
366
403
|
|
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 {
|
|
@@ -122,12 +132,37 @@ export interface SupatypeError {
|
|
|
122
132
|
|
|
123
133
|
// ─── Query result ─────────────────────────────────────────────────────────────
|
|
124
134
|
|
|
135
|
+
/**
|
|
136
|
+
* A column in the response that carries a read restriction.
|
|
137
|
+
*
|
|
138
|
+
* Postgres cannot omit a column — the result-set shape is fixed and identical for every row
|
|
139
|
+
* — so a column you may not read comes back as `null`, indistinguishable on the wire from a
|
|
140
|
+
* value that is genuinely null. This says which nulls are explicable by masking.
|
|
141
|
+
*
|
|
142
|
+
* Advisory. It describes the schema's restrictions, not a decision: what you can actually
|
|
143
|
+
* read is enforced in the database, and ignoring or tampering with this changes nothing.
|
|
144
|
+
*/
|
|
145
|
+
export interface MaskedField {
|
|
146
|
+
column: string
|
|
147
|
+
/**
|
|
148
|
+
* `identity` — the verdict is the same for every row in this response, so a `null` in the
|
|
149
|
+
* column is explicable by masking for the whole result set.
|
|
150
|
+
*
|
|
151
|
+
* `row` — the rule reads the row, so only *some* nulls are masked values and the rest are
|
|
152
|
+
* genuinely null. Deliberately not narrowed further: the header is computed before the
|
|
153
|
+
* query runs, so claiming more would be a guess.
|
|
154
|
+
*/
|
|
155
|
+
scope: "identity" | "row"
|
|
156
|
+
}
|
|
157
|
+
|
|
125
158
|
export interface QueryResult<TData> {
|
|
126
159
|
data: TData | null
|
|
127
160
|
error: SupatypeError | null
|
|
128
161
|
count: number | null
|
|
129
162
|
meta?: {
|
|
130
163
|
cacheStatus?: "HIT" | "MISS" | "BYPASS" | undefined
|
|
164
|
+
/** Present only when the response named restricted columns. Absent means "not stated". */
|
|
165
|
+
maskedFields?: MaskedField[] | undefined
|
|
131
166
|
} | undefined
|
|
132
167
|
}
|
|
133
168
|
|
|
@@ -285,4 +320,8 @@ export interface SupatypeClientConfig {
|
|
|
285
320
|
* before any requests are made.
|
|
286
321
|
*/
|
|
287
322
|
initialSession?: Session | undefined
|
|
323
|
+
/**
|
|
324
|
+
* Extra headers merged into every request (e.g. Studio `X-Supatype-Environment`).
|
|
325
|
+
*/
|
|
326
|
+
headers?: Record<string, string> | undefined
|
|
288
327
|
}
|
package/tests/auth.test.ts
CHANGED
|
@@ -455,6 +455,131 @@ describe("AuthClient custom storage", () => {
|
|
|
455
455
|
})
|
|
456
456
|
})
|
|
457
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
|
+
|
|
458
583
|
describe("AuthClient stale persisted session", () => {
|
|
459
584
|
let store: Map<string, string>
|
|
460
585
|
|