@lovable.dev/cloud-auth-js 1.1.2 → 1.1.3-dev.16

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/index.js CHANGED
@@ -1,39 +1,3 @@
1
- // package.json
2
- var package_default = {
3
- name: "@lovable.dev/cloud-auth-js",
4
- version: "1.1.2",
5
- description: "Lovable Cloud Auth JS",
6
- main: "./dist/index.cjs",
7
- module: "./dist/index.js",
8
- types: "./dist/index.d.ts",
9
- type: "module",
10
- files: [
11
- "dist"
12
- ],
13
- scripts: {
14
- build: "tsup src/index.ts --format cjs,esm --dts --outDir dist",
15
- dev: "tsup src/index.ts --format cjs,esm --dts --watch",
16
- test: "vitest run",
17
- typecheck: "tsgo --noEmit",
18
- prepublishOnly: "npm run clean && npm run build",
19
- clean: "rimraf dist"
20
- },
21
- keywords: [
22
- "lovable",
23
- "oauth",
24
- "authentication"
25
- ],
26
- license: "MIT",
27
- devDependencies: {
28
- "@types/node": "^22",
29
- jsdom: "^26",
30
- rimraf: "^5.0.0",
31
- tsup: "^7.2.0",
32
- typescript: "^5",
33
- vitest: "^4.1.0"
34
- }
35
- };
36
-
37
1
  // src/auth.ts
38
2
  var EXPECTED_MESSAGE_TYPE = "authorization_response";
39
3
  var DEFAULT_OAUTH_BROKER_URL = "/~oauth/initiate";
@@ -204,13 +168,431 @@ function createAuth(config = {}) {
204
168
  };
205
169
  }
206
170
 
