@agent-native/core 0.158.3 → 0.158.5

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.
@@ -62,11 +62,11 @@ export declare const postAwareness: import("h3").EventHandlerWithFetch<import("h
62
62
  error: string;
63
63
  states?: undefined;
64
64
  } | {
65
+ error?: undefined;
65
66
  states: {
66
67
  clientId: number;
67
68
  state: string;
68
69
  }[];
69
- error?: undefined;
70
70
  }>>;
71
71
  /**
72
72
  * GET /_agent-native/collab/:docId/users
@@ -77,9 +77,9 @@ export declare const getActiveUsers: import("h3").EventHandlerWithFetch<import("
77
77
  error: string;
78
78
  users?: undefined;
79
79
  } | {
80
+ error?: undefined;
80
81
  users: {
81
82
  clientId: number;
82
83
  lastSeen: number;
83
84
  }[];
84
- error?: undefined;
85
85
  }>>;
@@ -13,8 +13,8 @@
13
13
  * Body: { json: any, fieldName?: string, type?: "map"|"array", requestSource?: string }
14
14
  */
15
15
  export declare const postCollabJson: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
16
- ok?: undefined;
17
16
  error: string;
17
+ ok?: undefined;
18
18
  } | {
19
19
  error?: undefined;
20
20
  ok: boolean;
@@ -62,6 +62,6 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
62
62
  summary?: undefined;
63
63
  spans?: undefined;
64
64
  id?: undefined;
65
- error?: undefined;
66
65
  ok: boolean;
66
+ error?: undefined;
67
67
  }>>;
@@ -48,8 +48,8 @@ export declare function handleUpdateResource(event: any): Promise<import("./stor
48
48
  }>;
49
49
  /** DELETE /_agent-native/resources/:id — delete a resource */
