@motherbase/client 1.5.2 → 2.2.0

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/dist/auth.js CHANGED
@@ -1,57 +1,54 @@
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';
1
+ import { createAuthClient as createBetterAuthClient } from 'better-auth/client';
2
+ import { anonymousClient, emailOTPClient, genericOAuthClient, jwtClient, magicLinkClient, organizationClient, phoneNumberClient, twoFactorClient, } from 'better-auth/client/plugins';
3
+ import { passkeyClient } from '@better-auth/passkey/client';
4
+ import { ssoClient } from '@better-auth/sso/client';
5
+ import { apiKeyClient } from '@better-auth/api-key/client';
9
6
  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
- }
7
+ import { AuthAdminClient } from './admin.js';
8
+ import { normalizeUser } from './compat.js';
9
+ import { codeChallengeFor, generateCodeVerifier, withCodeChallenge } from './pkce.js';
10
+ const EVENT_MAP = {
11
+ signIn: 'SIGNED_IN',
12
+ signOut: 'SIGNED_OUT',
13
+ tokenRefreshed: 'TOKEN_REFRESHED',
14
+ userUpdated: 'USER_UPDATED',
15
+ mfaVerified: 'MFA_CHALLENGE_VERIFIED',
16
+ };
17
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.
18
+ * Endpoints whose next step needs a cookie set on the response: the OAuth
19
+ * state, the WebAuthn challenge, or the pending second factor a password
20
+ * sign-in leaves for `twoFactor.verify*`. Cross-origin, fetch only keeps and
21
+ * resends a cookie with `credentials: 'include'`. Everything else stays
22
+ * `same-origin`, so a backend that does not allow credentialed CORS still
23
+ * serves it.
21
24
  */
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
- }
25
+ const COOKIE_PATHS = [
26
+ '/sign-in/email',
27
+ '/sign-in/phone-number',
28
+ '/two-factor/',
29
+ '/sign-in/social',
30
+ '/sign-in/sso',
31
+ '/sign-in/oauth2',
32
+ '/link-social',
33
+ '/oauth2/link',
34
+ '/passkey/',
35
+ ];
36
+ /** Sign-ins that come back through the server's OAuth callback, where the PKCE challenge rides. */
37
+ const REDIRECT_SIGN_IN_PATHS = ['/sign-in/social', '/sign-in/sso', '/sign-in/oauth2'];
38
+ /** Calls after which the session this client holds no longer exists. */
39
+ const SIGN_OUT_PATHS = new Set(['/sign-out', '/revoke-sessions']);
40
+ /**
41
+ * Calls that change the user but answer without it (`{ status: true }`): the
42
+ * session is read again after them, so the stored user and USER_UPDATED follow.
43
+ */
44
+ const USER_CHANGE_PATHS = new Set(['/update-user', '/change-email', '/update-user-credentials', '/two-factor/disable']);
48
45
  /**
49
46
  * Read the token an OAuth callback left in the URL fragment and return the URL
50
47
  * with it removed, so a reload or a shared link cannot replay it.
51
48
  *
52
49
  * 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.
50
+ * redirect. The server therefore appends `#access_token=…` to the redirect it
51
+ * issues (auth/oauth-redirect.ts). Exported for testing.
55
52
  */
