@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/auth.ts
CHANGED
|
@@ -1,28 +1,31 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
AuthChangeEvent,
|
|
3
|
+
AuthFlowType,
|
|
3
4
|
AuthMFAChallengeResponse,
|
|
4
5
|
AuthMFAEnrollResponse,
|
|
5
6
|
AuthMFAListFactorsResponse,
|
|
7
|
+
AuthStorage,
|
|
6
8
|
Factor,
|
|
7
9
|
OtpType,
|
|
8
10
|
Session,
|
|
9
11
|
SupatypeError,
|
|
10
12
|
User,
|
|
11
13
|
} from "./types.js"
|
|
14
|
+
import {
|
|
15
|
+
createCodeChallengeS256,
|
|
16
|
+
generateCodeVerifier,
|
|
17
|
+
PKCE_METHOD_S256,
|
|
18
|
+
} from "./pkce.js"
|
|
12
19
|
|
|
13
20
|
type AuthListener = (event: AuthChangeEvent, session: Session | null) => void
|
|
14
21
|
|
|
15
|
-
interface AuthStorageAdapter {
|
|
16
|
-
getItem(key: string): string | null
|
|
17
|
-
setItem(key: string, value: string): void
|
|
18
|
-
removeItem(key: string): void
|
|
19
|
-
}
|
|
20
|
-
|
|
21
22
|
interface AuthClientOptions {
|
|
22
23
|
initialSession?: Session | undefined
|
|
23
24
|
persistSession?: boolean | undefined
|
|
24
25
|
storageKey?: string | undefined
|
|
25
26
|
cookiePrefix?: string | undefined
|
|
27
|
+
/** Custom session store (replaces browser localStorage/cookies when set). */
|
|
28
|
+
storage?: AuthStorage | undefined
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
const DEFAULT_STORAGE_KEY = "supatype.auth.session"
|
|
@@ -38,11 +41,17 @@ export class AuthClient {
|
|
|
38
41
|
private readonly persistSession: boolean
|
|
39
42
|
private readonly storageKey: string
|
|
40
43
|
private readonly cookieName: string
|
|
41
|
-
private readonly storage:
|
|
44
|
+
private readonly storage: AuthStorage | null
|
|
45
|
+
/** When true, session is also mirrored to document.cookie (browser default path only). */
|
|
46
|
+
private readonly useCookies: boolean
|
|
47
|
+
/** Resolves when async storage hydration completes (immediate when not used). */
|
|
48
|
+
private readonly ready: Promise<void>
|
|
42
49
|
/** Pending auto-refresh timer; refreshes the access token shortly before it expires. */
|
|
43
50
|
private refreshTimer: ReturnType<typeof setTimeout> | null = null
|
|
44
51
|
/** Dedupes concurrent refresh attempts (getSession + auto-refresh). */
|
|
45
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
|
|
46
55
|
|
|
47
56
|
constructor(url: string, baseHeaders: Record<string, string>, opts: AuthClientOptions = {}) {
|
|
48
57
|
this.url = url
|
|
@@ -51,10 +60,12 @@ export class AuthClient {
|
|
|
51
60
|
this.storageKey = opts.storageKey ?? DEFAULT_STORAGE_KEY
|
|
52
61
|
const cookiePrefix = opts.cookiePrefix ?? DEFAULT_COOKIE_PREFIX
|
|
53
62
|
this.cookieName = `${cookiePrefix}-auth-token`
|
|
54
|
-
this.
|
|
63
|
+
this.useCookies = opts.storage === undefined
|
|
64
|
+
this.storage = opts.storage ?? this.getBrowserStorage()
|
|
55
65
|
|
|
56
66
|
if (opts.initialSession !== undefined) {
|
|
57
67
|
this.currentSession = opts.initialSession
|
|
68
|
+
this.ready = Promise.resolve()
|
|
58
69
|
if (DEBUG_AUTH) {
|
|
59
70
|
console.debug("[supatype:auth] constructor initialSession provided", {
|
|
60
71
|
hasSession: true,
|
|
@@ -62,15 +73,22 @@ export class AuthClient {
|
|
|
62
73
|
})
|
|
63
74
|
}
|
|
64
75
|
} else if (this.persistSession) {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
76
|
+
if (opts.storage !== undefined) {
|
|
77
|
+
this.ready = this.hydrateFromStorage()
|
|
78
|
+
} else {
|
|
79
|
+
this.currentSession = this.loadPersistedSession()
|
|
80
|
+
this.ready = Promise.resolve()
|
|
81
|
+
if (DEBUG_AUTH) {
|
|
82
|
+
console.debug("[supatype:auth] constructor loaded persisted session", {
|
|
83
|
+
hasSession: this.currentSession !== null,
|
|
84
|
+
userId: this.currentSession?.user.id ?? null,
|
|
85
|
+
storageKey: this.storageKey,
|
|
86
|
+
cookieName: this.cookieName,
|
|
87
|
+
})
|
|
88
|
+
}
|
|
73
89
|
}
|
|
90
|
+
} else {
|
|
91
|
+
this.ready = Promise.resolve()
|
|
74
92
|
}
|
|
75
93
|
// Keep the access token fresh while the app is open (and refresh immediately
|
|
76
94
|
// if a persisted session loaded already expired).
|
|
@@ -80,6 +98,32 @@ export class AuthClient {
|
|
|
80
98
|
}
|
|
81
99
|
}
|
|
82
100
|
|
|
101
|
+
/** Resolves when custom storage hydration finishes (no-op resolve when sync). */
|
|
102
|
+
whenReady(): Promise<void> {
|
|
103
|
+
return this.ready
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private async hydrateFromStorage(): Promise<void> {
|
|
107
|
+
try {
|
|
108
|
+
const session = await this.loadPersistedSessionAsync()
|
|
109
|
+
if (session === null) return
|
|
110
|
+
this.currentSession = session
|
|
111
|
+
this.scheduleAutoRefresh()
|
|
112
|
+
if (this.isAccessTokenExpired(session)) {
|
|
113
|
+
await this.ensureValidSessionInternal()
|
|
114
|
+
}
|
|
115
|
+
this._emitEvent("SIGNED_IN", session)
|
|
116
|
+
if (DEBUG_AUTH) {
|
|
117
|
+
console.debug("[supatype:auth] hydrated session from custom storage", {
|
|
118
|
+
userId: session.user.id,
|
|
119
|
+
storageKey: this.storageKey,
|
|
120
|
+
})
|
|
121
|
+
}
|
|
122
|
+
} catch {
|
|
123
|
+
// Corrupt or unavailable storage — treat as signed out.
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
83
127
|
/** Milliseconds since epoch when the access token expires (with optional skew). */
|
|
84
128
|
private sessionExpiresAtMs(session: Session): number | null {
|
|
85
129
|
if (session.expiresAt !== undefined) return session.expiresAt * 1000
|
|
@@ -112,6 +156,11 @@ export class AuthClient {
|
|
|
112
156
|
* Safe to call before REST/RPC requests; no-op when signed out or token is valid.
|
|
113
157
|
*/
|
|
114
158
|
async ensureValidSession(): Promise<void> {
|
|
159
|
+
await this.ready
|
|
160
|
+
return this.ensureValidSessionInternal()
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private async ensureValidSessionInternal(): Promise<void> {
|
|
115
164
|
const session = this.currentSession
|
|
116
165
|
if (session === null || !this.isAccessTokenExpired(session)) return
|
|
117
166
|
if (!session.refreshToken?.trim()) {
|
|
@@ -221,7 +270,12 @@ export class AuthClient {
|
|
|
221
270
|
|
|
222
271
|
async signInWithOAuth(opts: {
|
|
223
272
|
provider: string
|
|
224
|
-
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
|
|
225
279
|
}): Promise<{
|
|
226
280
|
data: { url: string; provider: string }
|
|
227
281
|
error: SupatypeError | null
|
|
@@ -231,9 +285,147 @@ export class AuthClient {
|
|
|
231
285
|
if (opts.options?.redirectTo !== undefined) {
|
|
232
286
|
url.searchParams.set("redirect_to", opts.options.redirectTo)
|
|
233
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
|
+
}
|
|
234
297
|
return { data: { url: url.toString(), provider: opts.provider }, error: null }
|
|
235
298
|
}
|
|
236
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
|
+
|
|
237
429
|
async signInWithOtp(opts: {
|
|
238
430
|
email?: string | undefined
|
|
239
431
|
phone?: string | undefined
|
|
@@ -297,7 +489,8 @@ export class AuthClient {
|
|
|
297
489
|
data: { session: Session | null }
|
|
298
490
|
error: SupatypeError | null
|
|
299
491
|
}> {
|
|
300
|
-
await this.
|
|
492
|
+
await this.ready
|
|
493
|
+
await this.ensureValidSessionInternal()
|
|
301
494
|
return { data: { session: this.currentSession }, error: null }
|
|
302
495
|
}
|
|
303
496
|
|
|
@@ -791,7 +984,7 @@ export class AuthClient {
|
|
|
791
984
|
return this.currentSession?.accessToken ?? null
|
|
792
985
|
}
|
|
793
986
|
|
|
794
|
-
private getBrowserStorage():
|
|
987
|
+
private getBrowserStorage(): AuthStorage | null {
|
|
795
988
|
if (typeof window === "undefined") return null
|
|
796
989
|
try {
|
|
797
990
|
return window.localStorage
|
|
@@ -800,8 +993,87 @@ export class AuthClient {
|
|
|
800
993
|
}
|
|
801
994
|
}
|
|
802
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
|
+
|
|
1055
|
+
private async readStorageItem(key: string): Promise<string | null> {
|
|
1056
|
+
if (this.storage === null) return null
|
|
1057
|
+
return await this.storage.getItem(key)
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
private async loadPersistedSessionAsync(): Promise<Session | null> {
|
|
1061
|
+
const fromStorage = await this.readStorageItem(this.storageKey)
|
|
1062
|
+
if (fromStorage !== null) {
|
|
1063
|
+
const parsed = this.parsePersistedSession(fromStorage)
|
|
1064
|
+
if (parsed !== null) return parsed
|
|
1065
|
+
}
|
|
1066
|
+
return null
|
|
1067
|
+
}
|
|
1068
|
+
|
|
803
1069
|
private loadPersistedSession(): Session | null {
|
|
804
|
-
const
|
|
1070
|
+
const raw = this.storage?.getItem(this.storageKey)
|
|
1071
|
+
const fromStorage =
|
|
1072
|
+
raw === null || raw === undefined
|
|
1073
|
+
? null
|
|
1074
|
+
: typeof raw === "string"
|
|
1075
|
+
? raw
|
|
1076
|
+
: null
|
|
805
1077
|
if (fromStorage !== null) {
|
|
806
1078
|
const parsed = this.parsePersistedSession(fromStorage)
|
|
807
1079
|
if (DEBUG_AUTH) {
|
|
@@ -812,7 +1084,7 @@ export class AuthClient {
|
|
|
812
1084
|
}
|
|
813
1085
|
if (parsed !== null) return parsed
|
|
814
1086
|
}
|
|
815
|
-
if (typeof document !== "undefined") {
|
|
1087
|
+
if (this.useCookies && typeof document !== "undefined") {
|
|
816
1088
|
const fromCookie = this.readCookie(this.cookieName)
|
|
817
1089
|
if (fromCookie !== null) {
|
|
818
1090
|
const parsed = this.parsePersistedSession(fromCookie)
|
|
@@ -899,15 +1171,20 @@ export class AuthClient {
|
|
|
899
1171
|
|
|
900
1172
|
private syncPersistedSession(session: Session | null): void {
|
|
901
1173
|
if (!this.persistSession) return
|
|
1174
|
+
void this.writePersistedSession(session)
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
private async writePersistedSession(session: Session | null): Promise<void> {
|
|
902
1178
|
const storage = this.storage
|
|
903
|
-
const cookieExpires = session?.expiresAt
|
|
904
1179
|
if (session === null) {
|
|
905
1180
|
try {
|
|
906
|
-
storage?.removeItem(this.storageKey)
|
|
1181
|
+
await storage?.removeItem(this.storageKey)
|
|
907
1182
|
} catch {
|
|
908
1183
|
// Ignore storage write failures.
|
|
909
1184
|
}
|
|
910
|
-
|
|
1185
|
+
if (this.useCookies) {
|
|
1186
|
+
this.writeCookie(this.cookieName, "", -1)
|
|
1187
|
+
}
|
|
911
1188
|
if (DEBUG_AUTH) {
|
|
912
1189
|
console.debug("[supatype:auth] cleared persisted session", {
|
|
913
1190
|
storageKey: this.storageKey,
|
|
@@ -927,11 +1204,13 @@ export class AuthClient {
|
|
|
927
1204
|
user: this.serializeUserForCookie(session.user),
|
|
928
1205
|
})
|
|
929
1206
|
try {
|
|
930
|
-
storage?.setItem(this.storageKey, json)
|
|
1207
|
+
await storage?.setItem(this.storageKey, json)
|
|
931
1208
|
} catch {
|
|
932
1209
|
// Ignore storage write failures.
|
|
933
1210
|
}
|
|
934
|
-
|
|
1211
|
+
if (this.useCookies) {
|
|
1212
|
+
this.writeCookie(this.cookieName, cookiePayload, session.expiresAt)
|
|
1213
|
+
}
|
|
935
1214
|
if (DEBUG_AUTH) {
|
|
936
1215
|
console.debug("[supatype:auth] persisted session", {
|
|
937
1216
|
userId: session.user.id,
|
package/src/index.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
|
|
|
3
3
|
import { defaultQueryCache, type QueryCache } from "./query-cache.js"
|
|
4
4
|
import { StorageClient } from "./storage.js"
|
|
5
5
|
import { RealtimeClient } from "./realtime.js"
|
|
6
|
+
import type { RealtimeEvent, RealtimePayload } from "./realtime.js"
|
|
6
7
|
import { PostgrestError } from "./errors.js"
|
|
7
8
|
import { createRetryFetch } from "./retry.js"
|
|
8
9
|
import { warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
|
|
@@ -14,18 +15,22 @@ import type {
|
|
|
14
15
|
SupatypeFunctions,
|
|
15
16
|
SupatypeClientConfig,
|
|
16
17
|
SupatypeError,
|
|
18
|
+
SelectQueryOptions,
|
|
17
19
|
} from "./types.js"
|
|
18
20
|
|
|
19
21
|
export type {
|
|
20
22
|
User,
|
|
21
23
|
Session,
|
|
22
24
|
AuthChangeEvent,
|
|
25
|
+
AuthFlowType,
|
|
23
26
|
SupatypeError,
|
|
24
27
|
QueryResult,
|
|
25
28
|
RpcResult,
|
|
26
29
|
AnyDatabase,
|
|
27
30
|
SupatypeClientConfig,
|
|
28
31
|
FunctionDef,
|
|
32
|
+
AuthStorage,
|
|
33
|
+
SelectQueryOptions,
|
|
29
34
|
TableDef,
|
|
30
35
|
TableInsert,
|
|
31
36
|
SupatypeModels,
|
|
@@ -33,6 +38,11 @@ export type {
|
|
|
33
38
|
SupatypeFunctions,
|
|
34
39
|
AugmentedDatabase,
|
|
35
40
|
} from "./types.js"
|
|
41
|
+
export {
|
|
42
|
+
generateCodeVerifier,
|
|
43
|
+
createCodeChallengeS256,
|
|
44
|
+
PKCE_METHOD_S256,
|
|
45
|
+
} from "./pkce.js"
|
|
36
46
|
export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
|
|
37
47
|
export { AuthClient } from "./auth.js"
|
|
38
48
|
export { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
|
|
@@ -61,26 +71,34 @@ interface TableDef {
|
|
|
61
71
|
|
|
62
72
|
class TableClient<TDef extends TableDef> {
|
|
63
73
|
private readonly baseUrl: string
|
|
74
|
+
private readonly table: string
|
|
64
75
|
private readonly path: string
|
|
65
76
|
private readonly getHeaders: HeadersProvider
|
|
66
77
|
private readonly onUnauthorized: (() => Promise<void>) | undefined
|
|
67
78
|
private readonly queryCache: QueryCache
|
|
79
|
+
private readonly realtime: RealtimeClient
|
|
68
80
|
|
|
69
81
|
constructor(
|
|
70
82
|
baseUrl: string,
|
|
71
83
|
table: string,
|
|
72
84
|
getHeaders: HeadersProvider,
|
|
85
|
+
realtime: RealtimeClient,
|
|
73
86
|
queryCache: QueryCache = defaultQueryCache,
|
|
74
87
|
onUnauthorized?: (() => Promise<void>) | undefined,
|
|
75
88
|
) {
|
|
76
89
|
this.baseUrl = baseUrl
|
|
90
|
+
this.table = table
|
|
77
91
|
this.path = `/rest/v1/${table}`
|
|
78
92
|
this.getHeaders = getHeaders
|
|
93
|
+
this.realtime = realtime
|
|
79
94
|
this.onUnauthorized = onUnauthorized
|
|
80
95
|
this.queryCache = queryCache
|
|
81
96
|
}
|
|
82
97
|
|
|
83
|
-
select<TResult = TDef["Row"]>(
|
|
98
|
+
select<TResult = TDef["Row"]>(
|
|
99
|
+
columns?: string | undefined,
|
|
100
|
+
options?: SelectQueryOptions | undefined,
|
|
101
|
+
): QueryBuilder<TResult> {
|
|
84
102
|
return new QueryBuilder<TResult>(
|
|
85
103
|
this.baseUrl,
|
|
86
104
|
this.path,
|
|
@@ -88,6 +106,7 @@ class TableClient<TDef extends TableDef> {
|
|
|
88
106
|
columns,
|
|
89
107
|
this.queryCache,
|
|
90
108
|
this.onUnauthorized,
|
|
109
|
+
options,
|
|
91
110
|
)
|
|
92
111
|
}
|
|
93
112
|
|
|
@@ -142,6 +161,43 @@ class TableClient<TDef extends TableDef> {
|
|
|
142
161
|
this.onUnauthorized,
|
|
143
162
|
)
|
|
144
163
|
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Subscribe to postgres_changes for this table (typed to Row).
|
|
167
|
+
* Phase 10.6 F11 — preferred over raw `client.realtime.channel(...)`.
|
|
168
|
+
*/
|
|
169
|
+
subscribe(
|
|
170
|
+
callback: (payload: RealtimePayload<TDef["Row"]>) => void,
|
|
171
|
+
opts?: {
|
|
172
|
+
event?: RealtimeEvent | undefined
|
|
173
|
+
filter?: string | undefined
|
|
174
|
+
schema?: string | undefined
|
|
175
|
+
} | undefined,
|
|
176
|
+
): {
|
|
177
|
+
unsubscribe: () => void
|
|
178
|
+
channel: ReturnType<RealtimeClient["channel"]>
|
|
179
|
+
} {
|
|
180
|
+
const event = opts?.event ?? "*"
|
|
181
|
+
const schema = opts?.schema ?? "public"
|
|
182
|
+
const channel = this.realtime
|
|
183
|
+
.channel(`${schema}:${this.table}`)
|
|
184
|
+
.on(
|
|
185
|
+
"postgres_changes",
|
|
186
|
+
{
|
|
187
|
+
event,
|
|
188
|
+
schema,
|
|
189
|
+
table: this.table,
|
|
190
|
+
...(opts?.filter !== undefined && { filter: opts.filter }),
|
|
191
|
+
},
|
|
192
|
+
callback,
|
|
193
|
+
)
|
|
194
|
+
return {
|
|
195
|
+
channel,
|
|
196
|
+
unsubscribe: () => {
|
|
197
|
+
channel.unsubscribe()
|
|
198
|
+
},
|
|
199
|
+
}
|
|
200
|
+
}
|
|
145
201
|
}
|
|
146
202
|
|
|
147
203
|
// ─── Main client ──────────────────────────────────────────────────────────────
|
|
@@ -388,6 +444,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
388
444
|
persistSession: config.auth?.persistSession,
|
|
389
445
|
storageKey: config.auth?.storageKey,
|
|
390
446
|
cookiePrefix: config.auth?.cookiePrefix,
|
|
447
|
+
storage: config.auth?.storage,
|
|
391
448
|
})
|
|
392
449
|
// Storage admin operations (listBuckets, createBucket, etc.) require service_role.
|
|
393
450
|
// When a service role key is provided (developer tools like Studio), use it for
|
|
@@ -440,7 +497,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
440
497
|
table: TTable,
|
|
441
498
|
): TableClient<TDatabase["public"]["Tables"][TTable]> {
|
|
442
499
|
type TDef = TDatabase["public"]["Tables"][TTable]
|
|
443
|
-
return new TableClient<TDef>(config.url, table, getAuthHeaders, queryCache, onUnauthorized)
|
|
500
|
+
return new TableClient<TDef>(config.url, table, getAuthHeaders, realtime, queryCache, onUnauthorized)
|
|
444
501
|
},
|
|
445
502
|
|
|
446
503
|
global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow> {
|
|
@@ -448,12 +505,12 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
448
505
|
type TDef = { Row: TRow; Insert: TRow; Update: Partial<TRow> }
|
|
449
506
|
return {
|
|
450
507
|
async get(): Promise<{ data: TRow | null; error: SupatypeError | null }> {
|
|
451
|
-
const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, queryCache, onUnauthorized)
|
|
508
|
+
const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, realtime, queryCache, onUnauthorized)
|
|
452
509
|
const result = await tc.select().limit(1).maybeSingle()
|
|
453
510
|
return { data: result.data ?? null, error: result.error }
|
|
454
511
|
},
|
|
455
512
|
async update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }> {
|
|
456
|
-
const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, queryCache, onUnauthorized)
|
|
513
|
+
const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, realtime, queryCache, onUnauthorized)
|
|
457
514
|
const result = await tc.upsert(data as TRow)
|
|
458
515
|
const row = Array.isArray(result.data) ? (result.data[0] as TRow | undefined) ?? null : null
|
|
459
516
|
return { data: row, error: result.error }
|
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
|
+
}
|