50
50
  export declare function handleDeleteResource(event: any): Promise<{
51
- ok?: undefined;
52
51
  error: string;
52
+ ok?: undefined;
53
53
  } | {
54
54
  error?: undefined;
55
55
  ok: boolean;
@@ -1535,6 +1535,56 @@ function escapeHtmlAttr(value) {
1535
1535
  .replace(/>/g, "&gt;")
1536
1536
  .replace(/"/g, "&quot;");
1537
1537
  }
1538
+ const DESKTOP_MAGIC_LINK_CALLBACK_PATH = "/_agent-native/auth/magic-link/desktop-callback";
1539
+ const DESKTOP_MAGIC_LINK_LANDING_PATH = "/_agent-native/auth/magic-link/desktop-landing";
1540
+ const BETTER_AUTH_MAGIC_LINK_VERIFY_PATH = "/_agent-native/auth/ba/magic-link/verify";
1541
+ function desktopMagicLinkVerificationUrl(event, values) {
1542
+ const value = (key) => typeof values[key] === "string" ? values[key] : "";
1543
+ const token = value("token").trim();
1544
+ const callbackURL = value("callbackURL");
1545
+ if (!token || !callbackURL)
1546
+ return undefined;
1547
+ try {
1548
+ const callback = new URL(callbackURL, getOrigin(event));
1549
+ if (callback.origin !== new URL(getOrigin(event)).origin ||
1550
+ !callback.pathname.endsWith(DESKTOP_MAGIC_LINK_CALLBACK_PATH) ||
1551
+ !normalizeDesktopFlowId(callback.searchParams.get("flow_id")) ||
1552
+ !normalizeDesktopFlowVerifier(callback.searchParams.get("verifier"))) {
1553
+ return undefined;
1554
+ }
1555
+ const verificationURL = new URL(getAppUrl(event, BETTER_AUTH_MAGIC_LINK_VERIFY_PATH));
1556
+ verificationURL.searchParams.set("token", token);
1557
+ for (const key of [
1558
+ "callbackURL",
1559
+ "newUserCallbackURL",
1560
+ "errorCallbackURL",
1561
+ ]) {
1562
+ const queryValue = value(key);
1563
+ if (queryValue)
1564
+ verificationURL.searchParams.set(key, queryValue);
1565
+ }
1566
+ return verificationURL;
1567
+ // coercion-ok: malformed user-supplied callback data is rejected as absent.
1568
+ }
1569
+ catch {
1570
+ return undefined;
1571
+ }
1572
+ }
1573
+ function desktopMagicLinkLandingPage(actionUrl, fields) {
1574
+ const safeActionUrl = escapeHtmlAttr(actionUrl);
1575
+ const hiddenInputs = Object.entries(fields)
1576
+ .map(([name, value]) => `<input type="hidden" name="${escapeHtmlAttr(name)}" value="${escapeHtmlAttr(value)}">`)
1577
+ .join("");
1578
+ const html = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Continue sign-in</title></head><body><main><h1>Continue signing in</h1><p>Click continue to finish signing in to the Agent Native desktop app.</p><form method="post" action="${safeActionUrl}" autocomplete="off">${hiddenInputs}<button type="submit">Continue</button></form></main></body></html>`;
1579
+ return new Response(html, {
1580
+ status: 200,
1581
+ headers: {
1582
+ "cache-control": "no-store",
1583
+ "content-type": "text/html; charset=utf-8",
1584
+ "referrer-policy": "no-referrer",
1585
+ },
1586
+ });
1587
+ }
1538
1588
  function injectLoginSocialImageMeta(loginHtml, event) {
1539
1589
  const headCloseIdx = loginHtml.indexOf("</head>");
1540
1590
  if (headCloseIdx === -1)
@@ -3034,6 +3084,51 @@ async function mountBetterAuthRoutes(app, options) {
3034
3084
  // Magic-link verification happens in the system browser, so native shells
3035
3085
  // need the verified browser session copied into the same one-time exchange
3036
3086
  // used by Google OAuth before they can establish their own WebView session.
3087
+ // Keep the desktop email URL itself non-consuming: mail security scanners
3088
+ // commonly prefetch GET links, while Better Auth consumes a magic-link token
3089
+ // on the first verification GET. The explicit form action below is the only
3090
+ // request that reaches Better Auth's consuming verification endpoint.
3091
+ app.use(DESKTOP_MAGIC_LINK_LANDING_PATH, defineEventHandler((event) => {
3092
+ if (getMethod(event) === "POST") {
3093
+ return readBody(event).then((body) => {
3094
+ const verificationURL = desktopMagicLinkVerificationUrl(event, body);
3095
+ if (!verificationURL) {
3096
+ setResponseStatus(event, 400);
3097
+ return { error: "Invalid desktop magic-link" };
3098
+ }
3099
+ return new Response(null, {
3100
+ status: 303,
3101
+ headers: {
3102
+ "cache-control": "no-store",
3103
+ location: verificationURL.toString(),
3104
+ "referrer-policy": "no-referrer",
3105
+ },
3106
+ });
3107
+ });
3108
+ }
3109
+ if (!isReadMethod(event)) {
3110
+ setResponseStatus(event, 405);
3111
+ return { error: "Method not allowed" };
3112
+ }
3113
+ const query = getQuery(event);
3114
+ const verificationURL = desktopMagicLinkVerificationUrl(event, query);
3115
+ if (!verificationURL) {
3116
+ setResponseStatus(event, 400);
3117
+ return { error: "Invalid desktop magic-link" };
3118
+ }
3119
+ const fields = {};
3120
+ for (const key of [
3121
+ "token",
3122
+ "callbackURL",
3123
+ "newUserCallbackURL",
3124
+ "errorCallbackURL",
3125
+ ]) {
3126
+ if (typeof query[key] === "string" && query[key]) {
3127
+ fields[key] = query[key];
3128
+ }
3129
+ }
3130
+ return desktopMagicLinkLandingPage(getAppUrl(event, DESKTOP_MAGIC_LINK_LANDING_PATH), fields);
3131
+ }));
3037
3132
  app.use("/_agent-native/auth/magic-link/desktop-callback", defineEventHandler(async (event) => {
3038
3133
  if (!isReadMethod(event)) {
3039
3134
  setResponseStatus(event, 405);
@@ -3041,18 +3136,42 @@ async function mountBetterAuthRoutes(app, options) {
3041
3136
  }
3042
3137
  const flowId = normalizeDesktopFlowId(getQuery(event).flow_id);
3043
3138
  const verifier = normalizeDesktopFlowVerifier(getQuery(event).verifier);
3139
+ const callbackError = getQuery(event).error;
3044
3140
  if (!flowId) {
3045
3141
  setResponseStatus(event, 400);
3046
3142
  return { error: "Missing flow_id" };
3047
3143
  }
3048
3144
  if (!verifier) {
3145
+ setDesktopExchangeError(flowId, {
3146
+ message: AUTH_MAGIC_LINK_FALLBACK,
3147
+ code: "missing_verifier",
3148
+ });
3149
+ return oauthErrorPage(AUTH_MAGIC_LINK_FALLBACK);
3150
+ }
3151
+ if (typeof callbackError === "string" && callbackError.trim()) {
3152
+ const code = callbackError
3153
+ .trim()
3154
+ .replace(/[^a-z0-9_-]/gi, "_")
3155
+ .slice(0, 64);
3156
+ setDesktopExchangeError(flowId, {
3157
+ message: AUTH_MAGIC_LINK_FALLBACK,
3158
+ code: code || "callback_error",
3159
+ });
3160
+ logGoogleOAuthDebug(event, "magic-link-callback-error", {
3161
+ flowId,
3162
+ message: callbackError,
3163
+ code: code || "callback_error",
3164
+ });
3049
3165
  return oauthErrorPage(AUTH_MAGIC_LINK_FALLBACK);
3050
3166
  }
3051
3167
  const session = await getSession(event);
3052
3168
  if (!session?.email || !session.token) {
3053
3169
  setDesktopExchangeError(flowId, {
3054
3170
  message: AUTH_MAGIC_LINK_FALLBACK,
3055
- code: "callback_error",
3171
+ code: "callback_session_missing",
3172
+ });
3173
+ logGoogleOAuthDebug(event, "magic-link-callback-session-missing", {
3174
+ flowId,
3056
3175
  });
3057
3176
  return oauthErrorPage(AUTH_MAGIC_LINK_FALLBACK);
3058
3177
  }
@@ -3068,11 +3187,18 @@ async function mountBetterAuthRoutes(app, options) {
3068
3187
  });
3069
3188
  setDesktopExchangeError(flowId, {
3070
3189
  message: AUTH_MAGIC_LINK_FALLBACK,
3071
- code: "callback_error",
3190
+ code: "callback_session_persist_failed",
3191
+ });
3192
+ logGoogleOAuthDebug(event, "magic-link-callback-session-persist-failed", {
3193
+ flowId,
3072
3194
  });
3073
3195
  return oauthErrorPage(AUTH_MAGIC_LINK_FALLBACK);
3074
3196
  }
3075
- if (!(await claimDesktopMagicLinkFlow(flowId, verifier, session.token, session.email))) {
3197
+ const claimed = await claimDesktopMagicLinkFlow(flowId, verifier, session.token, session.email);
3198
+ if (!claimed) {
3199
+ logGoogleOAuthDebug(event, "magic-link-callback-flow-claim-failed", {
3200
+ flowId,
3201
+ });
3076
3202
  return oauthErrorPage(AUTH_MAGIC_LINK_FALLBACK);
3077
3203
  }
3078
3204
  return oauthDesktopExchangePage("Sign-in complete. You can return to the app.", !isElectronRequest(event));
@@ -152,6 +152,15 @@ export declare function getBetterAuth(config?: BetterAuthConfig): Promise<Better
152
152
  * Use this in hot paths where you know init has already happened.
153
153
  */
154
154
  export declare function getBetterAuthSync(): BetterAuthInstance | undefined;
155
+ /**
156
+ * Email security scanners commonly prefetch ordinary GET links. Better Auth
157
+ * intentionally consumes a magic-link token on that first GET, so a scanner
158
+ * can otherwise spend a desktop flow before the user ever clicks it. Keep the
159
+ * normal web link unchanged and put only desktop flows behind an explicit
160
+ * confirmation page that hands the original verification URL back after the
161
+ * user acts.
162
+ */
163
+ export declare function desktopMagicLinkLandingUrl(value: string): string | undefined;
155
164
  /**
156
165
  * The subset of Better Auth's internal adapter we use for federated-SSO
157
166
  * JIT account linking. Better Auth owns these writes (id + timestamp +
@@ -549,6 +549,53 @@ export async function getBetterAuth(config) {
549
549
  export function getBetterAuthSync() {
550
550
  return _auth;
551
551
  }
552
+ const BETTER_AUTH_MAGIC_LINK_VERIFY_MARKER = "/_agent-native/auth/ba/magic-link/verify";
553
+ const DESKTOP_MAGIC_LINK_CALLBACK_MARKER = "/_agent-native/auth/magic-link/desktop-callback";
554
+ const DESKTOP_MAGIC_LINK_LANDING_MARKER = "/_agent-native/auth/magic-link/desktop-landing";
555
+ /**
556
+ * Email security scanners commonly prefetch ordinary GET links. Better Auth
557
+ * intentionally consumes a magic-link token on that first GET, so a scanner
558
+ * can otherwise spend a desktop flow before the user ever clicks it. Keep the
559
+ * normal web link unchanged and put only desktop flows behind an explicit
560
+ * confirmation page that hands the original verification URL back after the
561
+ * user acts.
562
+ */
563
+ export function desktopMagicLinkLandingUrl(value) {
564
+ try {
565
+ const verificationUrl = new URL(value);
566
+ const callbackValue = verificationUrl.searchParams.get("callbackURL");
567
+ if (!callbackValue)
568
+ return undefined;
569
+ const callbackUrl = new URL(callbackValue, verificationUrl.origin);
570
+ if (callbackUrl.origin !== verificationUrl.origin)
571
+ return undefined;
572
+ if (!callbackUrl.pathname.endsWith(DESKTOP_MAGIC_LINK_CALLBACK_MARKER)) {
573
+ return undefined;
574
+ }
575
+ const verifyMarkerIndex = verificationUrl.pathname.lastIndexOf(BETTER_AUTH_MAGIC_LINK_VERIFY_MARKER);
576
+ if (verifyMarkerIndex < 0)
577
+ return undefined;
578
+ const landingUrl = new URL(verificationUrl.origin);
579
+ landingUrl.pathname =
580
+ verificationUrl.pathname.slice(0, verifyMarkerIndex) +
581
+ DESKTOP_MAGIC_LINK_LANDING_MARKER;
582
+ for (const key of [
583
+ "token",
584
+ "callbackURL",
585
+ "newUserCallbackURL",
586
+ "errorCallbackURL",
587
+ ]) {
588
+ const queryValue = verificationUrl.searchParams.get(key);
589
+ if (queryValue)
590
+ landingUrl.searchParams.set(key, queryValue);
591
+ }
592
+ return landingUrl.toString();
593
+ }
594
+ catch {
595
+ // coercion-ok: malformed provider URLs keep the original link unchanged.
596
+ return undefined;
597
+ }
598
+ }
552
599
  /**
553
600
  * Replace the only unverified credential account and add Google in one
554
601
  * database transaction. The read in ensureGoogleAuthIdentityWithAdapter is
@@ -1118,9 +1165,10 @@ async function createBetterAuthInstance(config) {
1118
1165
  const magicLinkUrl = appBasePath
1119
1166
  ? url.replace(/(\/\/[^/]+)(\/)/, `$1${appBasePath}$2`)
1120
1167
  : url;
1168
+ const deliveredMagicLinkUrl = desktopMagicLinkLandingUrl(magicLinkUrl) ?? magicLinkUrl;
1121
1169
  const { subject, html, text, appSender } = renderMagicLinkEmail({
1122
1170
  email,
1123
- magicLinkUrl,
1171
+ magicLinkUrl: deliveredMagicLinkUrl,
1124
1172
  });
1125
1173
  await sendEmail({ to: email, subject, html, text, appSender });
1126
1174
  },
@@ -26,8 +26,8 @@ export declare function createRealtimeTokenHandler(): import("h3").EventHandlerW
26
26
  expiresAt?: undefined;
27
27
  ttlSeconds?: undefined;
28
28
  } | {
29
+ error?: undefined;
29
30
  token: string;
30
31
  expiresAt: string;
31
32
  ttlSeconds: number;
32
- error?: undefined;
33
33
  }>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.158.3",
3
+ "version": "0.158.5",
4
4
  "description": "Framework for agent-native application development — where AI agents and UI share SQL state, actions, and context",
5
5
  "homepage": "https://github.com/BuilderIO/agent-native#readme",
6
6
  "bugs": {