56
53
  export function readAccessTokenFromUrl(href) {
57
54
  const hash = href.indexOf('#');
@@ -66,819 +63,259 @@ export function readAccessTokenFromUrl(href) {
66
63
  const rest = params.toString();
67
64
  return { accessToken, cleanedHref: `${href.slice(0, hash)}${rest ? `#${rest}` : ''}` };
68
65
  }
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
66
  /**
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.
67
+ * The session a successful auth response carries, if any.
68
+ *
69
+ * Better Auth answers a sign-in with `{ token, user }` (password, OTP, anonymous,
70
+ * id token, second factor) or `{ session: { token }, user }` (passkey,
71
+ * get-session). A `user` is required alongside: the jwt plugin's `/token`
72
+ * answers `{ token }` with a JWT, which is not a session.
80
73
  */
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');
74
+ export function sessionFromResponse(data) {
75
+ if (!data || typeof data !== 'object')
76
+ return null;
77
+ const body = data;
78
+ if (!body.user)
79
+ return null;
80
+ const token = typeof body.token === 'string' ? body.token : body.session?.token;
81
+ return typeof token === 'string' ? { token, user: body.user } : null;
82
+ }
83
+ /**
84
+ * Whether two tokens name the same session. The bearer the server hands out
85
+ * (`set-auth-token`, the OAuth fragment) is the signed cookie value,
86
+ * `<token>.<signature>`, while response bodies carry the bare `<token>`; the
87
+ * bearer plugin accepts either.
88
+ */
89
+ export function sameSession(stored, token) {
90
+ if (!stored || !token)
91
+ return false;
92
+ return stored === token || stored.startsWith(`${token}.`) || token.startsWith(`${stored}.`);
93
+ }
94
+ /** The auth path of a request: `/api/auth/sign-in/email` → `/sign-in/email`. */
95
+ function authPath(url) {
96
+ const pathname = typeof url === 'string' && !/^https?:/.test(url) ? url.split('?')[0] : new URL(url).pathname;
97
+ return pathname.startsWith(HTTP_ROUTES.auth) ? pathname.slice(HTTP_ROUTES.auth.length) : pathname;
98
+ }
99
+ /**
100
+ * The proxy hands out the function it finds detached from its object, so a
101
+ * class instance exposed as an action would lose `this`. Copy its methods out
102
+ * bound.
103
+ */
104
+ function bindMethods(target) {
105
+ const bound = {};
106
+ for (const key of Object.getOwnPropertyNames(Object.getPrototypeOf(target))) {
107
+ const value = target[key];
108
+ if (key !== 'constructor' && typeof value === 'function')
109
+ bound[key] = value.bind(target);
110
+ }
111
+ return bound;
112
+ }
113
+ function adminActions(http) {
114
+ const admin = new AuthAdminClient(http);
115
+ return { ...bindMethods(admin), mfa: bindMethods(admin.mfa) };
116
+ }
117
+ /**
118
+ * Keeps the SDK's session store and Better Auth's calls in step: the bearer
119
+ * goes out on every request, and every response that creates, replaces or ends
120
+ * the session is written back, which is what fires `onAuthStateChange`.
121
+ */
122
+ function sessionSync(store, options,
123
+ /** Reads the session again; its response comes back through this plugin. */
124
+ revalidate) {
125
+ const { flowType, verifiers } = options;
126
+ return {
127
+ id: 'motherbase-session',
128
+ name: 'Motherbase session',
129
+ // Edits the call's options in place rather than returning a copy: better-fetch
130
+ // runs its own schema plugin after this one, and it hands back the options
131
+ // object it was given. The object is built fresh for every call.
132
+ async init(url, fetchOptions = {}) {
133
+ const path = authPath(url);
134
+ fetchOptions.credentials = COOKIE_PATHS.some(prefix => path.startsWith(prefix)) ? 'include' : 'same-origin';
135
+ // Node does not send Origin, and Better Auth's CSRF check wants one on a
136
+ // mutation. Supply the project's own rather than turning the check off.
137
+ const headers = (fetchOptions.headers ?? {});
138
+ if (typeof window === 'undefined' && (fetchOptions.method ?? 'GET').toUpperCase() !== 'GET'
139
+ && !Object.keys(headers).some(name => name.toLowerCase() === 'origin')) {
140
+ fetchOptions.headers = { ...headers, origin: new URL(options.url).origin };
487
141
  }
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' } };
142
+ const body = (fetchOptions.body ?? {});
143
+ // An id-token sign-in answers with the session directly: no redirect.
144
+ if (!REDIRECT_SIGN_IN_PATHS.includes(path) || body.idToken)
145
+ return { url, options: fetchOptions };
146
+ if (flowType === 'pkce') {
147
+ fetchOptions.body = { ...body, callbackURL: await pkceCallback(body.callbackURL, verifiers) };
528
148
  }
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' } };
149
+ if (path === '/sign-in/social' && typeof window !== 'undefined' && !body.disableRedirect) {
150
+ // Started with a fetch, the OAuth state cookie is a cross-site write
151
+ // that Safari and Firefox drop (Chrome too, in incognito), and the
152
+ // callback fails with state_mismatch. Navigating to the server's GET
153
+ // start route makes it first-party. The request is answered locally
154
+ // with Better Auth's own shape, `redirect: false` so it does not
155
+ // navigate a second time.
156
+ const href = socialStartUrl(options.url, fetchOptions.body);
157
+ window.location.href = href;
158
+ fetchOptions.customFetchImpl = async () => Response.json({ url: href, redirect: false });
581
159
  }
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
- }
160
+ return { url, options: fetchOptions };
161
+ },
162
+ hooks: {
163
+ async onSuccess({ data, request }) {
164
+ const path = authPath(request.url);
165
+ const current = store.get();
166
+ const ended = SIGN_OUT_PATHS.has(path)
167
+ || (path === '/revoke-session' && sameSession(current?.accessToken, revokedToken(request.body)))
168
+ || (path === '/delete-user' && data?.message === 'User deleted')
169
+ // The stored token was revoked or expired elsewhere: the server answers
170
+ // null. Only for the stored token: getSessionFromUrl checks another one.
171
+ || (path === '/get-session' && data === null
172
+ && request.headers.get('authorization') === `Bearer ${current?.accessToken}`);
173
+ if (ended) {
174
+ if (current)
175
+ await store.set(null, 'signOut');
176
+ return;
177
+ }
178
+ if (USER_CHANGE_PATHS.has(path) && current) {
179
+ await revalidate();
180
+ return;
181
+ }
182
+ const next = sessionFromResponse(data);
183
+ if (!next)
184
+ return;
185
+ if (!current || !sameSession(current.accessToken, next.token)) {
186
+ await store.set({ accessToken: next.token, user: next.user }, path.startsWith('/two-factor/') ? 'mfaVerified' : 'signIn');
187
+ }
188
+ else if (JSON.stringify(normalizeUser(next.user)) !== JSON.stringify(current.user)) {
189
+ // Compared as the store holds it: normalised, aliases included.
190
+ await store.set({ ...current, user: next.user }, 'userUpdated');
191
+ }
192
+ },
193
+ },
194
+ };
195
+ }
196
+ /** The server's GET start route for a social sign-in (auth/social-start.ts). */
197
+ function socialStartUrl(projectUrl, body) {
198
+ const params = new URLSearchParams();
199
+ for (const key of ['callbackURL', 'errorCallbackURL', 'newUserCallbackURL']) {
200
+ if (body[key])
201
+ params.set(key, body[key]);
202
+ }
203
+ if (body.scopes?.length)
204
+ params.set('scopes', body.scopes.join(' '));
205
+ const query = params.toString();
206
+ const provider = encodeURIComponent(body.provider ?? '');
207
+ return `${projectUrl.replace(/\/$/, '')}${HTTP_ROUTES.authSignInSocial}/${provider}${query ? `?${query}` : ''}`;
208
+ }
209
+ /** The `token` a `/revoke-session` request names. The body reaches the hook serialized. */
210
+ function revokedToken(body) {
211
+ try {
212
+ return (typeof body === 'string' ? JSON.parse(body) : body)?.token;
691
213
  }
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
- }
214
+ catch {
215
+ return undefined;
730
216
  }
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),
217
+ }
218
+ /**
219
+ * The callback URL a PKCE sign-in should use: the given one, or this page, with
220
+ * a fresh challenge on it. The verifier waits in `verifiers` for
221
+ * `exchangeCodeForSession`.
222
+ */
223
+ async function pkceCallback(callbackURL, verifiers) {
224
+ const target = callbackURL ?? (typeof window !== 'undefined' ? window.location.href.split('#')[0] : undefined);
225
+ if (!target)
226
+ throw new Error('flowType "pkce" needs a callbackURL outside a browser.');
227
+ const verifier = generateCodeVerifier();
228
+ await verifiers.set(verifier);
229
+ return withCodeChallenge(target, await codeChallengeFor(verifier));
230
+ }
231
+ /** Motherbase's additions, as a Better Auth client plugin. */
232
+ function motherbaseClient(http, store, options) {
233
+ // Bound when Better Auth hands over its fetch, which happens as the client
234
+ // is built, before any request can reach the session sync.
235
+ let revalidate = async () => undefined;
236
+ return {
237
+ id: 'motherbase',
238
+ fetchPlugins: [sessionSync(store, options, () => revalidate())],
239
+ getActions: $fetch => {
240
+ revalidate = () => $fetch('/get-session');
241
+ return {
242
+ onAuthStateChange(callback) {
243
+ let active = true;
244
+ const unsubscribe = store.subscribe((event, session) => {
245
+ if (active)
246
+ callback(EVENT_MAP[event], session);
247
+ });
248
+ void store.hydrate().then(session => {
249
+ if (active)
250
+ callback('INITIAL_SESSION', session);
251
+ });
252
+ return { data: { subscription: { unsubscribe: () => { active = false; unsubscribe(); } } } };
744
253
  },
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
- },
254
+ async getSessionFromUrl(href) {
255
+ const url = href ?? (typeof window !== 'undefined' ? window.location.href : undefined);
256
+ const found = url ? readAccessTokenFromUrl(url) : null;
257
+ if (!found)
258
+ return { data: null, error: null };
259
+ // Strip the token before the network call: a failed lookup must not
260
+ // leave a usable token in the address bar or the history.
261
+ if (!href && typeof window !== 'undefined') {
262
+ window.history?.replaceState?.(window.history.state, '', found.cleanedHref);
263
+ }
264
+ // Checked before it is stored, so a rejected token never emits
265
+ // SIGNED_IN. On success, sessionSync adopts it from the response.
266
+ const { error } = await $fetch('/get-session', { auth: { type: 'Bearer', token: found.accessToken } });
267
+ if (error)
268
+ return { data: null, error };
269
+ return currentSession(store) ?? { data: null, error: { message: 'The session in the URL is no longer valid.' } };
788
270
  },
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
- },
271
+ async exchangeCodeForSession(authCode) {
272
+ const verifier = await options.verifiers.get();
273
+ if (!verifier) {
274
+ return { data: null, error: { message: 'No PKCE code verifier found: start the sign-in with flowType: "pkce" in this browser.' } };
275
+ }
276
+ const { error } = await $fetch('/exchange-code', {
277
+ method: 'POST',
278
+ body: { auth_code: authCode, code_verifier: verifier },
279
+ });
280
+ if (error)
281
+ return { data: null, error };
282
+ await options.verifiers.clear();
283
+ return currentSession(store) ?? { data: null, error: { message: 'The code did not produce a session.' } };
866
284
  },
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
- }
285
+ reauthenticate: () => $fetch('/reauthenticate', { method: 'POST' }),
286
+ updateUserCredentials: params => $fetch('/update-user-credentials', { method: 'POST', body: params }),
287
+ admin: adminActions(http),
288
+ };
289
+ },
290
+ };
291
+ }
292
+ function currentSession(store) {
293
+ const session = store.get();
294
+ return session ? { data: { user: session.user, session }, error: null } : null;
295
+ }
296
+ export function createAuthClient(http, store, options) {
297
+ const plugins = [
298
+ anonymousClient(),
299
+ emailOTPClient(),
300
+ magicLinkClient(),
301
+ phoneNumberClient(),
302
+ twoFactorClient(),
303
+ organizationClient({ teams: { enabled: true } }),
304
+ genericOAuthClient(),
305
+ jwtClient(),
306
+ passkeyClient(),
307
+ ssoClient(),
308
+ apiKeyClient(),
309
+ motherbaseClient(http, store, options),
310
+ ];
311
+ return createBetterAuthClient({
312
+ baseURL: `${options.url.replace(/\/$/, '')}${HTTP_ROUTES.auth}`,
313
+ fetchOptions: {
314
+ customFetchImpl: http.observedFetch(options.fetch),
315
+ headers: options.headers,
316
+ auth: { type: 'Bearer', token: async () => (await store.hydrate())?.accessToken },
317
+ },
318
+ plugins,
319
+ });
883
320
  }
884
321
  //# sourceMappingURL=auth.js.map