@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/.turbo/turbo-build.log
CHANGED
package/.turbo/turbo-test.log
CHANGED
|
@@ -1,26 +1,28 @@
|
|
|
1
1
|
|
|
2
|
-
> @supatype/client@0.1.
|
|
2
|
+
> @supatype/client@0.1.6 test /home/runner/work/supatype/supatype/packages/client
|
|
3
3
|
> vitest run
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
[1m[46m RUN [49m[22m [36mv4.0.18 [39m[90m/home/runner/work/supatype/supatype/packages/client[39m
|
|
7
7
|
|
|
8
|
-
[32m✓[39m tests/
|
|
9
|
-
[32m✓[39m tests/
|
|
10
|
-
[32m✓[39m tests/realtime-multi-tenant-integration.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m
|
|
11
|
-
[32m✓[39m tests/
|
|
12
|
-
[32m✓[39m tests/retry-integration.test.ts [2m([22m[2m12 tests[22m[2m)[22m[32m
|
|
13
|
-
[32m✓[39m tests/
|
|
14
|
-
[32m✓[39m tests/
|
|
15
|
-
|
|
16
|
-
[32m✓[39m tests/
|
|
17
|
-
[32m✓[39m tests/
|
|
18
|
-
[32m✓[39m tests/data-plane-auth.test.ts [2m([22m[2m2 tests[22m[2m)[22m[32m
|
|
19
|
-
[32m✓[39m tests/
|
|
20
|
-
[32m✓[39m tests/
|
|
8
|
+
[32m✓[39m tests/auth.test.ts [2m([22m[2m36 tests[22m[2m)[22m[32m 111[2mms[22m[39m
|
|
9
|
+
[32m✓[39m tests/query.test.ts [2m([22m[2m35 tests[22m[2m)[22m[32m 50[2mms[22m[39m
|
|
10
|
+
[32m✓[39m tests/realtime-multi-tenant-integration.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 214[2mms[22m[39m
|
|
11
|
+
[32m✓[39m tests/mfa-totp-integration.test.ts [2m([22m[2m12 tests[22m[2m)[22m[32m 23[2mms[22m[39m
|
|
12
|
+
[32m✓[39m tests/retry-integration.test.ts [2m([22m[2m12 tests[22m[2m)[22m[32m 184[2mms[22m[39m
|
|
13
|
+
[32m✓[39m tests/rate-limit-integration.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 220[2mms[22m[39m
|
|
14
|
+
[32m✓[39m tests/storage-quota-integration.test.ts [2m([22m[2m10 tests[22m[2m)[22m[33m 486[2mms[22m[39m
|
|
15
|
+
[33m[2m✓[22m[39m first upload succeeds, second hits quota [33m 325[2mms[22m[39m
|
|
16
|
+
[32m✓[39m tests/storage-upload-limit-integration.test.ts [2m([22m[2m11 tests[22m[2m)[22m[32m 204[2mms[22m[39m
|
|
17
|
+
[32m✓[39m tests/types.test.ts [2m([22m[2m12 tests[22m[2m)[22m[32m 113[2mms[22m[39m
|
|
18
|
+
[32m✓[39m tests/data-plane-auth.test.ts [2m([22m[2m2 tests[22m[2m)[22m[32m 45[2mms[22m[39m
|
|
19
|
+
[32m✓[39m tests/serverless.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 18[2mms[22m[39m
|
|
20
|
+
[32m✓[39m tests/query-cache.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 59[2mms[22m[39m
|
|
21
|
+
[32m✓[39m tests/pkce.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 16[2mms[22m[39m
|
|
22
|
+
[32m✓[39m tests/sha256-hex.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 14[2mms[22m[39m
|
|
21
23
|
|
|
22
|
-
[2m Test Files [22m [1m[
|
|
23
|
-
[2m Tests [22m [1m[
|
|
24
|
-
[2m Start at [22m
|
|
25
|
-
[2m Duration [22m
|
|
24
|
+
[2m Test Files [22m [1m[32m14 passed[39m[22m[90m (14)[39m
|
|
25
|
+
[2m Tests [22m [1m[32m167 passed[39m[22m[90m (167)[39m
|
|
26
|
+
[2m Start at [22m 19:08:23
|
|
27
|
+
[2m Duration [22m 4.05s[2m (transform 2.46s, setup 0ms, import 3.53s, tests 1.76s, environment 6ms)[22m
|
|
26
28
|
|
package/dist/auth.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import type { AuthChangeEvent, AuthMFAChallengeResponse, AuthMFAEnrollResponse, AuthMFAListFactorsResponse, OtpType, Session, SupatypeError, User } from "./types.js";
|
|
1
|
+
import type { AuthChangeEvent, AuthFlowType, AuthMFAChallengeResponse, AuthMFAEnrollResponse, AuthMFAListFactorsResponse, AuthStorage, OtpType, Session, SupatypeError, User } from "./types.js";
|
|
2
2
|
type AuthListener = (event: AuthChangeEvent, session: Session | null) => void;
|
|
3
3
|
interface AuthClientOptions {
|
|
4
4
|
initialSession?: Session | undefined;
|
|
5
5
|
persistSession?: boolean | undefined;
|
|
6
6
|
storageKey?: string | undefined;
|
|
7
7
|
cookiePrefix?: string | undefined;
|
|
8
|
+
/** Custom session store (replaces browser localStorage/cookies when set). */
|
|
9
|
+
storage?: AuthStorage | undefined;
|
|
8
10
|
}
|
|
9
11
|
export declare class AuthClient {
|
|
10
12
|
private readonly url;
|
|
@@ -16,11 +18,20 @@ export declare class AuthClient {
|
|
|
16
18
|
private readonly storageKey;
|
|
17
19
|
private readonly cookieName;
|
|
18
20
|
private readonly storage;
|
|
21
|
+
/** When true, session is also mirrored to document.cookie (browser default path only). */
|
|
22
|
+
private readonly useCookies;
|
|
23
|
+
/** Resolves when async storage hydration completes (immediate when not used). */
|
|
24
|
+
private readonly ready;
|
|
19
25
|
/** Pending auto-refresh timer; refreshes the access token shortly before it expires. */
|
|
20
26
|
private refreshTimer;
|
|
21
27
|
/** Dedupes concurrent refresh attempts (getSession + auto-refresh). */
|
|
22
28
|
private refreshInFlight;
|
|
29
|
+
/** In-memory PKCE code_verifier for the in-flight OAuth / OTP redirect. */
|
|
30
|
+
private codeVerifier;
|
|
23
31
|
constructor(url: string, baseHeaders: Record<string, string>, opts?: AuthClientOptions);
|
|
32
|
+
/** Resolves when custom storage hydration finishes (no-op resolve when sync). */
|
|
33
|
+
whenReady(): Promise<void>;
|
|
34
|
+
private hydrateFromStorage;
|
|
24
35
|
/** Milliseconds since epoch when the access token expires (with optional skew). */
|
|
25
36
|
private sessionExpiresAtMs;
|
|
26
37
|
private jwtExpMs;
|
|
@@ -31,6 +42,7 @@ export declare class AuthClient {
|
|
|
31
42
|
* Safe to call before REST/RPC requests; no-op when signed out or token is valid.
|
|
32
43
|
*/
|
|
33
44
|
ensureValidSession(): Promise<void>;
|
|
45
|
+
private ensureValidSessionInternal;
|
|
34
46
|
/** Schedule a token refresh ~60s before the current session expires. */
|
|
35
47
|
private scheduleAutoRefresh;
|
|
36
48
|
signUp(credentials: {
|
|
@@ -72,6 +84,9 @@ export declare class AuthClient {
|
|
|
72
84
|
provider: string;
|
|
73
85
|
options?: {
|
|
74
86
|
redirectTo?: string | undefined;
|
|
87
|
+
/** Default: `implicit` (web-compatible). Pass `pkce` for mobile / RN. */
|
|
88
|
+
flowType?: AuthFlowType | undefined;
|
|
89
|
+
scopes?: string | undefined;
|
|
75
90
|
} | undefined;
|
|
76
91
|
}): Promise<{
|
|
77
92
|
data: {
|
|
@@ -80,6 +95,43 @@ export declare class AuthClient {
|
|
|
80
95
|
};
|
|
81
96
|
error: SupatypeError | null;
|
|
82
97
|
}>;
|
|
98
|
+
/**
|
|
99
|
+
* Apply tokens from an OAuth / deep-link redirect (implicit grant) or restore a session.
|
|
100
|
+
* Fetches `/user` to hydrate the user object, then persists via the configured storage.
|
|
101
|
+
*/
|
|
102
|
+
setSession(params: {
|
|
103
|
+
accessToken: string;
|
|
104
|
+
refreshToken: string;
|
|
105
|
+
}): Promise<{
|
|
106
|
+
data: {
|
|
107
|
+
session: Session | null;
|
|
108
|
+
user: User | null;
|
|
109
|
+
};
|
|
110
|
+
error: SupatypeError | null;
|
|
111
|
+
}>;
|
|
112
|
+
/**
|
|
113
|
+
* Exchange a PKCE auth code for a session (`POST /token?grant_type=pkce`).
|
|
114
|
+
* Requires a prior `signInWithOAuth({ options: { flowType: "pkce" } })` (or OTP with PKCE)
|
|
115
|
+
* so the matching `code_verifier` is available in memory / storage.
|
|
116
|
+
*/
|
|
117
|
+
exchangeCodeForSession(authCode: string): Promise<{
|
|
118
|
+
data: {
|
|
119
|
+
session: Session | null;
|
|
120
|
+
user: User | null;
|
|
121
|
+
};
|
|
122
|
+
error: SupatypeError | null;
|
|
123
|
+
}>;
|
|
124
|
+
/**
|
|
125
|
+
* Parse an OAuth / magic-link redirect URL and establish a session.
|
|
126
|
+
* Supports PKCE (`?code=`) and implicit (`#access_token=` / query tokens).
|
|
127
|
+
*/
|
|
128
|
+
getSessionFromUrl(url: string): Promise<{
|
|
129
|
+
data: {
|
|
130
|
+
session: Session | null;
|
|
131
|
+
user: User | null;
|
|
132
|
+
};
|
|
133
|
+
error: SupatypeError | null;
|
|
134
|
+
}>;
|
|
83
135
|
signInWithOtp(opts: {
|
|
84
136
|
email?: string | undefined;
|
|
85
137
|
phone?: string | undefined;
|
|
@@ -274,10 +326,19 @@ export declare class AuthClient {
|
|
|
274
326
|
/** Returns the current session's access token, or null when signed out. */
|
|
275
327
|
get currentAccessToken(): string | null;
|
|
276
328
|
private getBrowserStorage;
|
|
329
|
+
private codeVerifierStorageKey;
|
|
330
|
+
private beginPkce;
|
|
331
|
+
private readCodeVerifier;
|
|
332
|
+
private clearCodeVerifier;
|
|
333
|
+
/** Decode JWT `exp` claim without verifying the signature. */
|
|
334
|
+
private decodeJwtExp;
|
|
335
|
+
private readStorageItem;
|
|
336
|
+
private loadPersistedSessionAsync;
|
|
277
337
|
private loadPersistedSession;
|
|
278
338
|
private parsePersistedSession;
|
|
279
339
|
private normalizePersistedSession;
|
|
280
340
|
private syncPersistedSession;
|
|
341
|
+
private writePersistedSession;
|
|
281
342
|
private serializeUserForCookie;
|
|
282
343
|
private readCookie;
|
|
283
344
|
private writeCookie;
|
package/dist/auth.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,wBAAwB,EACxB,qBAAqB,EACrB,0BAA0B,
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,YAAY,EACZ,wBAAwB,EACxB,qBAAqB,EACrB,0BAA0B,EAC1B,WAAW,EAEX,OAAO,EACP,OAAO,EACP,aAAa,EACb,IAAI,EACL,MAAM,YAAY,CAAA;AAOnB,KAAK,YAAY,GAAG,CAAC,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,KAAK,IAAI,CAAA;AAE7E,UAAU,iBAAiB;IACzB,cAAc,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IACpC,cAAc,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IACpC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AC,qBAAqB;IAS7B,OAAO,CAAC,yBAAyB;IA2DjC,OAAO,CAAC,oBAAoB;YAKd,qBAAqB;IA+CnC,OAAO,CAAC,sBAAsB;IAa9B,OAAO,CAAC,UAAU;IAkBlB,OAAO,CAAC,WAAW;IAgBnB,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,GAAG,IAAI;IAqB1C,OAAO,CAAC,UAAU;YAMJ,WAAW;YASX,kBAAkB;IA4BhC,OAAO,CAAC,UAAU;CAqCnB"}
|
package/dist/auth.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createCodeChallengeS256, generateCodeVerifier, PKCE_METHOD_S256, } from "./pkce.js";
|
|
1
2
|
const DEFAULT_STORAGE_KEY = "supatype.auth.session";
|
|
2
3
|
const DEFAULT_COOKIE_PREFIX = "st";
|
|
3
4
|
const DEBUG_AUTH = typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1";
|
|
@@ -11,10 +12,16 @@ export class AuthClient {
|
|
|
11
12
|
storageKey;
|
|
12
13
|
cookieName;
|
|
13
14
|
storage;
|
|
15
|
+
/** When true, session is also mirrored to document.cookie (browser default path only). */
|
|
16
|
+
useCookies;
|
|
17
|
+
/** Resolves when async storage hydration completes (immediate when not used). */
|
|
18
|
+
ready;
|
|
14
19
|
/** Pending auto-refresh timer; refreshes the access token shortly before it expires. */
|
|
15
20
|
refreshTimer = null;
|
|
16
21
|
/** Dedupes concurrent refresh attempts (getSession + auto-refresh). */
|
|
17
22
|
refreshInFlight = null;
|
|
23
|
+
/** In-memory PKCE code_verifier for the in-flight OAuth / OTP redirect. */
|
|
24
|
+
codeVerifier = null;
|
|
18
25
|
constructor(url, baseHeaders, opts = {}) {
|
|
19
26
|
this.url = url;
|
|
20
27
|
this.baseHeaders = baseHeaders;
|
|
@@ -22,9 +29,11 @@ export class AuthClient {
|
|
|
22
29
|
this.storageKey = opts.storageKey ?? DEFAULT_STORAGE_KEY;
|
|
23
30
|
const cookiePrefix = opts.cookiePrefix ?? DEFAULT_COOKIE_PREFIX;
|
|
24
31
|
this.cookieName = `${cookiePrefix}-auth-token`;
|
|
25
|
-
this.
|
|
32
|
+
this.useCookies = opts.storage === undefined;
|
|
33
|
+
this.storage = opts.storage ?? this.getBrowserStorage();
|
|
26
34
|
if (opts.initialSession !== undefined) {
|
|
27
35
|
this.currentSession = opts.initialSession;
|
|
36
|
+
this.ready = Promise.resolve();
|
|
28
37
|
if (DEBUG_AUTH) {
|
|
29
38
|
console.debug("[supatype:auth] constructor initialSession provided", {
|
|
30
39
|
hasSession: true,
|
|
@@ -33,16 +42,25 @@ export class AuthClient {
|
|
|
33
42
|
}
|
|
34
43
|
}
|
|
35
44
|
else if (this.persistSession) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
45
|
+
if (opts.storage !== undefined) {
|
|
46
|
+
this.ready = this.hydrateFromStorage();
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
this.currentSession = this.loadPersistedSession();
|
|
50
|
+
this.ready = Promise.resolve();
|
|
51
|
+
if (DEBUG_AUTH) {
|
|
52
|
+
console.debug("[supatype:auth] constructor loaded persisted session", {
|
|
53
|
+
hasSession: this.currentSession !== null,
|
|
54
|
+
userId: this.currentSession?.user.id ?? null,
|
|
55
|
+
storageKey: this.storageKey,
|
|
56
|
+
cookieName: this.cookieName,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
44
59
|
}
|
|
45
60
|
}
|
|
61
|
+
else {
|
|
62
|
+
this.ready = Promise.resolve();
|
|
63
|
+
}
|
|
46
64
|
// Keep the access token fresh while the app is open (and refresh immediately
|
|
47
65
|
// if a persisted session loaded already expired).
|
|
48
66
|
this.scheduleAutoRefresh();
|
|
@@ -50,6 +68,32 @@ export class AuthClient {
|
|
|
50
68
|
void this.ensureValidSession();
|
|
51
69
|
}
|
|
52
70
|
}
|
|
71
|
+
/** Resolves when custom storage hydration finishes (no-op resolve when sync). */
|
|
72
|
+
whenReady() {
|
|
73
|
+
return this.ready;
|
|
74
|
+
}
|
|
75
|
+
async hydrateFromStorage() {
|
|
76
|
+
try {
|
|
77
|
+
const session = await this.loadPersistedSessionAsync();
|
|
78
|
+
if (session === null)
|
|
79
|
+
return;
|
|
80
|
+
this.currentSession = session;
|
|
81
|
+
this.scheduleAutoRefresh();
|
|
82
|
+
if (this.isAccessTokenExpired(session)) {
|
|
83
|
+
await this.ensureValidSessionInternal();
|
|
84
|
+
}
|
|
85
|
+
this._emitEvent("SIGNED_IN", session);
|
|
86
|
+
if (DEBUG_AUTH) {
|
|
87
|
+
console.debug("[supatype:auth] hydrated session from custom storage", {
|
|
88
|
+
userId: session.user.id,
|
|
89
|
+
storageKey: this.storageKey,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
// Corrupt or unavailable storage — treat as signed out.
|
|
95
|
+
}
|
|
96
|
+
}
|
|
53
97
|
/** Milliseconds since epoch when the access token expires (with optional skew). */
|
|
54
98
|
sessionExpiresAtMs(session) {
|
|
55
99
|
if (session.expiresAt !== undefined)
|
|
@@ -84,6 +128,10 @@ export class AuthClient {
|
|
|
84
128
|
* Safe to call before REST/RPC requests; no-op when signed out or token is valid.
|
|
85
129
|
*/
|
|
86
130
|
async ensureValidSession() {
|
|
131
|
+
await this.ready;
|
|
132
|
+
return this.ensureValidSessionInternal();
|
|
133
|
+
}
|
|
134
|
+
async ensureValidSessionInternal() {
|
|
87
135
|
const session = this.currentSession;
|
|
88
136
|
if (session === null || !this.isAccessTokenExpired(session))
|
|
89
137
|
return;
|
|
@@ -170,8 +218,122 @@ export class AuthClient {
|
|
|
170
218
|
if (opts.options?.redirectTo !== undefined) {
|
|
171
219
|
url.searchParams.set("redirect_to", opts.options.redirectTo);
|
|
172
220
|
}
|
|
221
|
+
if (opts.options?.scopes !== undefined) {
|
|
222
|
+
url.searchParams.set("scopes", opts.options.scopes);
|
|
223
|
+
}
|
|
224
|
+
const flowType = opts.options?.flowType ?? "implicit";
|
|
225
|
+
if (flowType === "pkce") {
|
|
226
|
+
await this.beginPkce();
|
|
227
|
+
url.searchParams.set("code_challenge", createCodeChallengeS256(this.codeVerifier));
|
|
228
|
+
url.searchParams.set("code_challenge_method", PKCE_METHOD_S256);
|
|
229
|
+
}
|
|
173
230
|
return { data: { url: url.toString(), provider: opts.provider }, error: null };
|
|
174
231
|
}
|
|
232
|
+
/**
|
|
233
|
+
* Apply tokens from an OAuth / deep-link redirect (implicit grant) or restore a session.
|
|
234
|
+
* Fetches `/user` to hydrate the user object, then persists via the configured storage.
|
|
235
|
+
*/
|
|
236
|
+
async setSession(params) {
|
|
237
|
+
const res = await fetch(`${this.url}/user`, {
|
|
238
|
+
headers: {
|
|
239
|
+
...this.baseHeaders,
|
|
240
|
+
Authorization: `Bearer ${params.accessToken}`,
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
if (!res.ok) {
|
|
244
|
+
return {
|
|
245
|
+
data: { session: null, user: null },
|
|
246
|
+
error: await this._parseError(res),
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
const raw = await res.json();
|
|
250
|
+
const user = this._parseUser(raw);
|
|
251
|
+
const session = {
|
|
252
|
+
accessToken: params.accessToken,
|
|
253
|
+
refreshToken: params.refreshToken,
|
|
254
|
+
tokenType: "bearer",
|
|
255
|
+
expiresIn: 3600,
|
|
256
|
+
user,
|
|
257
|
+
};
|
|
258
|
+
const exp = this.decodeJwtExp(params.accessToken);
|
|
259
|
+
if (exp !== null) {
|
|
260
|
+
session.expiresAt = exp;
|
|
261
|
+
session.expiresIn = Math.max(0, exp - Math.floor(Date.now() / 1000));
|
|
262
|
+
}
|
|
263
|
+
this._setSession(session);
|
|
264
|
+
return { data: { session, user }, error: null };
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Exchange a PKCE auth code for a session (`POST /token?grant_type=pkce`).
|
|
268
|
+
* Requires a prior `signInWithOAuth({ options: { flowType: "pkce" } })` (or OTP with PKCE)
|
|
269
|
+
* so the matching `code_verifier` is available in memory / storage.
|
|
270
|
+
*/
|
|
271
|
+
async exchangeCodeForSession(authCode) {
|
|
272
|
+
const verifier = await this.readCodeVerifier();
|
|
273
|
+
if (verifier === null) {
|
|
274
|
+
return {
|
|
275
|
+
data: { session: null, user: null },
|
|
276
|
+
error: {
|
|
277
|
+
message: "Missing PKCE code_verifier. Start OAuth with flowType: \"pkce\" first.",
|
|
278
|
+
status: 400,
|
|
279
|
+
},
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
const res = await fetch(`${this.url}/token?grant_type=pkce`, {
|
|
283
|
+
method: "POST",
|
|
284
|
+
headers: this.baseHeaders,
|
|
285
|
+
body: JSON.stringify({
|
|
286
|
+
auth_code: authCode,
|
|
287
|
+
code_verifier: verifier,
|
|
288
|
+
}),
|
|
289
|
+
});
|
|
290
|
+
await this.clearCodeVerifier();
|
|
291
|
+
return this._parseAuthResponse(res);
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Parse an OAuth / magic-link redirect URL and establish a session.
|
|
295
|
+
* Supports PKCE (`?code=`) and implicit (`#access_token=` / query tokens).
|
|
296
|
+
*/
|
|
297
|
+
async getSessionFromUrl(url) {
|
|
298
|
+
let parsed;
|
|
299
|
+
try {
|
|
300
|
+
parsed = new URL(url);
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
return {
|
|
304
|
+
data: { session: null, user: null },
|
|
305
|
+
error: { message: `Invalid redirect URL: ${url}`, status: 400 },
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
const query = parsed.searchParams;
|
|
309
|
+
const hashParams = new URLSearchParams(parsed.hash.startsWith("#") ? parsed.hash.slice(1) : parsed.hash);
|
|
310
|
+
const errorDescription = query.get("error_description") ??
|
|
311
|
+
hashParams.get("error_description") ??
|
|
312
|
+
query.get("error") ??
|
|
313
|
+
hashParams.get("error");
|
|
314
|
+
if (errorDescription !== null && errorDescription !== "") {
|
|
315
|
+
return {
|
|
316
|
+
data: { session: null, user: null },
|
|
317
|
+
error: { message: errorDescription, status: 400 },
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
const code = query.get("code") ?? hashParams.get("code");
|
|
321
|
+
if (code !== null && code !== "") {
|
|
322
|
+
return this.exchangeCodeForSession(code);
|
|
323
|
+
}
|
|
324
|
+
const accessToken = hashParams.get("access_token") ?? query.get("access_token");
|
|
325
|
+
const refreshToken = hashParams.get("refresh_token") ?? query.get("refresh_token");
|
|
326
|
+
if (accessToken !== null && accessToken !== "" && refreshToken !== null && refreshToken !== "") {
|
|
327
|
+
return this.setSession({ accessToken, refreshToken });
|
|
328
|
+
}
|
|
329
|
+
return {
|
|
330
|
+
data: { session: null, user: null },
|
|
331
|
+
error: {
|
|
332
|
+
message: "No auth code or tokens found in redirect URL",
|
|
333
|
+
status: 400,
|
|
334
|
+
},
|
|
335
|
+
};
|
|
336
|
+
}
|
|
175
337
|
async signInWithOtp(opts) {
|
|
176
338
|
const body = {
|
|
177
339
|
create_user: opts.options?.createUser ?? true,
|
|
@@ -222,7 +384,8 @@ export class AuthClient {
|
|
|
222
384
|
return { error: null };
|
|
223
385
|
}
|
|
224
386
|
async getSession() {
|
|
225
|
-
await this.
|
|
387
|
+
await this.ready;
|
|
388
|
+
await this.ensureValidSessionInternal();
|
|
226
389
|
return { data: { session: this.currentSession }, error: null };
|
|
227
390
|
}
|
|
228
391
|
async getUser() {
|
|
@@ -631,8 +794,89 @@ export class AuthClient {
|
|
|
631
794
|
return null;
|
|
632
795
|
}
|
|
633
796
|
}
|
|
797
|
+
codeVerifierStorageKey() {
|
|
798
|
+
return `${this.storageKey}-code-verifier`;
|
|
799
|
+
}
|
|
800
|
+
async beginPkce() {
|
|
801
|
+
const verifier = generateCodeVerifier();
|
|
802
|
+
this.codeVerifier = verifier;
|
|
803
|
+
if (!this.persistSession || this.storage === null)
|
|
804
|
+
return;
|
|
805
|
+
try {
|
|
806
|
+
await this.storage.setItem(this.codeVerifierStorageKey(), verifier);
|
|
807
|
+
}
|
|
808
|
+
catch {
|
|
809
|
+
// Ignore storage write failures — in-memory verifier still works for same-process flows.
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
async readCodeVerifier() {
|
|
813
|
+
if (this.codeVerifier !== null)
|
|
814
|
+
return this.codeVerifier;
|
|
815
|
+
if (this.storage === null)
|
|
816
|
+
return null;
|
|
817
|
+
try {
|
|
818
|
+
const stored = await this.storage.getItem(this.codeVerifierStorageKey());
|
|
819
|
+
if (stored !== null && stored !== "") {
|
|
820
|
+
this.codeVerifier = stored;
|
|
821
|
+
return stored;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
catch {
|
|
825
|
+
// fall through
|
|
826
|
+
}
|
|
827
|
+
return null;
|
|
828
|
+
}
|
|
829
|
+
async clearCodeVerifier() {
|
|
830
|
+
this.codeVerifier = null;
|
|
831
|
+
if (this.storage === null)
|
|
832
|
+
return;
|
|
833
|
+
try {
|
|
834
|
+
await this.storage.removeItem(this.codeVerifierStorageKey());
|
|
835
|
+
}
|
|
836
|
+
catch {
|
|
837
|
+
// Ignore
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
/** Decode JWT `exp` claim without verifying the signature. */
|
|
841
|
+
decodeJwtExp(accessToken) {
|
|
842
|
+
const parts = accessToken.split(".");
|
|
843
|
+
if (parts.length < 2)
|
|
844
|
+
return null;
|
|
845
|
+
try {
|
|
846
|
+
const payload = parts[1];
|
|
847
|
+
const padded = payload + "=".repeat((4 - (payload.length % 4)) % 4);
|
|
848
|
+
const b64 = padded.replace(/-/g, "+").replace(/_/g, "/");
|
|
849
|
+
const json = typeof atob === "function"
|
|
850
|
+
? atob(b64)
|
|
851
|
+
: Buffer.from(b64, "base64").toString("utf8");
|
|
852
|
+
const claims = JSON.parse(json);
|
|
853
|
+
return typeof claims.exp === "number" ? claims.exp : null;
|
|
854
|
+
}
|
|
855
|
+
catch {
|
|
856
|
+
return null;
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
async readStorageItem(key) {
|
|
860
|
+
if (this.storage === null)
|
|
861
|
+
return null;
|
|
862
|
+
return await this.storage.getItem(key);
|
|
863
|
+
}
|
|
864
|
+
async loadPersistedSessionAsync() {
|
|
865
|
+
const fromStorage = await this.readStorageItem(this.storageKey);
|
|
866
|
+
if (fromStorage !== null) {
|
|
867
|
+
const parsed = this.parsePersistedSession(fromStorage);
|
|
868
|
+
if (parsed !== null)
|
|
869
|
+
return parsed;
|
|
870
|
+
}
|
|
871
|
+
return null;
|
|
872
|
+
}
|
|
634
873
|
loadPersistedSession() {
|
|
635
|
-
const
|
|
874
|
+
const raw = this.storage?.getItem(this.storageKey);
|
|
875
|
+
const fromStorage = raw === null || raw === undefined
|
|
876
|
+
? null
|
|
877
|
+
: typeof raw === "string"
|
|
878
|
+
? raw
|
|
879
|
+
: null;
|
|
636
880
|
if (fromStorage !== null) {
|
|
637
881
|
const parsed = this.parsePersistedSession(fromStorage);
|
|
638
882
|
if (DEBUG_AUTH) {
|
|
@@ -644,7 +888,7 @@ export class AuthClient {
|
|
|
644
888
|
if (parsed !== null)
|
|
645
889
|
return parsed;
|
|
646
890
|
}
|
|
647
|
-
if (typeof document !== "undefined") {
|
|
891
|
+
if (this.useCookies && typeof document !== "undefined") {
|
|
648
892
|
const fromCookie = this.readCookie(this.cookieName);
|
|
649
893
|
if (fromCookie !== null) {
|
|
650
894
|
const parsed = this.parsePersistedSession(fromCookie);
|
|
@@ -729,16 +973,20 @@ export class AuthClient {
|
|
|
729
973
|
syncPersistedSession(session) {
|
|
730
974
|
if (!this.persistSession)
|
|
731
975
|
return;
|
|
976
|
+
void this.writePersistedSession(session);
|
|
977
|
+
}
|
|
978
|
+
async writePersistedSession(session) {
|
|
732
979
|
const storage = this.storage;
|
|
733
|
-
const cookieExpires = session?.expiresAt;
|
|
734
980
|
if (session === null) {
|
|
735
981
|
try {
|
|
736
|
-
storage?.removeItem(this.storageKey);
|
|
982
|
+
await storage?.removeItem(this.storageKey);
|
|
737
983
|
}
|
|
738
984
|
catch {
|
|
739
985
|
// Ignore storage write failures.
|
|
740
986
|
}
|
|
741
|
-
|
|
987
|
+
if (this.useCookies) {
|
|
988
|
+
this.writeCookie(this.cookieName, "", -1);
|
|
989
|
+
}
|
|
742
990
|
if (DEBUG_AUTH) {
|
|
743
991
|
console.debug("[supatype:auth] cleared persisted session", {
|
|
744
992
|
storageKey: this.storageKey,
|
|
@@ -757,12 +1005,14 @@ export class AuthClient {
|
|
|
757
1005
|
user: this.serializeUserForCookie(session.user),
|
|
758
1006
|
});
|
|
759
1007
|
try {
|
|
760
|
-
storage?.setItem(this.storageKey, json);
|
|
1008
|
+
await storage?.setItem(this.storageKey, json);
|
|
761
1009
|
}
|
|
762
1010
|
catch {
|
|
763
1011
|
// Ignore storage write failures.
|
|
764
1012
|
}
|
|
765
|
-
|
|
1013
|
+
if (this.useCookies) {
|
|
1014
|
+
this.writeCookie(this.cookieName, cookiePayload, session.expiresAt);
|
|
1015
|
+
}
|
|
766
1016
|
if (DEBUG_AUTH) {
|
|
767
1017
|
console.debug("[supatype:auth] persisted session", {
|
|
768
1018
|
userId: session.user.id,
|