@motherbase/client 1.5.0 → 1.5.2
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/README.md +25 -1
- package/dist/admin.d.ts +131 -0
- package/dist/admin.d.ts.map +1 -0
- package/dist/admin.js +121 -0
- package/dist/admin.js.map +1 -0
- package/dist/auth.d.ts +463 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +884 -0
- package/dist/auth.js.map +1 -0
- package/dist/channel.d.ts +129 -0
- package/dist/channel.d.ts.map +1 -0
- package/dist/channel.js +215 -0
- package/dist/channel.js.map +1 -0
- package/dist/compat.d.ts +40 -0
- package/dist/compat.d.ts.map +1 -0
- package/dist/compat.js +100 -0
- package/dist/compat.js.map +1 -0
- package/dist/cookie.d.ts +68 -0
- package/dist/cookie.d.ts.map +1 -0
- package/dist/cookie.js +152 -0
- package/dist/cookie.js.map +1 -0
- package/dist/database.d.ts +188 -0
- package/dist/database.d.ts.map +1 -0
- package/dist/database.js +2 -0
- package/dist/database.js.map +1 -0
- package/dist/functions.d.ts +60 -0
- package/dist/functions.d.ts.map +1 -0
- package/dist/functions.js +75 -0
- package/dist/functions.js.map +1 -0
- package/dist/http.d.ts +122 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +206 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +215 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +365 -0
- package/dist/index.js.map +1 -0
- package/dist/mfa.d.ts +126 -0
- package/dist/mfa.d.ts.map +1 -0
- package/dist/mfa.js +167 -0
- package/dist/mfa.js.map +1 -0
- package/dist/organization.d.ts +234 -0
- package/dist/organization.d.ts.map +1 -0
- package/dist/organization.js +157 -0
- package/dist/organization.js.map +1 -0
- package/dist/passkey.d.ts +59 -0
- package/dist/passkey.d.ts.map +1 -0
- package/dist/passkey.js +87 -0
- package/dist/passkey.js.map +1 -0
- package/dist/pkce.d.ts +13 -0
- package/dist/pkce.d.ts.map +1 -0
- package/dist/pkce.js +52 -0
- package/dist/pkce.js.map +1 -0
- package/dist/plugin-endpoint.d.ts +20 -0
- package/dist/plugin-endpoint.d.ts.map +1 -0
- package/dist/plugin-endpoint.js +24 -0
- package/dist/plugin-endpoint.js.map +1 -0
- package/dist/postgrest.d.ts +326 -0
- package/dist/postgrest.d.ts.map +1 -0
- package/dist/postgrest.js +625 -0
- package/dist/postgrest.js.map +1 -0
- package/dist/query.d.ts +97 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +94 -0
- package/dist/query.js.map +1 -0
- package/dist/realtime.d.ts +114 -0
- package/dist/realtime.d.ts.map +1 -0
- package/dist/realtime.js +376 -0
- package/dist/realtime.js.map +1 -0
- package/dist/session.d.ts +47 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +136 -0
- package/dist/session.js.map +1 -0
- package/dist/sso.d.ts +147 -0
- package/dist/sso.d.ts.map +1 -0
- package/dist/sso.js +35 -0
- package/dist/sso.js.map +1 -0
- package/dist/storage.d.ts +268 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +441 -0
- package/dist/storage.js.map +1 -0
- package/dist/testing.d.ts +38 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +50 -0
- package/dist/testing.js.map +1 -0
- package/dist/types.d.ts +353 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/warn.d.ts +2 -0
- package/dist/warn.d.ts.map +1 -0
- package/dist/warn.js +23 -0
- package/dist/warn.js.map +1 -0
- package/package.json +4 -2
package/dist/auth.js
ADDED
|
@@ -0,0 +1,884 @@
|
|
|
1
|
+
import { BackendError, toError } from './http.js';
|
|
2
|
+
import { normalizeUser } from './compat.js';
|
|
3
|
+
import { MfaClient } from './mfa.js';
|
|
4
|
+
import { AuthAdminClient } from './admin.js';
|
|
5
|
+
import { codeChallengeFor, generateCodeVerifier, verifierStore, withCodeChallenge } from './pkce.js';
|
|
6
|
+
import { OrganizationClient } from './organization.js';
|
|
7
|
+
import { PasskeyClient, authenticateWithPasskey } from './passkey.js';
|
|
8
|
+
import { SsoClient } from './sso.js';
|
|
9
|
+
import { HTTP_ROUTES } from '@motherbase/contracts';
|
|
10
|
+
function asIsoString(value) {
|
|
11
|
+
if (typeof value === 'string')
|
|
12
|
+
return value;
|
|
13
|
+
if (value instanceof Date)
|
|
14
|
+
return value.toISOString();
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Read a JWT's payload without verifying it. Base64url, so `-`/`_` are mapped
|
|
19
|
+
* back and the padding is restored before decoding. Returns null for anything
|
|
20
|
+
* that is not a three-part token with a JSON object payload.
|
|
21
|
+
*/
|
|
22
|
+
function decodeJwtPayload(token) {
|
|
23
|
+
const parts = token.split('.');
|
|
24
|
+
if (parts.length !== 3)
|
|
25
|
+
return null;
|
|
26
|
+
try {
|
|
27
|
+
const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
|
|
28
|
+
const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
|
|
29
|
+
// `atob` is global in every runtime this SDK supports (browsers, Node 16+,
|
|
30
|
+
// Deno, workers). Its output is latin1, so the percent-escape round trip is
|
|
31
|
+
// what turns a multi-byte claim value back into correct UTF-8.
|
|
32
|
+
const json = decodeURIComponent(Array.from(atob(padded), c => `%${c.charCodeAt(0).toString(16).padStart(2, '0')}`).join(''));
|
|
33
|
+
const parsed = JSON.parse(json);
|
|
34
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** The header the server's captcha plugin reads the widget token from. */
|
|
41
|
+
function captchaHeaders(options) {
|
|
42
|
+
return options?.captchaToken ? { 'x-captcha-response': options.captchaToken } : undefined;
|
|
43
|
+
}
|
|
44
|
+
/** Build a clean Session from the Better Auth auth payload. */
|
|
45
|
+
function toSession(payload) {
|
|
46
|
+
return { accessToken: payload.token, user: payload.user };
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Read the token an OAuth callback left in the URL fragment and return the URL
|
|
50
|
+
* with it removed, so a reload or a shared link cannot replay it.
|
|
51
|
+
*
|
|
52
|
+
* The provider callback cannot answer the SDK with a JSON body: it is a browser
|
|
53
|
+
* redirect. The backend therefore appends `#access_token=…` to the redirect it
|
|
54
|
+
* issues, the same implicit flow supabase-js reads. Exported for testing.
|
|
55
|
+
*/
|
|
56
|
+
export function readAccessTokenFromUrl(href) {
|
|
57
|
+
const hash = href.indexOf('#');
|
|
58
|
+
if (hash === -1)
|
|
59
|
+
return null;
|
|
60
|
+
const params = new URLSearchParams(href.slice(hash + 1));
|
|
61
|
+
const accessToken = params.get('access_token');
|
|
62
|
+
if (!accessToken)
|
|
63
|
+
return null;
|
|
64
|
+
params.delete('access_token');
|
|
65
|
+
params.delete('token_type');
|
|
66
|
+
const rest = params.toString();
|
|
67
|
+
return { accessToken, cleanedHref: `${href.slice(0, hash)}${rest ? `#${rest}` : ''}` };
|
|
68
|
+
}
|
|
69
|
+
const EVENT_MAP = {
|
|
70
|
+
signIn: 'SIGNED_IN',
|
|
71
|
+
signOut: 'SIGNED_OUT',
|
|
72
|
+
tokenRefreshed: 'TOKEN_REFRESHED',
|
|
73
|
+
userUpdated: 'USER_UPDATED',
|
|
74
|
+
mfaVerified: 'MFA_CHALLENGE_VERIFIED',
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Supabase-compatible auth client. Maps supabase-js method names onto the
|
|
78
|
+
* Motherbase auth endpoints and reuses the existing token/refresh/session-store
|
|
79
|
+
* machinery. Returns `{ data, error }` and never throws for expected failures.
|
|
80
|
+
*/
|
|
81
|
+
export class AuthClient {
|
|
82
|
+
constructor(http, store, options = {}) {
|
|
83
|
+
this.http = http;
|
|
84
|
+
this.store = store;
|
|
85
|
+
this.autoRefreshTimer = null;
|
|
86
|
+
this.flowType = options.flowType ?? 'implicit';
|
|
87
|
+
this.verifiers = options.verifiers ?? verifierStore('motherbase.session');
|
|
88
|
+
this.mfa = new MfaClient(http, async (payload) => {
|
|
89
|
+
await this.store.set(toSession(payload), this.store.get() ? 'mfaVerified' : 'signIn');
|
|
90
|
+
});
|
|
91
|
+
this.admin = new AuthAdminClient(http);
|
|
92
|
+
this.organization = new OrganizationClient(http);
|
|
93
|
+
this.passkey = new PasskeyClient(http);
|
|
94
|
+
this.sso = new SsoClient(http);
|
|
95
|
+
}
|
|
96
|
+
async signUp(credentials) {
|
|
97
|
+
try {
|
|
98
|
+
const payload = await this.http.request(HTTP_ROUTES.authSignUp, {
|
|
99
|
+
method: 'POST',
|
|
100
|
+
body: {
|
|
101
|
+
email: credentials.email,
|
|
102
|
+
password: credentials.password,
|
|
103
|
+
name: credentials.username ?? credentials.email,
|
|
104
|
+
...(credentials.options?.emailRedirectTo ? { callbackURL: credentials.options.emailRedirectTo } : {}),
|
|
105
|
+
},
|
|
106
|
+
headers: captchaHeaders(credentials.options),
|
|
107
|
+
anonymous: true,
|
|
108
|
+
raw: true,
|
|
109
|
+
});
|
|
110
|
+
if (!payload?.token)
|
|
111
|
+
return { data: { user: payload?.user ?? null, session: null }, error: null };
|
|
112
|
+
if (!payload.user)
|
|
113
|
+
throw new Error('Sign-up response did not include a user.');
|
|
114
|
+
const session = await this.persist({ token: payload.token, user: payload.user });
|
|
115
|
+
return { data: { user: session.user, session }, error: null };
|
|
116
|
+
}
|
|
117
|
+
catch (err) {
|
|
118
|
+
return { data: { user: null, session: null }, error: toError(err) };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
async signInWithPassword(credentials) {
|
|
122
|
+
try {
|
|
123
|
+
const payload = await this.http.request(HTTP_ROUTES.authSignIn, {
|
|
124
|
+
method: 'POST',
|
|
125
|
+
body: { email: credentials.email, password: credentials.password },
|
|
126
|
+
headers: captchaHeaders(credentials.options),
|
|
127
|
+
anonymous: true,
|
|
128
|
+
// Better Auth scopes the follow-up verification to a short-lived cookie.
|
|
129
|
+
credentials: 'include',
|
|
130
|
+
raw: true,
|
|
131
|
+
});
|
|
132
|
+
if (!payload)
|
|
133
|
+
throw new Error('Sign-in response was empty.');
|
|
134
|
+
if ('twoFactorRedirect' in payload) {
|
|
135
|
+
// A previous user's bearer must not turn the follow-up into a step-up
|
|
136
|
+
// request for that user instead of completing this sign-in.
|
|
137
|
+
if (this.store.get())
|
|
138
|
+
await this.store.set(null, 'signOut');
|
|
139
|
+
return {
|
|
140
|
+
data: {
|
|
141
|
+
user: null,
|
|
142
|
+
session: null,
|
|
143
|
+
twoFactorRequired: true,
|
|
144
|
+
twoFactorMethods: payload.twoFactorMethods ?? [],
|
|
145
|
+
},
|
|
146
|
+
error: null,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
if (!payload.token || !payload.user)
|
|
150
|
+
throw new Error('Sign-in response did not include a session.');
|
|
151
|
+
const session = await this.persist(payload);
|
|
152
|
+
return { data: { user: session.user, session }, error: null };
|
|
153
|
+
}
|
|
154
|
+
catch (err) {
|
|
155
|
+
return { data: { user: null, session: null }, error: toError(err) };
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Sign in as a new guest, supabase-js style. The project must allow
|
|
160
|
+
* anonymous sign-ins (Studio → Authentication → Sign In / Providers).
|
|
161
|
+
*
|
|
162
|
+
* The guest is a real user whose `is_anonymous` is true, and RLS sees the
|
|
163
|
+
* same flag as the `is_anonymous` claim. Make it permanent without changing
|
|
164
|
+
* its id with `updateUser({ email })` or `linkIdentity()`.
|
|
165
|
+
*/
|
|
166
|
+
async signInAnonymously(credentials = {}) {
|
|
167
|
+
try {
|
|
168
|
+
const payload = await this.http.request(HTTP_ROUTES.authSignInAnonymous, {
|
|
169
|
+
method: 'POST',
|
|
170
|
+
body: {},
|
|
171
|
+
headers: captchaHeaders(credentials.options),
|
|
172
|
+
anonymous: true,
|
|
173
|
+
raw: true,
|
|
174
|
+
});
|
|
175
|
+
await this.persist(payload);
|
|
176
|
+
const data = credentials.options?.data;
|
|
177
|
+
if (data && Object.keys(data).length > 0) {
|
|
178
|
+
// Better Auth creates the guest with no profile, so the metadata is
|
|
179
|
+
// written straight after, as the guest itself.
|
|
180
|
+
const updated = await this.updateUser({ data });
|
|
181
|
+
if (updated.error)
|
|
182
|
+
return { data: { user: null, session: null }, error: updated.error };
|
|
183
|
+
}
|
|
184
|
+
const session = this.store.get();
|
|
185
|
+
return { data: { user: session?.user ?? null, session }, error: null };
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
return { data: { user: null, session: null }, error: toError(err) };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Email the signed-in user a one-time nonce, then pass it to
|
|
193
|
+
* `updateUser({ password, nonce })`. GoTrue's "secure password change".
|
|
194
|
+
*/
|
|
195
|
+
async reauthenticate() {
|
|
196
|
+
try {
|
|
197
|
+
await this.http.request(HTTP_ROUTES.authReauthenticate, { method: 'POST', body: {}, raw: true });
|
|
198
|
+
return { data: { user: null, session: null }, error: null };
|
|
199
|
+
}
|
|
200
|
+
catch (err) {
|
|
201
|
+
return { data: { user: null, session: null }, error: toError(err) };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Request a password-reset OTP by email. Always resolves successfully
|
|
206
|
+
* (whether or not the email is registered) to avoid leaking account
|
|
207
|
+
* existence; check `error` only for transport/server failures.
|
|
208
|
+
*/
|
|
209
|
+
async resetPasswordForEmail(email, options) {
|
|
210
|
+
try {
|
|
211
|
+
await this.http.request(HTTP_ROUTES.authRequestPasswordReset, {
|
|
212
|
+
method: 'POST',
|
|
213
|
+
body: { email },
|
|
214
|
+
headers: captchaHeaders(options),
|
|
215
|
+
anonymous: true,
|
|
216
|
+
raw: true,
|
|
217
|
+
});
|
|
218
|
+
return { error: null };
|
|
219
|
+
}
|
|
220
|
+
catch (err) {
|
|
221
|
+
return { error: toError(err) };
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/** Complete a password reset using the OTP sent to the user's email. */
|
|
225
|
+
async resetPassword(args) {
|
|
226
|
+
try {
|
|
227
|
+
await this.http.request(HTTP_ROUTES.authResetPassword, {
|
|
228
|
+
method: 'POST',
|
|
229
|
+
body: { email: args.email, otp: args.otp, password: args.password },
|
|
230
|
+
anonymous: true,
|
|
231
|
+
raw: true,
|
|
232
|
+
});
|
|
233
|
+
return { error: null };
|
|
234
|
+
}
|
|
235
|
+
catch (err) {
|
|
236
|
+
return { error: toError(err) };
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Send a one-time sign-in code, by email or by SMS. Pair with `verifyOtp` to
|
|
241
|
+
* complete the sign-in.
|
|
242
|
+
*
|
|
243
|
+
* `{ phone }` routes to the phone-number plugin, which the project has to
|
|
244
|
+
* have enabled with an SMS sender configured; without one the call resolves
|
|
245
|
+
* with the backend's error rather than pretending a code was sent.
|
|
246
|
+
*/
|
|
247
|
+
async signInWithOtp(credentials) {
|
|
248
|
+
if (!credentials.email && !credentials.phone) {
|
|
249
|
+
return { data: {}, error: { message: 'signInWithOtp needs either `email` or `phone`.' } };
|
|
250
|
+
}
|
|
251
|
+
try {
|
|
252
|
+
if (credentials.phone) {
|
|
253
|
+
await this.http.request(HTTP_ROUTES.authSendPhoneOtp, {
|
|
254
|
+
method: 'POST',
|
|
255
|
+
body: { phoneNumber: credentials.phone },
|
|
256
|
+
headers: captchaHeaders(credentials.options),
|
|
257
|
+
anonymous: true,
|
|
258
|
+
raw: true,
|
|
259
|
+
});
|
|
260
|
+
return { data: {}, error: null };
|
|
261
|
+
}
|
|
262
|
+
await this.http.request(HTTP_ROUTES.authSendOtp, {
|
|
263
|
+
method: 'POST',
|
|
264
|
+
body: { email: credentials.email, type: 'sign-in' },
|
|
265
|
+
headers: captchaHeaders(credentials.options),
|
|
266
|
+
anonymous: true,
|
|
267
|
+
raw: true,
|
|
268
|
+
});
|
|
269
|
+
return { data: {}, error: null };
|
|
270
|
+
}
|
|
271
|
+
catch (err) {
|
|
272
|
+
return { data: {}, error: toError(err) };
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Send the one-time code again, supabase-js style.
|
|
277
|
+
*
|
|
278
|
+
* supabase-js names the flows `signup` (confirm a new address), `email_change`
|
|
279
|
+
* and `recovery`; Better Auth names them `email-verification` and
|
|
280
|
+
* `forget-password`. The mapping lives here so ported code keeps working.
|
|
281
|
+
* `sms` and `phone_change` re-send an SMS code through the phone-number flow.
|
|
282
|
+
*/
|
|
283
|
+
async resend(params) {
|
|
284
|
+
if (params.type === 'sms' || params.type === 'phone_change') {
|
|
285
|
+
if (!params.phone)
|
|
286
|
+
return { data: {}, error: { message: '`phone` is required.' } };
|
|
287
|
+
return this.signInWithOtp({ phone: params.phone });
|
|
288
|
+
}
|
|
289
|
+
const OTP_TYPE = {
|
|
290
|
+
signup: 'email-verification',
|
|
291
|
+
email_change: 'email-verification',
|
|
292
|
+
recovery: 'forget-password',
|
|
293
|
+
};
|
|
294
|
+
const type = OTP_TYPE[params.type];
|
|
295
|
+
if (!type) {
|
|
296
|
+
return { data: {}, error: { message: `resend({ type: '${params.type}' }) is not supported.` } };
|
|
297
|
+
}
|
|
298
|
+
if (!params.email) {
|
|
299
|
+
return { data: {}, error: { message: '`email` is required.' } };
|
|
300
|
+
}
|
|
301
|
+
try {
|
|
302
|
+
await this.http.request(HTTP_ROUTES.authSendOtp, {
|
|
303
|
+
method: 'POST',
|
|
304
|
+
body: { email: params.email, type },
|
|
305
|
+
anonymous: true,
|
|
306
|
+
raw: true,
|
|
307
|
+
});
|
|
308
|
+
return { data: {}, error: null };
|
|
309
|
+
}
|
|
310
|
+
catch (err) {
|
|
311
|
+
return { data: {}, error: toError(err) };
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Complete a `signInWithOtp` sign-in with the code that was sent.
|
|
316
|
+
*
|
|
317
|
+
* The channel follows the identifier, as in supabase-js: `{ phone }` verifies
|
|
318
|
+
* an SMS code, `{ email }` an email one. `type` is accepted for signature
|
|
319
|
+
* parity and only disambiguates when both are somehow present.
|
|
320
|
+
*/
|
|
321
|
+
async verifyOtp(params) {
|
|
322
|
+
if (!params.email && !params.phone) {
|
|
323
|
+
return { data: { user: null, session: null }, error: { message: 'verifyOtp needs either `email` or `phone`.' } };
|
|
324
|
+
}
|
|
325
|
+
try {
|
|
326
|
+
const bySms = Boolean(params.phone) && params.type !== 'email';
|
|
327
|
+
const payload = await this.http.request(bySms ? HTTP_ROUTES.authVerifyPhoneOtp : HTTP_ROUTES.authSignInEmailOtp, {
|
|
328
|
+
method: 'POST',
|
|
329
|
+
body: bySms
|
|
330
|
+
? { phoneNumber: params.phone, code: params.token }
|
|
331
|
+
: { email: params.email, otp: params.token },
|
|
332
|
+
anonymous: true,
|
|
333
|
+
raw: true,
|
|
334
|
+
});
|
|
335
|
+
if (!payload?.token) {
|
|
336
|
+
return { data: { user: null, session: null }, error: { message: 'The code did not produce a session.' } };
|
|
337
|
+
}
|
|
338
|
+
const session = await this.persist(payload);
|
|
339
|
+
return { data: { user: session.user, session }, error: null };
|
|
340
|
+
}
|
|
341
|
+
catch (err) {
|
|
342
|
+
return { data: { user: null, session: null }, error: toError(err) };
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Start an OAuth sign-in with a configured social provider. Resolves with the
|
|
347
|
+
* provider's authorize URL and, in a browser, redirects to it immediately
|
|
348
|
+
* unless `options.skipBrowserRedirect` is set.
|
|
349
|
+
*/
|
|
350
|
+
async signInWithOAuth(credentials) {
|
|
351
|
+
const redirectTo = await this.redirectForFlow(credentials.options?.redirectTo);
|
|
352
|
+
if (redirectTo instanceof Error)
|
|
353
|
+
return { data: { provider: credentials.provider, url: null }, error: { message: redirectTo.message } };
|
|
354
|
+
credentials = { ...credentials, options: { ...credentials.options, redirectTo } };
|
|
355
|
+
// In a browser, hand the whole handshake to a top-level navigation. Starting
|
|
356
|
+
// it with a fetch makes the OAuth state cookie a cross-site write, which
|
|
357
|
+
// Safari and Firefox drop outright and Chrome drops in incognito, and the
|
|
358
|
+
// callback then fails with state_mismatch. Navigating to the backend's own
|
|
359
|
+
// origin makes that cookie first-party, so a plain SameSite=Lax cookie
|
|
360
|
+
// survives everywhere. The backend redirects on from there.
|
|
361
|
+
if (typeof window !== 'undefined' && !credentials.options?.skipBrowserRedirect) {
|
|
362
|
+
const params = new URLSearchParams();
|
|
363
|
+
if (credentials.options?.redirectTo)
|
|
364
|
+
params.set('callbackURL', credentials.options.redirectTo);
|
|
365
|
+
const query = params.toString();
|
|
366
|
+
const url = this.http.url(`${HTTP_ROUTES.authSignInSocial}/${encodeURIComponent(credentials.provider)}${query ? `?${query}` : ''}`);
|
|
367
|
+
window.location.href = url;
|
|
368
|
+
return { data: { provider: credentials.provider, url }, error: null };
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
const payload = await this.http.request(HTTP_ROUTES.authSignInSocial, {
|
|
372
|
+
method: 'POST',
|
|
373
|
+
body: {
|
|
374
|
+
provider: credentials.provider,
|
|
375
|
+
callbackURL: credentials.options?.redirectTo,
|
|
376
|
+
scopes: credentials.options?.scopes ? credentials.options.scopes.split(' ') : undefined,
|
|
377
|
+
disableRedirect: true,
|
|
378
|
+
},
|
|
379
|
+
anonymous: true,
|
|
380
|
+
raw: true,
|
|
381
|
+
// The server answers with a signed OAuth state cookie it checks again on
|
|
382
|
+
// the provider callback. Without 'include' the browser drops that cookie
|
|
383
|
+
// on a cross-origin call and every callback fails with state_mismatch.
|
|
384
|
+
credentials: 'include',
|
|
385
|
+
});
|
|
386
|
+
const url = payload?.url ?? null;
|
|
387
|
+
if (url && !credentials.options?.skipBrowserRedirect && typeof window !== 'undefined') {
|
|
388
|
+
window.location.href = url;
|
|
389
|
+
}
|
|
390
|
+
return { data: { provider: credentials.provider, url }, error: null };
|
|
391
|
+
}
|
|
392
|
+
catch (err) {
|
|
393
|
+
return { data: { provider: credentials.provider, url: null }, error: toError(err) };
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Sign in with a passkey saved on this device or a synced one. Opens the
|
|
398
|
+
* browser's passkey prompt; dismissing it resolves with an error, not a throw.
|
|
399
|
+
* Needs Auth · Passkey on and a browser (see `auth.passkey`).
|
|
400
|
+
*/
|
|
401
|
+
async signInWithPasskey() {
|
|
402
|
+
const result = await authenticateWithPasskey(this.http);
|
|
403
|
+
if (result.error)
|
|
404
|
+
return { data: { user: null, session: null }, error: result.error };
|
|
405
|
+
const session = await this.persist(result.data);
|
|
406
|
+
return { data: { user: session.user, session }, error: null };
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Start an enterprise SSO sign-in. Identify the provider by the user's email
|
|
410
|
+
* domain, by an explicit `domain`, or by `providerId` when you already know
|
|
411
|
+
* which one to use.
|
|
412
|
+
*
|
|
413
|
+
* Resolves with the identity provider's URL and, in a browser, redirects to it
|
|
414
|
+
* unless `options.skipBrowserRedirect` is set. The project must have the SSO
|
|
415
|
+
* plugin enabled and at least one provider registered (Studio →
|
|
416
|
+
* Authentication → Organizations & SSO).
|
|
417
|
+
*/
|
|
418
|
+
async signInWithSSO(params) {
|
|
419
|
+
if (!params.domain && !params.email && !params.providerId && !params.organizationSlug) {
|
|
420
|
+
return { data: { url: null }, error: { message: 'signInWithSSO needs a domain, email, providerId or organizationSlug' } };
|
|
421
|
+
}
|
|
422
|
+
const redirectTo = await this.redirectForFlow(params.options?.redirectTo);
|
|
423
|
+
if (redirectTo instanceof Error)
|
|
424
|
+
return { data: { url: null }, error: { message: redirectTo.message } };
|
|
425
|
+
params = { ...params, options: { ...params.options, redirectTo } };
|
|
426
|
+
try {
|
|
427
|
+
const payload = await this.http.request('/api/auth/sign-in/sso', {
|
|
428
|
+
method: 'POST',
|
|
429
|
+
body: {
|
|
430
|
+
...(params.domain ? { domain: params.domain } : {}),
|
|
431
|
+
...(params.email ? { email: params.email } : {}),
|
|
432
|
+
...(params.providerId ? { providerId: params.providerId } : {}),
|
|
433
|
+
...(params.organizationSlug ? { organizationSlug: params.organizationSlug } : {}),
|
|
434
|
+
callbackURL: params.options?.redirectTo,
|
|
435
|
+
},
|
|
436
|
+
anonymous: true,
|
|
437
|
+
raw: true,
|
|
438
|
+
credentials: 'include', // Same OAuth state cookie as signInWithOAuth.
|
|
439
|
+
});
|
|
440
|
+
const url = payload?.url ?? null;
|
|
441
|
+
if (url && !params.options?.skipBrowserRedirect && typeof window !== 'undefined') {
|
|
442
|
+
window.location.href = url;
|
|
443
|
+
}
|
|
444
|
+
return { data: { url }, error: null };
|
|
445
|
+
}
|
|
446
|
+
catch (err) {
|
|
447
|
+
return { data: { url: null }, error: toError(err) };
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Update the signed-in user's profile fields and/or password. Password
|
|
452
|
+
* changes require `currentPassword` (a Better Auth requirement. There is no
|
|
453
|
+
* blind password overwrite from an authenticated session).
|
|
454
|
+
*/
|
|
455
|
+
async updateUser(attributes) {
|
|
456
|
+
try {
|
|
457
|
+
if (attributes.data && Object.keys(attributes.data).length > 0) {
|
|
458
|
+
await this.http.request(HTTP_ROUTES.authUpdateUser, { method: 'POST', body: attributes.data, raw: true });
|
|
459
|
+
}
|
|
460
|
+
if (attributes.password && attributes.currentPassword) {
|
|
461
|
+
await this.http.request(HTTP_ROUTES.authChangePassword, {
|
|
462
|
+
method: 'POST',
|
|
463
|
+
body: { newPassword: attributes.password, currentPassword: attributes.currentPassword },
|
|
464
|
+
raw: true,
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
else if (attributes.email || attributes.password) {
|
|
468
|
+
// Email (a guest's upgrade) and a password set by nonce, or a first
|
|
469
|
+
// password, go through GoTrue's `PUT /user` equivalent.
|
|
470
|
+
await this.http.request(HTTP_ROUTES.authUpdateUserCredentials, {
|
|
471
|
+
method: 'POST',
|
|
472
|
+
body: {
|
|
473
|
+
...(attributes.email ? { email: attributes.email } : {}),
|
|
474
|
+
...(attributes.password ? { password: attributes.password } : {}),
|
|
475
|
+
...(attributes.nonce ? { nonce: attributes.nonce } : {}),
|
|
476
|
+
},
|
|
477
|
+
raw: true,
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
const result = await this.getUser();
|
|
481
|
+
// supabase-js emits USER_UPDATED here, and apps re-read the profile off
|
|
482
|
+
// that event rather than off the return value. Refresh the stored session
|
|
483
|
+
// so the user the listener receives is the updated one.
|
|
484
|
+
const current = this.store.get();
|
|
485
|
+
if (result.data?.user && current) {
|
|
486
|
+
await this.store.set({ ...current, user: result.data.user }, 'userUpdated');
|
|
487
|
+
}
|
|
488
|
+
return result;
|
|
489
|
+
}
|
|
490
|
+
catch (err) {
|
|
491
|
+
return { data: { user: null }, error: toError(err) };
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Permanently delete the signed-in user's account. Not part of the
|
|
496
|
+
* supabase-js client surface (there it's admin-only). Kept here because
|
|
497
|
+
* self-service account deletion is a real product need. Requires the
|
|
498
|
+
* backend's `delete-user` flow to be enabled; clears the local session on
|
|
499
|
+
* success.
|
|
500
|
+
*/
|
|
501
|
+
async deleteUser(attributes = {}) {
|
|
502
|
+
try {
|
|
503
|
+
await this.http.request(HTTP_ROUTES.authDeleteUser, {
|
|
504
|
+
method: 'POST',
|
|
505
|
+
body: attributes,
|
|
506
|
+
raw: true,
|
|
507
|
+
});
|
|
508
|
+
await this.store.set(null, 'signOut');
|
|
509
|
+
return { error: null };
|
|
510
|
+
}
|
|
511
|
+
catch (err) {
|
|
512
|
+
return { error: toError(err) };
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Adopt an externally-obtained access token as the current session (e.g. one
|
|
517
|
+
* captured from an OAuth redirect). Validates it against the server before
|
|
518
|
+
* persisting. `refresh_token` is accepted for supabase-js signature parity
|
|
519
|
+
* and unused: Better Auth bearer sessions have none.
|
|
520
|
+
*/
|
|
521
|
+
async setSession(currentSession) {
|
|
522
|
+
await this.store.set({ accessToken: currentSession.access_token, user: { id: '', email: '' } }, 'signIn');
|
|
523
|
+
try {
|
|
524
|
+
const payload = await this.http.request(HTTP_ROUTES.authSession, { raw: true });
|
|
525
|
+
if (!payload?.user) {
|
|
526
|
+
await this.store.set(null, 'signOut');
|
|
527
|
+
return { data: { user: null, session: null }, error: { message: 'Invalid session' } };
|
|
528
|
+
}
|
|
529
|
+
const session = { accessToken: currentSession.access_token, user: payload.user };
|
|
530
|
+
await this.store.set(session, 'signIn');
|
|
531
|
+
return { data: { user: session.user, session }, error: null };
|
|
532
|
+
}
|
|
533
|
+
catch (err) {
|
|
534
|
+
await this.store.set(null, 'signOut');
|
|
535
|
+
return { data: { user: null, session: null }, error: toError(err) };
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
async signOut() {
|
|
539
|
+
try {
|
|
540
|
+
await this.http.request(HTTP_ROUTES.authSignOut, { method: 'POST', raw: true });
|
|
541
|
+
}
|
|
542
|
+
catch {
|
|
543
|
+
// best-effort; clear locally regardless
|
|
544
|
+
}
|
|
545
|
+
await this.store.set(null, 'signOut');
|
|
546
|
+
return { error: null };
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Finish an OAuth / SSO sign-in after the provider redirected back.
|
|
550
|
+
*
|
|
551
|
+
* `signInWithOAuth` only starts the flow; the session is created during the
|
|
552
|
+
* redirect the browser makes to the backend callback, so the SDK has to pick
|
|
553
|
+
* it up from the URL the browser landed on. Call this once on the page you
|
|
554
|
+
* pointed `redirectTo` at (or on app start, which is where supabase-js does
|
|
555
|
+
* the equivalent). Without it the user is signed in on the backend and signed
|
|
556
|
+
* out in your app.
|
|
557
|
+
*
|
|
558
|
+
* Resolves with a null session and no error when there is nothing to read, so
|
|
559
|
+
* it is safe to call on every page load.
|
|
560
|
+
*/
|
|
561
|
+
async getSessionFromUrl(href) {
|
|
562
|
+
const url = href ?? (typeof window !== 'undefined' ? window.location.href : undefined);
|
|
563
|
+
const found = url ? readAccessTokenFromUrl(url) : null;
|
|
564
|
+
if (!found)
|
|
565
|
+
return { data: { user: null, session: null }, error: null };
|
|
566
|
+
// Strip the token before the network call: a failed lookup must not leave a
|
|
567
|
+
// usable token sitting in the address bar or in the back/forward history.
|
|
568
|
+
if (!href && typeof window !== 'undefined') {
|
|
569
|
+
window.history?.replaceState?.(window.history.state, '', found.cleanedHref);
|
|
570
|
+
}
|
|
571
|
+
try {
|
|
572
|
+
// Resolve the user with the token explicitly rather than storing it first:
|
|
573
|
+
// a rejected token must not emit a SIGNED_IN event carrying a null user.
|
|
574
|
+
const payload = await this.http.request(HTTP_ROUTES.authSession, {
|
|
575
|
+
raw: true,
|
|
576
|
+
anonymous: true,
|
|
577
|
+
headers: { Authorization: `Bearer ${found.accessToken}` },
|
|
578
|
+
});
|
|
579
|
+
if (!payload?.user) {
|
|
580
|
+
return { data: { user: null, session: null }, error: { message: 'OAuth session is no longer valid' } };
|
|
581
|
+
}
|
|
582
|
+
const session = await this.persist({ token: found.accessToken, user: payload.user });
|
|
583
|
+
return { data: { user: session.user, session }, error: null };
|
|
584
|
+
}
|
|
585
|
+
catch (err) {
|
|
586
|
+
return { data: { user: null, session: null }, error: toError(err) };
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Finish a PKCE sign-in: trade the `?code=` the provider redirect came back
|
|
591
|
+
* with for the session. Needs the verifier `signInWithOAuth` stored, so it
|
|
592
|
+
* works once, in the browser that started the flow.
|
|
593
|
+
*/
|
|
594
|
+
async exchangeCodeForSession(authCode) {
|
|
595
|
+
const verifier = await this.verifiers.get();
|
|
596
|
+
if (!verifier) {
|
|
597
|
+
return { data: { user: null, session: null }, error: { message: 'No PKCE code verifier found: start the flow with flowType: "pkce" in this browser.' } };
|
|
598
|
+
}
|
|
599
|
+
try {
|
|
600
|
+
const payload = await this.http.request(HTTP_ROUTES.authExchangeCode, {
|
|
601
|
+
method: 'POST',
|
|
602
|
+
body: { auth_code: authCode, code_verifier: verifier },
|
|
603
|
+
anonymous: true,
|
|
604
|
+
raw: true,
|
|
605
|
+
});
|
|
606
|
+
await this.verifiers.clear();
|
|
607
|
+
const session = await this.persist(payload);
|
|
608
|
+
return { data: { user: session.user, session }, error: null };
|
|
609
|
+
}
|
|
610
|
+
catch (err) {
|
|
611
|
+
return { data: { user: null, session: null }, error: toError(err) };
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* The redirect a flow should use. Implicit: as given. PKCE: with a fresh
|
|
616
|
+
* challenge on it, the verifier stored for `exchangeCodeForSession`; the
|
|
617
|
+
* challenge rides on the redirect URL, so PKCE needs one, and in a browser
|
|
618
|
+
* the current page stands in when none is given.
|
|
619
|
+
*/
|
|
620
|
+
async redirectForFlow(redirectTo) {
|
|
621
|
+
if (this.flowType !== 'pkce')
|
|
622
|
+
return redirectTo;
|
|
623
|
+
const target = redirectTo ?? (typeof window !== 'undefined' ? window.location.href.split('#')[0] : undefined);
|
|
624
|
+
if (!target)
|
|
625
|
+
return new Error('flowType "pkce" needs options.redirectTo outside a browser.');
|
|
626
|
+
const verifier = generateCodeVerifier();
|
|
627
|
+
await this.verifiers.set(verifier);
|
|
628
|
+
return withCodeChallenge(target, await codeChallengeFor(verifier));
|
|
629
|
+
}
|
|
630
|
+
/** Fetch the current user from Better Auth (requires a valid session). */
|
|
631
|
+
async getUser() {
|
|
632
|
+
try {
|
|
633
|
+
const payload = await this.http.request(HTTP_ROUTES.authSession, { raw: true });
|
|
634
|
+
return { data: { user: normalizeUser(payload?.user) }, error: null };
|
|
635
|
+
}
|
|
636
|
+
catch (err) {
|
|
637
|
+
return { data: { user: null }, error: toError(err) };
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* NEVER USE FOR AN AUTHORIZATION DECISION. Use {@link getUser} instead.
|
|
642
|
+
*
|
|
643
|
+
* The locally-held session, if any (no network call). It is whatever the
|
|
644
|
+
* caller's cookie or storage said, parsed: unsigned JSON the browser sent,
|
|
645
|
+
* which anyone can set by hand. `session.user.id`, `.email` and `.role` are
|
|
646
|
+
* therefore attacker-controlled, and an admin allowlist checked against
|
|
647
|
+
* them is checked against nothing.
|
|
648
|
+
*
|
|
649
|
+
* Reads and writes through `from()` are unaffected: they carry the access
|
|
650
|
+
* token to the backend, which verifies it under RLS. It is the decisions
|
|
651
|
+
* your own app takes from `session.user` that are forgeable.
|
|
652
|
+
*
|
|
653
|
+
* `getUser()` costs one round trip and returns the user the backend
|
|
654
|
+
* confirms, in the same `{ data, error }` shape. Prefer it everywhere but a
|
|
655
|
+
* cosmetic "am I probably signed in" check.
|
|
656
|
+
*/
|
|
657
|
+
async getSession() {
|
|
658
|
+
await this.store.hydrate();
|
|
659
|
+
return { data: { session: this.store.get() }, error: null };
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Revalidate the current session against the server. Better Auth bearer
|
|
663
|
+
* sessions have no refresh token: if the session is still valid the user is
|
|
664
|
+
* refreshed; otherwise the local session is cleared.
|
|
665
|
+
*/
|
|
666
|
+
async refreshSession() {
|
|
667
|
+
await this.store.hydrate();
|
|
668
|
+
const current = this.store.get();
|
|
669
|
+
if (!current?.accessToken) {
|
|
670
|
+
return { data: { user: null, session: null }, error: { message: 'Auth session missing!' } };
|
|
671
|
+
}
|
|
672
|
+
try {
|
|
673
|
+
const payload = await this.http.request(HTTP_ROUTES.authSession, { raw: true, _retry: true });
|
|
674
|
+
if (!payload?.user) {
|
|
675
|
+
await this.store.set(null, 'signOut');
|
|
676
|
+
return { data: { user: null, session: null }, error: { message: 'Session expired' } };
|
|
677
|
+
}
|
|
678
|
+
const session = { accessToken: current.accessToken, user: payload.user };
|
|
679
|
+
await this.store.set(session, 'tokenRefreshed');
|
|
680
|
+
return { data: { user: session.user, session }, error: null };
|
|
681
|
+
}
|
|
682
|
+
catch (err) {
|
|
683
|
+
// Only a rejected token clears the session. A network failure or a 5xx
|
|
684
|
+
// must leave it intact: middleware runs this on every navigation, so
|
|
685
|
+
// one backend hiccup would otherwise sign the user out.
|
|
686
|
+
const status = err instanceof BackendError ? err.httpStatus : 0;
|
|
687
|
+
if (status === 401 || status === 403)
|
|
688
|
+
await this.store.set(null, 'signOut');
|
|
689
|
+
return { data: { user: null, session: null }, error: toError(err) };
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Subscribe to auth changes, supabase-js style.
|
|
694
|
+
*
|
|
695
|
+
* The callback fires once with `INITIAL_SESSION` as soon as the stored
|
|
696
|
+
* session has been read, before any later event. That first call is not a
|
|
697
|
+
* nicety: the standard Supabase bootstrap is
|
|
698
|
+
* `if (event === 'INITIAL_SESSION') setLoading(false)`, and without it the
|
|
699
|
+
* app renders its loading state forever for a signed-out visitor, who never
|
|
700
|
+
* produces any other event.
|
|
701
|
+
*
|
|
702
|
+
* It is delivered asynchronously (after hydration), so unsubscribing
|
|
703
|
+
* synchronously suppresses it, exactly as in supabase-js.
|
|
704
|
+
*/
|
|
705
|
+
/**
|
|
706
|
+
* The providers linked to the signed-in user, in the supabase-js identity
|
|
707
|
+
* shape. Backed by Better Auth's `list-accounts`, which is why `email` shows
|
|
708
|
+
* up as an identity for a password account: it is a real linked credential,
|
|
709
|
+
* exactly as in Supabase.
|
|
710
|
+
*/
|
|
711
|
+
async getUserIdentities() {
|
|
712
|
+
try {
|
|
713
|
+
const accounts = await this.http.request(HTTP_ROUTES.authListAccounts, { raw: true });
|
|
714
|
+
const userId = this.store.get()?.user?.id ?? '';
|
|
715
|
+
const identities = (accounts ?? []).map(account => ({
|
|
716
|
+
id: account.accountId ?? account.id,
|
|
717
|
+
identity_id: account.id,
|
|
718
|
+
user_id: userId,
|
|
719
|
+
provider: account.providerId,
|
|
720
|
+
identity_data: { sub: account.accountId, ...(account.scopes ? { scopes: account.scopes } : {}) },
|
|
721
|
+
created_at: asIsoString(account.createdAt),
|
|
722
|
+
updated_at: asIsoString(account.updatedAt),
|
|
723
|
+
last_sign_in_at: asIsoString(account.updatedAt),
|
|
724
|
+
}));
|
|
725
|
+
return { data: { identities }, error: null };
|
|
726
|
+
}
|
|
727
|
+
catch (err) {
|
|
728
|
+
return { data: null, error: toError(err) };
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Link another provider to the signed-in user. Like `signInWithOAuth`, this
|
|
733
|
+
* only starts the flow: the browser is sent to the provider and comes back
|
|
734
|
+
* through the callback.
|
|
735
|
+
*/
|
|
736
|
+
async linkIdentity(credentials) {
|
|
737
|
+
try {
|
|
738
|
+
const payload = await this.http.request(HTTP_ROUTES.authLinkSocial, {
|
|
739
|
+
method: 'POST',
|
|
740
|
+
body: {
|
|
741
|
+
provider: credentials.provider,
|
|
742
|
+
callbackURL: credentials.options?.redirectTo,
|
|
743
|
+
scopes: credentials.options?.scopes?.split(/\s+/).filter(Boolean),
|
|
744
|
+
},
|
|
745
|
+
credentials: 'include',
|
|
746
|
+
raw: true,
|
|
747
|
+
});
|
|
748
|
+
const url = payload?.url ?? null;
|
|
749
|
+
if (url && !credentials.options?.skipBrowserRedirect && typeof window !== 'undefined') {
|
|
750
|
+
window.location.assign(url);
|
|
751
|
+
}
|
|
752
|
+
return { data: { provider: credentials.provider, url }, error: null };
|
|
753
|
+
}
|
|
754
|
+
catch (err) {
|
|
755
|
+
return { data: { provider: credentials.provider, url: null }, error: toError(err) };
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
/** Unlink a provider from the signed-in user. */
|
|
759
|
+
async unlinkIdentity(identity) {
|
|
760
|
+
try {
|
|
761
|
+
await this.http.request(HTTP_ROUTES.authUnlinkAccount, {
|
|
762
|
+
method: 'POST',
|
|
763
|
+
body: { providerId: identity.provider, accountId: identity.id },
|
|
764
|
+
raw: true,
|
|
765
|
+
});
|
|
766
|
+
return { data: {}, error: null };
|
|
767
|
+
}
|
|
768
|
+
catch (err) {
|
|
769
|
+
return { data: null, error: toError(err) };
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* Native mobile sign-in with a provider id token (Sign in with Apple, Google
|
|
774
|
+
* One Tap), routed to Better Auth's social sign-in with an `idToken`.
|
|
775
|
+
* The provider must be configured on the backend.
|
|
776
|
+
*/
|
|
777
|
+
async signInWithIdToken(params) {
|
|
778
|
+
try {
|
|
779
|
+
const payload = await this.http.request(HTTP_ROUTES.authSignInSocial, {
|
|
780
|
+
method: 'POST',
|
|
781
|
+
body: {
|
|
782
|
+
provider: params.provider,
|
|
783
|
+
idToken: {
|
|
784
|
+
token: params.token,
|
|
785
|
+
...(params.access_token ? { accessToken: params.access_token } : {}),
|
|
786
|
+
...(params.nonce ? { nonce: params.nonce } : {}),
|
|
787
|
+
},
|
|
788
|
+
},
|
|
789
|
+
anonymous: true,
|
|
790
|
+
raw: true,
|
|
791
|
+
});
|
|
792
|
+
if (!payload?.token) {
|
|
793
|
+
return { data: { user: null, session: null }, error: { message: 'The provider did not return a session.' } };
|
|
794
|
+
}
|
|
795
|
+
const session = await this.persist(payload);
|
|
796
|
+
return { data: { user: session.user, session }, error: null };
|
|
797
|
+
}
|
|
798
|
+
catch (err) {
|
|
799
|
+
return { data: { user: null, session: null }, error: toError(err) };
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Claims for the current session, as a JWT payload.
|
|
804
|
+
*
|
|
805
|
+
* supabase-js reads them out of the access token, which is itself a JWT.
|
|
806
|
+
* A Better Auth session token is an opaque bearer, so this asks the server's
|
|
807
|
+
* jwt plugin to mint one and decodes it. The decode is NOT a verification:
|
|
808
|
+
* the token came from the authenticated endpoint over TLS, and a client
|
|
809
|
+
* verifying a token it just asked for proves nothing. Verify server side,
|
|
810
|
+
* against `/api/auth/jwks`.
|
|
811
|
+
*/
|
|
812
|
+
async getClaims() {
|
|
813
|
+
try {
|
|
814
|
+
const payload = await this.http.request(HTTP_ROUTES.authToken, { raw: true });
|
|
815
|
+
const token = payload?.token;
|
|
816
|
+
const claims = token ? decodeJwtPayload(token) : null;
|
|
817
|
+
if (!token || !claims) {
|
|
818
|
+
return { data: null, error: { message: 'No JWT is available for this session.' } };
|
|
819
|
+
}
|
|
820
|
+
return { data: { claims, token }, error: null };
|
|
821
|
+
}
|
|
822
|
+
catch (err) {
|
|
823
|
+
return { data: null, error: toError(err) };
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Revalidate the session on a timer, the way supabase-js does while the tab
|
|
828
|
+
* is focused. Motherbase refreshes on a 401 already, so this is opt-in: it
|
|
829
|
+
* exists so a ported app that calls it keeps working, and so a long-lived
|
|
830
|
+
* screen notices a revoked session without waiting for its next request.
|
|
831
|
+
*/
|
|
832
|
+
startAutoRefresh(intervalMs = 60000) {
|
|
833
|
+
this.stopAutoRefresh();
|
|
834
|
+
this.autoRefreshTimer = setInterval(() => {
|
|
835
|
+
if (this.store.get())
|
|
836
|
+
void this.refreshSession();
|
|
837
|
+
}, intervalMs);
|
|
838
|
+
// Node keeps the process alive for a pending timer; a background refresh
|
|
839
|
+
// must never be the reason a script does not exit.
|
|
840
|
+
this.autoRefreshTimer.unref?.();
|
|
841
|
+
}
|
|
842
|
+
/** Stop the timer started by `startAutoRefresh`. Safe to call when none runs. */
|
|
843
|
+
stopAutoRefresh() {
|
|
844
|
+
if (this.autoRefreshTimer !== null) {
|
|
845
|
+
clearInterval(this.autoRefreshTimer);
|
|
846
|
+
this.autoRefreshTimer = null;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
onAuthStateChange(callback) {
|
|
850
|
+
let active = true;
|
|
851
|
+
const unsubscribeStore = this.store.subscribe((event, session) => {
|
|
852
|
+
if (active)
|
|
853
|
+
callback(EVENT_MAP[event], session);
|
|
854
|
+
});
|
|
855
|
+
void this.store.hydrate().then(session => {
|
|
856
|
+
if (active)
|
|
857
|
+
callback('INITIAL_SESSION', session);
|
|
858
|
+
});
|
|
859
|
+
return {
|
|
860
|
+
data: {
|
|
861
|
+
subscription: {
|
|
862
|
+
unsubscribe: () => {
|
|
863
|
+
active = false;
|
|
864
|
+
unsubscribeStore();
|
|
865
|
+
},
|
|
866
|
+
},
|
|
867
|
+
},
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* Internal: refresh used by the HttpClient's 401 path. Returns true on success.
|
|
872
|
+
* Not part of the public Supabase surface.
|
|
873
|
+
*/
|
|
874
|
+
async _refresh() {
|
|
875
|
+
const result = await this.refreshSession();
|
|
876
|
+
return result.error === null;
|
|
877
|
+
}
|
|
878
|
+
async persist(payload) {
|
|
879
|
+
const session = toSession(payload);
|
|
880
|
+
await this.store.set(session, 'signIn');
|
|
881
|
+
return session;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
//# sourceMappingURL=auth.js.map
|