207
- // src/index.ts
208
- if (typeof window !== "undefined") {
209
- window.__lovable_cloud_auth_js_version = package_default.version;
171
+ // src/client.ts
172
+ import { genericOAuthClient } from "better-auth/client/plugins";
173
+ import { createAuthClient } from "better-auth/react";
174
+ var DEFAULT_PROVIDER_ID = "lovable";
175
+ var POPUP_NAME = "lovable-oauth";
176
+ var POPUP_CHECK_INTERVAL_MS2 = 500;
177
+ var DEFAULT_POPUP_TIMEOUT_MS = 12e4;
178
+ var POPUP_MESSAGE_TYPE = "lovable:better-auth-popup-complete";
179
+ var POPUP_START_PATH = "lovable-popup/start";
180
+ var POPUP_COMPLETE_PATH = "lovable-popup/complete";
181
+ var SESSION_EVENT_TYPE = "lovable-auth:session";
182
+ function isLivePreview() {
183
+ if (typeof window === "undefined")
184
+ return false;
185
+ try {
186
+ return window.self !== window.top;
187
+ } catch {
188
+ return true;
189
+ }
190
+ }
191
+ function resolveSignInMode(mode) {
192
+ if (mode === "popup" || mode === "redirect")
193
+ return mode;
194
+ return isLivePreview() ? "popup" : "redirect";
195
+ }
196
+ function resolveBaseURL(configured) {
197
+ if (typeof window === "undefined")
198
+ return configured;
199
+ return window.location.origin;
200
+ }
201
+ function resolveAuthBasePath(configured) {
202
+ const basePath = typeof configured === "string" && configured ? configured : "/api/auth";
203
+ return `/${basePath.replace(/^\/+|\/+$/g, "")}`;
204
+ }
205
+ function resolveCallbackURL(callbackURL) {
206
+ if (typeof window === "undefined")
207
+ return callbackURL;
208
+ if (!callbackURL)
209
+ return window.location.href;
210
+ try {
211
+ return new URL(callbackURL, window.location.href).toString();
212
+ } catch {
213
+ return callbackURL;
214
+ }
215
+ }
216
+ function generatePopupId() {
217
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto)
218
+ return crypto.randomUUID();
219
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
220
+ }
221
+ function resolveSameOriginCallbackURL(callbackURL) {
222
+ const resolved = resolveCallbackURL(callbackURL);
223
+ if (typeof window === "undefined" || !resolved)
224
+ return resolved ?? null;
225
+ try {
226
+ const url = new URL(resolved);
227
+ if (url.origin !== window.location.origin)
228
+ return null;
229
+ return url.toString();
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+ function buildPopupCompleteURL(baseURL, basePath, popupId, returnTo) {
235
+ if (typeof window === "undefined")
236
+ return null;
237
+ try {
238
+ const url = new URL(`${basePath}/${POPUP_COMPLETE_PATH}`, baseURL ?? window.location.origin);
239
+ url.searchParams.set("popupId", popupId);
240
+ if (returnTo)
241
+ url.searchParams.set("returnTo", returnTo);
242
+ return url.toString();
243
+ } catch {
244
+ return null;
245
+ }
246
+ }
247
+ function buildPopupStartURL(baseURL, basePath, providerId, options, callbackURL, errorCallbackURL, newUserCallbackURL) {
248
+ if (typeof window === "undefined")
249
+ return null;
250
+ try {
251
+ const url = new URL(`${basePath}/${POPUP_START_PATH}`, baseURL ?? window.location.origin);
252
+ url.searchParams.set("providerId", providerId);
253
+ url.searchParams.set("callbackURL", callbackURL);
254
+ url.searchParams.set("errorCallbackURL", errorCallbackURL);
255
+ url.searchParams.set("newUserCallbackURL", newUserCallbackURL);
256
+ if (options.requestSignUp !== void 0)
257
+ url.searchParams.set("requestSignUp", String(options.requestSignUp));
258
+ for (const scope of options.scopes ?? []) {
259
+ url.searchParams.append("scope", scope);
260
+ }
261
+ return url.toString();
262
+ } catch {
263
+ return null;
264
+ }
265
+ }
266
+ function notifySessionChanged(client, session) {
267
+ const store = client.$store;
268
+ store?.notify?.("$sessionSignal");
269
+ if (typeof window === "undefined" || typeof CustomEvent === "undefined")
270
+ return;
271
+ window.dispatchEvent(new CustomEvent(SESSION_EVENT_TYPE, { detail: { session } }));
272
+ }
273
+ async function getSessionAfterPopupComplete(client, fallback) {
274
+ const session = await client.getSession?.();
275
+ const data = session?.data ?? fallback ?? null;
276
+ notifySessionChanged(client, data);
277
+ return data;
278
+ }
279
+ function toError(error, fallback) {
280
+ if (error instanceof Error)
281
+ return error;
282
+ if (error && typeof error === "object" && "message" in error) {
283
+ const message = error.message;
284
+ if (typeof message === "string" && message)
285
+ return new Error(message);
286
+ }
287
+ if (typeof error === "string" && error)
288
+ return new Error(error);
289
+ return new Error(fallback);
210
290
  }
291
+ function getRedirectUrl(data) {
292
+ if (!data || typeof data !== "object")
293
+ return null;
294
+ const fields = data;
295
+ for (const key of ["url", "redirectURL", "redirectUrl"]) {
296
+ const value = fields[key];
297
+ if (typeof value === "string" && value)
298
+ return value;
299
+ }
300
+ return null;
301
+ }
302
+ function getPopupFeatures(configuredFeatures) {
303
+ if (configuredFeatures)
304
+ return configuredFeatures;
305
+ const width = 520;
306
+ const height = 720;
307
+ const left = typeof window === "undefined" ? 0 : window.screenX + (window.outerWidth - width) / 2;
308
+ const top = typeof window === "undefined" ? 0 : window.screenY + (window.outerHeight - height) / 2;
309
+ return `popup=yes,width=${width},height=${height},left=${left},top=${top}`;
310
+ }
311
+ function openSyncPopup(features) {
312
+ if (typeof window === "undefined")
313
+ return null;
314
+ try {
315
+ return window.open("about:blank", POPUP_NAME, features);
316
+ } catch {
317
+ return null;
318
+ }
319
+ }
320
+ function navigatePopup(popup, url) {
321
+ try {
322
+ popup.location.href = url;
323
+ return true;
324
+ } catch {
325
+ return false;
326
+ }
327
+ }
328
+ function popupReturnedToOpenerOrigin(popup) {
329
+ if (typeof window === "undefined")
330
+ return false;
331
+ try {
332
+ const href = popup.location.href;
333
+ if (!href || href === "about:blank")
334
+ return false;
335
+ return new URL(href).origin === window.location.origin;
336
+ } catch {
337
+ return false;
338
+ }
339
+ }
340
+ async function waitForPopupSession(client, popup, timeoutMs) {
341
+ const startedAt = Date.now();
342
+ return new Promise((resolve, reject) => {
343
+ const interval = setInterval(async () => {
344
+ if (popup.closed) {
345
+ clearInterval(interval);
346
+ reject(new Error("Sign in was cancelled"));
347
+ return;
348
+ }
349
+ if (Date.now() - startedAt > timeoutMs) {
350
+ clearInterval(interval);
351
+ popup.close();
352
+ reject(new Error("OAuth timed out waiting for session"));
353
+ return;
354
+ }
355
+ if (popupReturnedToOpenerOrigin(popup)) {
356
+ clearInterval(interval);
357
+ try {
358
+ const session = await client.getSession?.();
359
+ popup.close();
360
+ resolve(session?.data ?? null);
361
+ } catch (error) {
362
+ popup.close();
363
+ reject(toError(error, "Failed to read session after popup completed"));
364
+ }
365
+ return;
366
+ }
367
+ try {
368
+ const session = await client.getSession?.();
369
+ if (session?.data) {
370
+ clearInterval(interval);
371
+ popup.close();
372
+ resolve(session.data);
373
+ }
374
+ } catch {
375
+ return;
376
+ }
377
+ }, POPUP_CHECK_INTERVAL_MS2);
378
+ });
379
+ }
380
+ function isPopupMessageData(data) {
381
+ return Boolean(data && typeof data === "object" && data.type === POPUP_MESSAGE_TYPE);
382
+ }
383
+ async function waitForPopupMessage(client, popup, popupId, timeoutMs) {
384
+ const startedAt = Date.now();
385
+ return new Promise((resolve, reject) => {
386
+ let interval;
387
+ let timeout;
388
+ const cleanup = () => {
389
+ window.removeEventListener("message", onMessage);
390
+ if (interval)
391
+ clearInterval(interval);
392
+ if (timeout)
393
+ clearTimeout(timeout);
394
+ };
395
+ const onMessage = (event) => {
396
+ if (event.origin !== window.location.origin)
397
+ return;
398
+ if (event.source && event.source !== popup)
399
+ return;
400
+ if (!isPopupMessageData(event.data) || event.data.popupId !== popupId)
401
+ return;
402
+ cleanup();
403
+ popup.close();
404
+ if (event.data.error) {
405
+ reject(new Error(event.data.error));
406
+ return;
407
+ }
408
+ client.getSession?.().then((session) => session?.data ?? event.data.session ?? null).then((session) => {
409
+ notifySessionChanged(client, session);
410
+ resolve(session);
411
+ }).catch((error) => {
412
+ reject(toError(error, "Failed to read session after popup completed"));
413
+ });
414
+ };
415
+ window.addEventListener("message", onMessage);
416
+ interval = setInterval(() => {
417
+ if (popup.closed) {
418
+ cleanup();
419
+ getSessionAfterPopupComplete(client, null).then((session) => {
420
+ if (session) {
421
+ resolve(session);
422
+ return;
423
+ }
424
+ reject(new Error("Sign in was cancelled"));
425
+ }).catch(() => {
426
+ reject(new Error("Sign in was cancelled"));
427
+ });
428
+ }
429
+ }, POPUP_CHECK_INTERVAL_MS2);
430
+ timeout = setTimeout(
431
+ () => {
432
+ cleanup();
433
+ popup.close();
434
+ reject(new Error("OAuth timed out waiting for popup message"));
435
+ },
436
+ Math.max(0, timeoutMs - (Date.now() - startedAt))
437
+ );
438
+ });
439
+ }
440
+ function newAuthClient(options = {}) {
441
+ const {
442
+ providerId = DEFAULT_PROVIDER_ID,
443
+ signInMode = "auto",
444
+ popupFeatures,
445
+ popupTimeoutMs = DEFAULT_POPUP_TIMEOUT_MS,
446
+ ...betterAuthOptions
447
+ } = options;
448
+ const baseURL = resolveBaseURL(betterAuthOptions.baseURL);
449
+ const basePath = resolveAuthBasePath(betterAuthOptions.basePath);
450
+ const client = createAuthClient({
451
+ ...betterAuthOptions,
452
+ baseURL,
453
+ plugins: [genericOAuthClient(), ...betterAuthOptions.plugins ?? []]
454
+ });
455
+ const oauthClient = client;
456
+ const signInWithLovable = async (signInOptions = {}) => {
457
+ const mode = resolveSignInMode(signInOptions.mode ?? signInMode);
458
+ const usePopupMessage = mode === "popup" && isLivePreview();
459
+ if (mode === "popup" && typeof window === "undefined") {
460
+ return {
461
+ data: null,
462
+ error: new Error("Popup sign in requires a browser"),
463
+ mode
464
+ };
465
+ }
466
+ const features = getPopupFeatures(signInOptions.popupFeatures ?? popupFeatures);
467
+ const popup = mode === "popup" ? openSyncPopup(features) : null;
468
+ if (mode === "popup" && !popup) {
469
+ return { data: null, error: new Error("Popup was blocked"), mode };
470
+ }
471
+ const popupId = usePopupMessage ? generatePopupId() : void 0;
472
+ const callbackURL = popupId ? resolveSameOriginCallbackURL(signInOptions.callbackURL) : resolveCallbackURL(signInOptions.callbackURL);
473
+ const errorCallbackURL = popupId && signInOptions.errorCallbackURL ? resolveSameOriginCallbackURL(signInOptions.errorCallbackURL) : resolveCallbackURL(signInOptions.errorCallbackURL) ?? callbackURL;
474
+ const newUserCallbackURL = popupId && signInOptions.newUserCallbackURL ? resolveSameOriginCallbackURL(signInOptions.newUserCallbackURL) : resolveCallbackURL(signInOptions.newUserCallbackURL) ?? callbackURL;
475
+ if (popupId && (!callbackURL || !errorCallbackURL || !newUserCallbackURL)) {
476
+ popup?.close();
477
+ return {
478
+ data: null,
479
+ error: new Error("Iframe popup sign in requires same-origin callback URLs"),
480
+ mode
481
+ };
482
+ }
483
+ if (popupId && callbackURL && errorCallbackURL && newUserCallbackURL && popup) {
484
+ const popupCallbackURL = buildPopupCompleteURL(baseURL, basePath, popupId, callbackURL);
485
+ const popupErrorCallbackURL = buildPopupCompleteURL(baseURL, basePath, popupId, errorCallbackURL);
486
+ const popupNewUserCallbackURL = buildPopupCompleteURL(baseURL, basePath, popupId, newUserCallbackURL);
487
+ const popupStartURL = popupCallbackURL && popupErrorCallbackURL && popupNewUserCallbackURL ? buildPopupStartURL(
488
+ baseURL,
489
+ basePath,
490
+ providerId,
491
+ signInOptions,
492
+ popupCallbackURL,
493
+ popupErrorCallbackURL,
494
+ popupNewUserCallbackURL
495
+ ) : null;
496
+ if (!popupStartURL) {
497
+ popup.close();
498
+ return {
499
+ data: null,
500
+ error: new Error("Failed to build iframe popup sign-in URL"),
501
+ mode
502
+ };
503
+ }
504
+ if (!navigatePopup(popup, popupStartURL)) {
505
+ popup.close();
506
+ return {
507
+ data: null,
508
+ error: new Error("Failed to navigate popup"),
509
+ mode
510
+ };
511
+ }
512
+ try {
513
+ const timeoutMs = signInOptions.popupTimeoutMs ?? popupTimeoutMs;
514
+ const session = await waitForPopupMessage(oauthClient, popup, popupId, timeoutMs);
515
+ return { data: session, error: null, mode };
516
+ } catch (error) {
517
+ return { data: null, error: toError(error, "Sign in failed"), mode };
518
+ }
519
+ }
520
+ const result = await oauthClient.signIn.oauth2({
521
+ providerId,
522
+ callbackURL,
523
+ errorCallbackURL: signInOptions.errorCallbackURL,
524
+ newUserCallbackURL: signInOptions.newUserCallbackURL,
525
+ scopes: signInOptions.scopes,
526
+ requestSignUp: signInOptions.requestSignUp,
527
+ disableRedirect: mode === "popup"
528
+ });
529
+ if (result.error) {
530
+ popup?.close();
531
+ return {
532
+ data: null,
533
+ error: toError(result.error, "Sign in failed"),
534
+ mode
535
+ };
536
+ }
537
+ if (mode === "redirect") {
538
+ return { data: result.data ?? null, error: null, mode };
539
+ }
540
+ const redirectUrl = getRedirectUrl(result.data);
541
+ if (!redirectUrl || !popup) {
542
+ popup?.close();
543
+ return {
544
+ data: null,
545
+ error: new Error("No OAuth redirect URL received"),
546
+ mode
547
+ };
548
+ }
549
+ if (!navigatePopup(popup, redirectUrl)) {
550
+ popup.close();
551
+ return {
552
+ data: null,
553
+ error: new Error("Failed to navigate popup"),
554
+ mode
555
+ };
556
+ }
557
+ try {
558
+ const timeoutMs = signInOptions.popupTimeoutMs ?? popupTimeoutMs;
559
+ const session = await waitForPopupSession(oauthClient, popup, timeoutMs);
560
+ return { data: session, error: null, mode };
561
+ } catch (error) {
562
+ return { data: null, error: toError(error, "Sign in failed"), mode };
563
+ }
564
+ };
565
+ return new Proxy(client, {
566
+ get(target, prop, receiver) {
567
+ if (prop === "signInWithLovable")
568
+ return signInWithLovable;
569
+ return Reflect.get(target, prop, receiver);
570
+ },
571
+ getOwnPropertyDescriptor(target, prop) {
572
+ if (prop === "signInWithLovable") {
573
+ return {
574
+ configurable: true,
575
+ enumerable: true,
576
+ value: signInWithLovable,
577
+ writable: false
578
+ };
579
+ }
580
+ return Reflect.getOwnPropertyDescriptor(target, prop);
581
+ },
582
+ has(target, prop) {
583
+ return prop === "signInWithLovable" || Reflect.has(target, prop);
584
+ },
585
+ ownKeys(target) {
586
+ return [.../* @__PURE__ */ new Set([...Reflect.ownKeys(target), "signInWithLovable"])];
587
+ }
588
+ });
589
+ }
590
+
591
+ // src/index.ts
211
592
  function createLovableAuth(config = {}) {
212
593
  return createAuth(config);
213
594
  }
214
595
  export {
215
- createLovableAuth
596
+ createLovableAuth,
597
+ newAuthClient
216
598
  };