@agent-native/core 0.12.27 → 0.12.30

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.
Files changed (69) hide show
  1. package/dist/agent/engine/builder-engine.d.ts +1 -1
  2. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  3. package/dist/agent/index.d.ts +1 -1
  4. package/dist/agent/index.d.ts.map +1 -1
  5. package/dist/agent/index.js.map +1 -1
  6. package/dist/agent/model-config.d.ts +3 -3
  7. package/dist/agent/model-config.d.ts.map +1 -1
  8. package/dist/agent/model-config.js +5 -4
  9. package/dist/agent/model-config.js.map +1 -1
  10. package/dist/agent/production-agent.d.ts +25 -1
  11. package/dist/agent/production-agent.d.ts.map +1 -1
  12. package/dist/agent/production-agent.js +47 -7
  13. package/dist/agent/production-agent.js.map +1 -1
  14. package/dist/application-state/emitter.d.ts +3 -2
  15. package/dist/application-state/emitter.d.ts.map +1 -1
  16. package/dist/application-state/emitter.js +4 -2
  17. package/dist/application-state/emitter.js.map +1 -1
  18. package/dist/application-state/store.js +3 -3
  19. package/dist/application-state/store.js.map +1 -1
  20. package/dist/client/AgentPanel.d.ts.map +1 -1
  21. package/dist/client/AgentPanel.js +0 -1
  22. package/dist/client/AgentPanel.js.map +1 -1
  23. package/dist/client/AssistantChat.d.ts.map +1 -1
  24. package/dist/client/AssistantChat.js +45 -7
  25. package/dist/client/AssistantChat.js.map +1 -1
  26. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  27. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  28. package/dist/client/agent-chat-adapter.js +12 -5
  29. package/dist/client/agent-chat-adapter.js.map +1 -1
  30. package/dist/client/use-chat-models.js.map +1 -1
  31. package/dist/client/use-db-sync.d.ts +4 -0
  32. package/dist/client/use-db-sync.d.ts.map +1 -1
  33. package/dist/client/use-db-sync.js +38 -13
  34. package/dist/client/use-db-sync.js.map +1 -1
  35. package/dist/client/use-pausing-interval.d.ts.map +1 -1
  36. package/dist/client/use-pausing-interval.js +5 -2
  37. package/dist/client/use-pausing-interval.js.map +1 -1
  38. package/dist/collab/client.d.ts +2 -0
  39. package/dist/collab/client.d.ts.map +1 -1
  40. package/dist/collab/client.js +37 -4
  41. package/dist/collab/client.js.map +1 -1
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js.map +1 -1
  45. package/dist/server/agent-chat-plugin.d.ts +25 -1
  46. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  47. package/dist/server/agent-chat-plugin.js +3 -0
  48. package/dist/server/agent-chat-plugin.js.map +1 -1
  49. package/dist/server/auth.d.ts.map +1 -1
  50. package/dist/server/auth.js +83 -2
  51. package/dist/server/auth.js.map +1 -1
  52. package/dist/server/google-auth-plugin.d.ts.map +1 -1
  53. package/dist/server/google-auth-plugin.js +50 -3
  54. package/dist/server/google-auth-plugin.js.map +1 -1
  55. package/dist/server/google-oauth.d.ts.map +1 -1
  56. package/dist/server/google-oauth.js +10 -4
  57. package/dist/server/google-oauth.js.map +1 -1
  58. package/dist/server/index.d.ts +1 -1
  59. package/dist/server/index.d.ts.map +1 -1
  60. package/dist/server/index.js.map +1 -1
  61. package/dist/server/onboarding-html.d.ts.map +1 -1
  62. package/dist/server/onboarding-html.js +50 -3
  63. package/dist/server/onboarding-html.js.map +1 -1
  64. package/dist/server/poll.d.ts.map +1 -1
  65. package/dist/server/poll.js +15 -0
  66. package/dist/server/poll.js.map +1 -1
  67. package/dist/templates/default/app/hooks/use-navigation-state.ts +0 -1
  68. package/package.json +1 -1
  69. package/src/templates/default/app/hooks/use-navigation-state.ts +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"google-auth-plugin.d.ts","sourceRoot":"","sources":["../../src/server/google-auth-plugin.ts"],"names":[],"mappings":"AAEA,KAAK,cAAc,GAAG,CAAC,QAAQ,EAAE,GAAG,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE9D,MAAM,WAAW,uBAAuB;IACtC,yDAAyD;IACzD,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CACxB;AA6KD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,CAAC,EAAE,uBAAuB,GAChC,cAAc,CAUhB"}
1
+ {"version":3,"file":"google-auth-plugin.d.ts","sourceRoot":"","sources":["../../src/server/google-auth-plugin.ts"],"names":[],"mappings":"AAEA,KAAK,cAAc,GAAG,CAAC,QAAQ,EAAE,GAAG,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE9D,MAAM,WAAW,uBAAuB;IACtC,yDAAyD;IACzD,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CACxB;AA4ND;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,CAAC,EAAE,uBAAuB,GAChC,cAAc,CAUhB"}
@@ -46,6 +46,15 @@ const GOOGLE_LOGIN_HTML = `<!DOCTYPE html>
46
46
  button:disabled { opacity: 0.5; cursor: wait; }
47
47
  .error { margin-top: 0.75rem; font-size: 0.8125rem; color: #f87171; display: none; }
48
48
  .error.show { display: block; }
49
+ .debug {
50
+ display: none;
51
+ margin-top: 0.625rem;
52
+ font-size: 0.6875rem;
53
+ line-height: 1.45;
54
+ color: #777;
55
+ word-break: break-word;
56
+ }
57
+ .debug.show { display: block; }
49
58
  svg { width: 18px; height: 18px; }
50
59
  </style>
51
60
  </head>
@@ -58,6 +67,7 @@ const GOOGLE_LOGIN_HTML = `<!DOCTYPE html>
58
67
  Sign in with Google
59
68
  </button>
60
69
  <p class="error" id="err"></p>
70
+ <p class="debug" id="debug"></p>
61
71
  </div>
62
72
  <script>
63
73
  function __anBasePath() {
@@ -81,6 +91,7 @@ const GOOGLE_LOGIN_HTML = `<!DOCTYPE html>
81
91
  }
82
92
  }
83
93
  var __anOAuthPollTimer = null;
94
+ var __anOAuthPollCount = 0;
84
95
  function __anNewOAuthFlowId() {
85
96
  try {
86
97
  if (window.crypto && typeof window.crypto.randomUUID === 'function') {
@@ -89,6 +100,20 @@ const GOOGLE_LOGIN_HTML = `<!DOCTYPE html>
89
100
  } catch(e) {}
90
101
  return 'builder-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2);
91
102
  }
103
+ function __anFlowDebugId(flowId) {
104
+ return flowId ? String(flowId).slice(-10) : '';
105
+ }
106
+ function __anSetOAuthDebug(message, flowId) {
107
+ var text = message + (flowId ? ' (flow ' + __anFlowDebugId(flowId) + ')' : '');
108
+ try {
109
+ console.info('[agent-native][google-oauth]', { message: message, flow: __anFlowDebugId(flowId) || undefined });
110
+ } catch(e) {}
111
+ var debug = document.getElementById('debug');
112
+ if (debug) {
113
+ debug.textContent = text;
114
+ debug.classList.add('show');
115
+ }
116
+ }
92
117
  function __anShowOAuthError(err, btn, message) {
93
118
  if (__anOAuthPollTimer) {
94
119
  clearInterval(__anOAuthPollTimer);
@@ -101,23 +126,34 @@ const GOOGLE_LOGIN_HTML = `<!DOCTYPE html>
101
126
  function __anWaitForOAuthExchange(flowId, ret, btn, err) {
102
127
  var started = Date.now();
103
128
  var timeoutMs = 5 * 60 * 1000;
129
+ __anOAuthPollCount = 0;
104
130
  async function check() {
131
+ __anOAuthPollCount++;
105
132
  try {
106
133
  var res = await fetch(__anPath('/_agent-native/auth/desktop-exchange') + '?flow_id=' + encodeURIComponent(flowId), { credentials: 'include' });
107
134
  var data = await res.json().catch(function() { return {}; });
108
135
  if (data && (data.email || data.token)) {
109
136
  if (__anOAuthPollTimer) clearInterval(__anOAuthPollTimer);
110
137
  __anOAuthPollTimer = null;
138
+ __anSetOAuthDebug('OAuth exchange redeemed; returning to the app', flowId);
111
139
  window.location.href = ret || '/';
112
140
  return;
113
141
  }
114
142
  if (data && data.error) {
143
+ __anSetOAuthDebug('OAuth exchange returned an error: ' + (data.message || data.error), flowId);
115
144
  __anShowOAuthError(err, btn, data.message || data.error);
116
145
  return;
117
146
  }
118
- } catch(e) {}
147
+ if (data && data.pending && (__anOAuthPollCount === 1 || __anOAuthPollCount % 5 === 0)) {
148
+ __anSetOAuthDebug('Waiting for the Google callback; polling attempt ' + __anOAuthPollCount, flowId);
149
+ }
150
+ } catch(e) {
151
+ if (__anOAuthPollCount === 1 || __anOAuthPollCount % 5 === 0) {
152
+ __anSetOAuthDebug('Could not reach the OAuth exchange endpoint: ' + (e && e.message ? e.message : 'network error'), flowId);
153
+ }
154
+ }
119
155
  if (Date.now() - started > timeoutMs) {
120
- __anShowOAuthError(err, btn, 'Google sign-in did not finish. Allow popups and try again.');
156
+ __anShowOAuthError(err, btn, 'Google sign-in did not finish. Flow ' + __anFlowDebugId(flowId) + ' never redeemed; check server logs for [agent-native][google-oauth].');
121
157
  }
122
158
  }
123
159
  if (__anOAuthPollTimer) clearInterval(__anOAuthPollTimer);
@@ -133,7 +169,18 @@ const GOOGLE_LOGIN_HTML = `<!DOCTYPE html>
133
169
  params.set('redirect', '1');
134
170
  var url = __anPath('/_agent-native/google/auth-url') + '?' + params.toString();
135
171
  try { sessionStorage.setItem('__an_signin', '1'); } catch(e) {}
136
- try { window.open(url, '_blank', 'noopener,noreferrer,width=640,height=760'); } catch(e) {}
172
+ __anSetOAuthDebug('Opening Google sign-in popup', flowId);
173
+ try {
174
+ var popup = window.open(url, '_blank', 'noopener,noreferrer,width=640,height=760');
175
+ if (!popup) {
176
+ __anShowOAuthError(err, btn, 'Google popup was blocked. Allow popups for this site and try again (flow ' + __anFlowDebugId(flowId) + ').');
177
+ return;
178
+ }
179
+ __anSetOAuthDebug('Google popup opened; waiting for callback', flowId);
180
+ } catch(e) {
181
+ __anShowOAuthError(err, btn, 'Could not open Google popup for flow ' + __anFlowDebugId(flowId) + ': ' + (e && e.message ? e.message : 'unknown error'));
182
+ return;
183
+ }
137
184
  __anWaitForOAuthExchange(flowId, ret, btn, err);
138
185
  }
139
186
  function __anOpenOAuthUrl(url) {
@@ -1 +1 @@
1
- {"version":3,"file":"google-auth-plugin.js","sourceRoot":"","sources":["../../src/server/google-auth-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AASpD,MAAM,iBAAiB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAyKlB,CAAC;AAET;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAiC;IAEjC,OAAO,gBAAgB,CAAC;QACtB,WAAW,EAAE;YACX,gCAAgC;YAChC,gCAAgC;YAChC,wBAAwB;YACxB,GAAG,CAAC,OAAO,EAAE,WAAW,IAAI,EAAE,CAAC;SAChC;QACD,SAAS,EAAE,iBAAiB;KAC7B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { createAuthPlugin } from \"./auth-plugin.js\";\n\ntype NitroPluginDef = (nitroApp: any) => void | Promise<void>;\n\nexport interface GoogleAuthPluginOptions {\n /** Additional paths accessible without authentication */\n publicPaths?: string[];\n}\n\nconst GOOGLE_LOGIN_HTML = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\">\n<title>Sign in</title>\n<style>\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n background: #0a0a0a;\n color: #e5e5e5;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n .card {\n width: 100%;\n max-width: 360px;\n padding: 2rem;\n background: #141414;\n border: 1px solid rgba(255,255,255,0.08);\n border-radius: 12px;\n text-align: center;\n }\n h1 { font-size: 1.125rem; font-weight: 600; margin-bottom: 0.5rem; color: #fff; }\n .subtitle { font-size: 0.8125rem; color: #888; margin-bottom: 1.5rem; }\n button {\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 0.625rem;\n padding: 0.625rem;\n background: #fff;\n color: #000;\n border: none;\n border-radius: 8px;\n font-size: 0.9375rem;\n font-weight: 500;\n cursor: pointer;\n }\n button:hover { opacity: 0.85; }\n button:disabled { opacity: 0.5; cursor: wait; }\n .error { margin-top: 0.75rem; font-size: 0.8125rem; color: #f87171; display: none; }\n .error.show { display: block; }\n svg { width: 18px; height: 18px; }\n</style>\n</head>\n<body>\n<div class=\"card\">\n <h1>Sign in</h1>\n <p class=\"subtitle\">Continue with your Google account</p>\n <button id=\"btn\" onclick=\"signIn()\">\n <svg viewBox=\"0 0 24 24\"><path fill=\"#4285F4\" d=\"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z\"/><path fill=\"#34A853\" d=\"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z\"/><path fill=\"#FBBC05\" d=\"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z\"/><path fill=\"#EA4335\" d=\"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z\"/></svg>\n Sign in with Google\n </button>\n <p class=\"error\" id=\"err\"></p>\n</div>\n<script>\n function __anBasePath() {\n var marker = '/_agent-native';\n var idx = window.location.pathname.indexOf(marker);\n return idx > 0 ? window.location.pathname.slice(0, idx) : '';\n }\n function __anPath(path) {\n return __anBasePath() + path;\n }\n function __anIsBuilderPreview() {\n try {\n var params = new URLSearchParams(window.location.search);\n if (params.has('builder.preview') || params.has('builder.frameEditing') || params.has('__builder_editing__')) return true;\n } catch(e) {}\n try {\n var ref = document.referrer || '';\n return ref.indexOf('builder.io') !== -1 || ref.indexOf('builder.my') !== -1 || ref.indexOf('builderio.xyz') !== -1;\n } catch(e) {\n return false;\n }\n }\n var __anOAuthPollTimer = null;\n function __anNewOAuthFlowId() {\n try {\n if (window.crypto && typeof window.crypto.randomUUID === 'function') {\n return window.crypto.randomUUID();\n }\n } catch(e) {}\n return 'builder-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2);\n }\n function __anShowOAuthError(err, btn, message) {\n if (__anOAuthPollTimer) {\n clearInterval(__anOAuthPollTimer);\n __anOAuthPollTimer = null;\n }\n err.textContent = message;\n err.classList.add('show');\n btn.disabled = false;\n }\n function __anWaitForOAuthExchange(flowId, ret, btn, err) {\n var started = Date.now();\n var timeoutMs = 5 * 60 * 1000;\n async function check() {\n try {\n var res = await fetch(__anPath('/_agent-native/auth/desktop-exchange') + '?flow_id=' + encodeURIComponent(flowId), { credentials: 'include' });\n var data = await res.json().catch(function() { return {}; });\n if (data && (data.email || data.token)) {\n if (__anOAuthPollTimer) clearInterval(__anOAuthPollTimer);\n __anOAuthPollTimer = null;\n window.location.href = ret || '/';\n return;\n }\n if (data && data.error) {\n __anShowOAuthError(err, btn, data.message || data.error);\n return;\n }\n } catch(e) {}\n if (Date.now() - started > timeoutMs) {\n __anShowOAuthError(err, btn, 'Google sign-in did not finish. Allow popups and try again.');\n }\n }\n if (__anOAuthPollTimer) clearInterval(__anOAuthPollTimer);\n __anOAuthPollTimer = setInterval(check, 1000);\n setTimeout(check, 500);\n }\n function __anStartBuilderOAuth(ret, btn, err) {\n var flowId = __anNewOAuthFlowId();\n var params = new URLSearchParams();\n if (ret) params.set('return', ret);\n params.set('desktop', '1');\n params.set('flow_id', flowId);\n params.set('redirect', '1');\n var url = __anPath('/_agent-native/google/auth-url') + '?' + params.toString();\n try { sessionStorage.setItem('__an_signin', '1'); } catch(e) {}\n try { window.open(url, '_blank', 'noopener,noreferrer,width=640,height=760'); } catch(e) {}\n __anWaitForOAuthExchange(flowId, ret, btn, err);\n }\n function __anOpenOAuthUrl(url) {\n try { sessionStorage.setItem('__an_signin', '1'); } catch(e) {}\n window.location.href = url;\n }\n async function signIn() {\n var btn = document.getElementById('btn');\n var err = document.getElementById('err');\n var ret = window.location.pathname + window.location.search;\n btn.disabled = true;\n err.classList.remove('show');\n if (__anIsBuilderPreview()) {\n __anStartBuilderOAuth(ret, btn, err);\n return;\n }\n try {\n var res = await fetch(__anPath('/_agent-native/google/auth-url') + '?return=' + encodeURIComponent(ret));\n var data = await res.json();\n if (data.url) {\n __anOpenOAuthUrl(data.url);\n } else {\n err.textContent = data.message || 'Google OAuth is not configured. Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET.';\n err.classList.add('show');\n btn.disabled = false;\n }\n } catch (e) {\n err.textContent = 'Failed to connect. Please try again.';\n err.classList.add('show');\n btn.disabled = false;\n }\n }\n</script>\n</body>\n</html>`;\n\n/**\n * Create an auth plugin that uses Google OAuth for authentication.\n *\n * When a user visits the app unauthenticated, they see a \"Sign in with Google\"\n * page. The Google OAuth callback (handled by the template) creates a session\n * tied to the user's Google email. `getSession()` then returns `{ email }` for\n * all subsequent requests.\n *\n * Better Auth handles Google OAuth internally when GOOGLE_CLIENT_ID and\n * GOOGLE_CLIENT_SECRET are set. The template's callback route at\n * /_agent-native/google/callback handles mobile deep linking.\n *\n * Usage in a template's `server/plugins/auth.ts`:\n * ```ts\n * import { createGoogleAuthPlugin } from \"@agent-native/core/server\";\n * export default createGoogleAuthPlugin();\n * ```\n */\nexport function createGoogleAuthPlugin(\n options?: GoogleAuthPluginOptions,\n): NitroPluginDef {\n return createAuthPlugin({\n publicPaths: [\n \"/_agent-native/google/callback\",\n \"/_agent-native/google/auth-url\",\n \"/_agent-native/auth/ba\",\n ...(options?.publicPaths ?? []),\n ],\n loginHtml: GOOGLE_LOGIN_HTML,\n });\n}\n"]}
1
+ {"version":3,"file":"google-auth-plugin.js","sourceRoot":"","sources":["../../src/server/google-auth-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AASpD,MAAM,iBAAiB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAwNlB,CAAC;AAET;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAiC;IAEjC,OAAO,gBAAgB,CAAC;QACtB,WAAW,EAAE;YACX,gCAAgC;YAChC,gCAAgC;YAChC,wBAAwB;YACxB,GAAG,CAAC,OAAO,EAAE,WAAW,IAAI,EAAE,CAAC;SAChC;QACD,SAAS,EAAE,iBAAiB;KAC7B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { createAuthPlugin } from \"./auth-plugin.js\";\n\ntype NitroPluginDef = (nitroApp: any) => void | Promise<void>;\n\nexport interface GoogleAuthPluginOptions {\n /** Additional paths accessible without authentication */\n publicPaths?: string[];\n}\n\nconst GOOGLE_LOGIN_HTML = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\">\n<title>Sign in</title>\n<style>\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n background: #0a0a0a;\n color: #e5e5e5;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n .card {\n width: 100%;\n max-width: 360px;\n padding: 2rem;\n background: #141414;\n border: 1px solid rgba(255,255,255,0.08);\n border-radius: 12px;\n text-align: center;\n }\n h1 { font-size: 1.125rem; font-weight: 600; margin-bottom: 0.5rem; color: #fff; }\n .subtitle { font-size: 0.8125rem; color: #888; margin-bottom: 1.5rem; }\n button {\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 0.625rem;\n padding: 0.625rem;\n background: #fff;\n color: #000;\n border: none;\n border-radius: 8px;\n font-size: 0.9375rem;\n font-weight: 500;\n cursor: pointer;\n }\n button:hover { opacity: 0.85; }\n button:disabled { opacity: 0.5; cursor: wait; }\n .error { margin-top: 0.75rem; font-size: 0.8125rem; color: #f87171; display: none; }\n .error.show { display: block; }\n .debug {\n display: none;\n margin-top: 0.625rem;\n font-size: 0.6875rem;\n line-height: 1.45;\n color: #777;\n word-break: break-word;\n }\n .debug.show { display: block; }\n svg { width: 18px; height: 18px; }\n</style>\n</head>\n<body>\n<div class=\"card\">\n <h1>Sign in</h1>\n <p class=\"subtitle\">Continue with your Google account</p>\n <button id=\"btn\" onclick=\"signIn()\">\n <svg viewBox=\"0 0 24 24\"><path fill=\"#4285F4\" d=\"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z\"/><path fill=\"#34A853\" d=\"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z\"/><path fill=\"#FBBC05\" d=\"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z\"/><path fill=\"#EA4335\" d=\"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z\"/></svg>\n Sign in with Google\n </button>\n <p class=\"error\" id=\"err\"></p>\n <p class=\"debug\" id=\"debug\"></p>\n</div>\n<script>\n function __anBasePath() {\n var marker = '/_agent-native';\n var idx = window.location.pathname.indexOf(marker);\n return idx > 0 ? window.location.pathname.slice(0, idx) : '';\n }\n function __anPath(path) {\n return __anBasePath() + path;\n }\n function __anIsBuilderPreview() {\n try {\n var params = new URLSearchParams(window.location.search);\n if (params.has('builder.preview') || params.has('builder.frameEditing') || params.has('__builder_editing__')) return true;\n } catch(e) {}\n try {\n var ref = document.referrer || '';\n return ref.indexOf('builder.io') !== -1 || ref.indexOf('builder.my') !== -1 || ref.indexOf('builderio.xyz') !== -1;\n } catch(e) {\n return false;\n }\n }\n var __anOAuthPollTimer = null;\n var __anOAuthPollCount = 0;\n function __anNewOAuthFlowId() {\n try {\n if (window.crypto && typeof window.crypto.randomUUID === 'function') {\n return window.crypto.randomUUID();\n }\n } catch(e) {}\n return 'builder-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2);\n }\n function __anFlowDebugId(flowId) {\n return flowId ? String(flowId).slice(-10) : '';\n }\n function __anSetOAuthDebug(message, flowId) {\n var text = message + (flowId ? ' (flow ' + __anFlowDebugId(flowId) + ')' : '');\n try {\n console.info('[agent-native][google-oauth]', { message: message, flow: __anFlowDebugId(flowId) || undefined });\n } catch(e) {}\n var debug = document.getElementById('debug');\n if (debug) {\n debug.textContent = text;\n debug.classList.add('show');\n }\n }\n function __anShowOAuthError(err, btn, message) {\n if (__anOAuthPollTimer) {\n clearInterval(__anOAuthPollTimer);\n __anOAuthPollTimer = null;\n }\n err.textContent = message;\n err.classList.add('show');\n btn.disabled = false;\n }\n function __anWaitForOAuthExchange(flowId, ret, btn, err) {\n var started = Date.now();\n var timeoutMs = 5 * 60 * 1000;\n __anOAuthPollCount = 0;\n async function check() {\n __anOAuthPollCount++;\n try {\n var res = await fetch(__anPath('/_agent-native/auth/desktop-exchange') + '?flow_id=' + encodeURIComponent(flowId), { credentials: 'include' });\n var data = await res.json().catch(function() { return {}; });\n if (data && (data.email || data.token)) {\n if (__anOAuthPollTimer) clearInterval(__anOAuthPollTimer);\n __anOAuthPollTimer = null;\n __anSetOAuthDebug('OAuth exchange redeemed; returning to the app', flowId);\n window.location.href = ret || '/';\n return;\n }\n if (data && data.error) {\n __anSetOAuthDebug('OAuth exchange returned an error: ' + (data.message || data.error), flowId);\n __anShowOAuthError(err, btn, data.message || data.error);\n return;\n }\n if (data && data.pending && (__anOAuthPollCount === 1 || __anOAuthPollCount % 5 === 0)) {\n __anSetOAuthDebug('Waiting for the Google callback; polling attempt ' + __anOAuthPollCount, flowId);\n }\n } catch(e) {\n if (__anOAuthPollCount === 1 || __anOAuthPollCount % 5 === 0) {\n __anSetOAuthDebug('Could not reach the OAuth exchange endpoint: ' + (e && e.message ? e.message : 'network error'), flowId);\n }\n }\n if (Date.now() - started > timeoutMs) {\n __anShowOAuthError(err, btn, 'Google sign-in did not finish. Flow ' + __anFlowDebugId(flowId) + ' never redeemed; check server logs for [agent-native][google-oauth].');\n }\n }\n if (__anOAuthPollTimer) clearInterval(__anOAuthPollTimer);\n __anOAuthPollTimer = setInterval(check, 1000);\n setTimeout(check, 500);\n }\n function __anStartBuilderOAuth(ret, btn, err) {\n var flowId = __anNewOAuthFlowId();\n var params = new URLSearchParams();\n if (ret) params.set('return', ret);\n params.set('desktop', '1');\n params.set('flow_id', flowId);\n params.set('redirect', '1');\n var url = __anPath('/_agent-native/google/auth-url') + '?' + params.toString();\n try { sessionStorage.setItem('__an_signin', '1'); } catch(e) {}\n __anSetOAuthDebug('Opening Google sign-in popup', flowId);\n try {\n var popup = window.open(url, '_blank', 'noopener,noreferrer,width=640,height=760');\n if (!popup) {\n __anShowOAuthError(err, btn, 'Google popup was blocked. Allow popups for this site and try again (flow ' + __anFlowDebugId(flowId) + ').');\n return;\n }\n __anSetOAuthDebug('Google popup opened; waiting for callback', flowId);\n } catch(e) {\n __anShowOAuthError(err, btn, 'Could not open Google popup for flow ' + __anFlowDebugId(flowId) + ': ' + (e && e.message ? e.message : 'unknown error'));\n return;\n }\n __anWaitForOAuthExchange(flowId, ret, btn, err);\n }\n function __anOpenOAuthUrl(url) {\n try { sessionStorage.setItem('__an_signin', '1'); } catch(e) {}\n window.location.href = url;\n }\n async function signIn() {\n var btn = document.getElementById('btn');\n var err = document.getElementById('err');\n var ret = window.location.pathname + window.location.search;\n btn.disabled = true;\n err.classList.remove('show');\n if (__anIsBuilderPreview()) {\n __anStartBuilderOAuth(ret, btn, err);\n return;\n }\n try {\n var res = await fetch(__anPath('/_agent-native/google/auth-url') + '?return=' + encodeURIComponent(ret));\n var data = await res.json();\n if (data.url) {\n __anOpenOAuthUrl(data.url);\n } else {\n err.textContent = data.message || 'Google OAuth is not configured. Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET.';\n err.classList.add('show');\n btn.disabled = false;\n }\n } catch (e) {\n err.textContent = 'Failed to connect. Please try again.';\n err.classList.add('show');\n btn.disabled = false;\n }\n }\n</script>\n</body>\n</html>`;\n\n/**\n * Create an auth plugin that uses Google OAuth for authentication.\n *\n * When a user visits the app unauthenticated, they see a \"Sign in with Google\"\n * page. The Google OAuth callback (handled by the template) creates a session\n * tied to the user's Google email. `getSession()` then returns `{ email }` for\n * all subsequent requests.\n *\n * Better Auth handles Google OAuth internally when GOOGLE_CLIENT_ID and\n * GOOGLE_CLIENT_SECRET are set. The template's callback route at\n * /_agent-native/google/callback handles mobile deep linking.\n *\n * Usage in a template's `server/plugins/auth.ts`:\n * ```ts\n * import { createGoogleAuthPlugin } from \"@agent-native/core/server\";\n * export default createGoogleAuthPlugin();\n * ```\n */\nexport function createGoogleAuthPlugin(\n options?: GoogleAuthPluginOptions,\n): NitroPluginDef {\n return createAuthPlugin({\n publicPaths: [\n \"/_agent-native/google/callback\",\n \"/_agent-native/google/auth-url\",\n \"/_agent-native/auth/ba\",\n ...(options?.publicPaths ?? []),\n ],\n loginHtml: GOOGLE_LOGIN_HTML,\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"google-oauth.d.ts","sourceRoot":"","sources":["../../src/server/google-oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAKL,KAAK,OAAO,EACb,MAAM,IAAI,CAAC;AA6CZ;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAElD;AAED,2DAA2D;AAC3D,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAEhD;AAsBD;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAsBhD;AASD,uEAAuE;AACvE,wBAAgB,cAAc,IAAI,MAAM,CAIvC;AAED,sEAAsE;AACtE,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,SAAM,GAAG,MAAM,CAG5D;AAgED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,yBAAyB,CACvC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,OAAO,GACb,OAAO,CAqCT;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,OAAO,EACd,WAAW,SAAmC,GAC7C,MAAM,GAAG,IAAI,CAMf;AAID,MAAM,WAAW,iBAAiB;IAChC,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,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E,MAAM,GAClB,iBAAiB,CAqCnB;AAID,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,oBAAoB,EAAE,OAAO,CAAC;CAC/B;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CACrC,KAAK,EAAE,OAAO,EACd,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,gBAAgB,CAAC,CAQ3B;AAED,MAAM,WAAW,kBAAkB;IACjC,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;CAClC;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CACtC,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,MAAM,EACb,IAAI,EAAE;IACJ,oBAAoB,EAAE,OAAO,CAAC;IAC9B,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GACA,OAAO,CAAC,kBAAkB,CAAC,CA2B7B;AAID;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,MAAM,EACb,IAAI,EAAE;IACJ,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,GACA,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC,CA4FpE;AAED;;;kEAGkE;AAClE,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ,CAMxD;AAED,wBAAgB,wBAAwB,CACtC,OAAO,SAA4B,GAClC,QAAQ,CAKV"}
@@ -25,8 +25,14 @@ function htmlResponse(html, status = 200) {
25
25
  * check icon above the message, with a little breathing room between the
26
26
  * headline and secondary line. Used by every template that goes through the
27
27
  * shared Google OAuth flow. */
28
- function oauthSuccessCloseTabHtml(headline, footnote) {
29
- return `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Connected</title></head><body style="background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column"><svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-bottom:14px" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M9 12l2 2l4 -4"/></svg><p style="font-size:16px;margin:0 0 12px 0">${headline}</p><p style="font-size:13px;color:#888;margin:0">${footnote}</p><script>setTimeout(function(){try{window.close()}catch(e){}},250)</script></body></html>`;
28
+ function oauthDebugFlowId(flowId) {
29
+ return flowId ? flowId.slice(-10) : undefined;
30
+ }
31
+ function oauthSuccessCloseTabHtml(headline, footnote, debugFlowId) {
32
+ const debug = debugFlowId
33
+ ? `<p style="font-size:11px;color:#555;margin:12px 0 0 0">Debug flow: ${escapeHtml(debugFlowId)}</p>`
34
+ : "";
35
+ return `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Connected</title></head><body style="background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column"><svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-bottom:14px" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M9 12l2 2l4 -4"/></svg><p style="font-size:16px;margin:0 0 12px 0">${headline}</p><p style="font-size:13px;color:#888;margin:0">${footnote}</p>${debug}<script>console.info("[agent-native][google-oauth] success page loaded",{flow:${JSON.stringify(debugFlowId || null)}});setTimeout(function(){try{window.close()}catch(e){}},250)</script></body></html>`;
30
36
  }
31
37
  /**
32
38
  * HTML escape — minimal but covers the cases that matter when interpolating
@@ -447,7 +453,7 @@ export function oauthCallbackResponse(event, email, opts) {
447
453
  const safeEmail = email ? escapeHtml(email) : "";
448
454
  const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));
449
455
  const msg = safeEmail ? `Connected ${safeEmail}!` : "Connected!";
450
- return htmlResponse(oauthSuccessCloseTabHtml(msg, `You can close this tab and return to ${safeAppName}.`));
456
+ return htmlResponse(oauthSuccessCloseTabHtml(msg, `You can close this tab and return to ${safeAppName}.`, oauthDebugFlowId(opts.flowId)));
451
457
  }
452
458
  // Electron desktop exchange flow: mail/calendar still pass a flow id so the
453
459
  // renderer can poll as a fallback, but the main handoff should use the
@@ -461,7 +467,7 @@ export function oauthCallbackResponse(event, email, opts) {
461
467
  const safeEmail = email ? escapeHtml(email) : "";
462
468
  const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));
463
469
  const msg = safeEmail ? `Signed in as ${safeEmail}!` : "Signed in!";
464
- return htmlResponse(oauthSuccessCloseTabHtml(msg, `You can close this tab and return to ${safeAppName}.`));
470
+ return htmlResponse(oauthSuccessCloseTabHtml(msg, `You can close this tab and return to ${safeAppName}.`, oauthDebugFlowId(opts.flowId)));
465
471
  }
466
472
  // Desktop login: deep link back to Electron app — only when the callback
467
473
  // request actually carries the AgentNativeDesktop UA marker. Without this
@@ -1 +1 @@
1
- {"version":3,"file":"google-oauth.js","sourceRoot":"","sources":["../../src/server/google-oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,SAAS,EACT,QAAQ,EACR,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,IAAI,CAAC;AACZ,OAAO,EACL,UAAU,EACV,UAAU,EACV,gBAAgB,EAChB,cAAc,EACd,yBAAyB,GAC1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnD,+EAA+E;AAE/E;;oDAEoD;AACpD,SAAS,YAAY,C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CAAC;IACjC,OAAO,MAAM;QACX,CAAC,CAAC,gCAAgC,MAAM,EAAE;QAC1C,CAAC,CAAC,8BAA8B,CAAC;AACrC,CAAC;AAED,SAAS,kBAAkB,CACzB,MAAe,EACf,KAAc,EACd,YAAqB,EACrB,KAAc;IAEd,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACjD,MAAM,GAAG,GAAG,SAAS,CAAC,CAAC,CAAC,aAAa,SAAS,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC;IACjE,IAAI,YAAY,EAAE,CAAC;QACjB,MAAM,QAAQ,GAAG,0BAA0B,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;QACjE,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QAC9C,wEAAwE;QACxE,yEAAyE;QACzE,qEAAqE;QACrE,qEAAqE;QACrE,yEAAyE;QACzE,OAAO,YAAY,CACjB,isBAAisB,GAAG,2FAA2F,YAAY,2bAA2b,YAAY,4KAA4K,CAC/5C,CAAC;IACJ,CAAC;IACD,OAAO,YAAY,CACjB,wBAAwB,CACtB,GAAG,EACH,oDAAoD,CACrD,CACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared Google OAuth utilities for all templates.\n *\n * Handles platform detection (desktop/mobile), state encoding,\n * session token creation, and deep-link responses — the logic\n * that was previously copy-pasted across every template's\n * google-auth.ts handler.\n */\n\nimport crypto from \"node:crypto\";\nimport {\n getHeader,\n getQuery,\n setResponseStatus,\n setResponseHeader,\n type H3Event,\n} from \"h3\";\nimport {\n addSession,\n getSession,\n getSessionMaxAge,\n safeReturnPath,\n setFrameworkSessionCookie,\n} from \"./auth.js\";\nimport { getAppName } from \"./app-name.js\";\nimport { writeDesktopSso } from \"./desktop-sso.js\";\n\n// ─── Platform Detection ─────────────────────────────────────────────────────\n\n/** Return an HTML response with the correct Content-Type.\n * Uses a web-standard Response to ensure the header survives\n * Nitro dev mode's mock-node-response pipeline. */\nfunction htmlResponse(html: string, status = 200): Response {\n return new Response(html, {\n status,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Shared markup for OAuth success \"close this tab\" pages. Renders a green\n * check icon above the message, with a little breathing room between the\n * headline and secondary line. Used by every template that goes through the\n * shared Google OAuth flow. */\nfunction oauthSuccessCloseTabHtml(headline: string, footnote: string): string {\n return `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#22c55e\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M9 12l2 2l4 -4\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0\">${headline}</p><p style=\"font-size:13px;color:#888;margin:0\">${footnote}</p><script>setTimeout(function(){try{window.close()}catch(e){}},250)</script></body></html>`;\n}\n\n/**\n * HTML escape — minimal but covers the cases that matter when interpolating\n * user-controlled values into our OAuth callback HTML. Mirrors the helper in\n * email-template.ts; kept inline here to avoid a circular import.\n */\nfunction escapeHtml(s: string): string {\n return String(s ?? \"\")\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/**\n * Detect requests from the Agent Native desktop app specifically.\n *\n * The desktop app appends `AgentNativeDesktop/<version>` to its user-agent\n * (see `packages/desktop-app/src/main/index.ts`). We check for that marker\n * rather than matching generic `Electron`, which would also match other\n * Electron-based webviews like Builder.io's Fusion, Slack desktop, Discord,\n * etc. Falsely treating those as \"the desktop app\" sends users to the\n * `agentnative://oauth-complete` deep-link success page after Google sign-in,\n * where the protocol handler can't fire and the \"Open Agent Native\" button\n * does nothing.\n *\n * Kept exported as `isElectron` for backwards compatibility with consumers.\n */\nexport function isElectron(event: H3Event): boolean {\n return /AgentNativeDesktop/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/** Detect requests from a mobile browser (iOS/Android). */\nexport function isMobile(event: H3Event): boolean {\n return /iPhone|iPad|iPod|Android/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/**\n * Build the static allowlist of origins we trust for `getOrigin`. Reads\n * `APP_URL` and `BETTER_AUTH_URL` (both are deployment-known public URLs).\n * Each entry is normalised to `${proto}://${host}` (no path). Duplicates\n * collapse, invalid entries are dropped silently.\n */\nfunction getConfiguredOriginAllowlist(): Set<string> {\n const out = new Set<string>();\n for (const raw of [process.env.APP_URL, process.env.BETTER_AUTH_URL]) {\n if (!raw) continue;\n try {\n const u = new URL(raw);\n out.add(`${u.protocol}//${u.host}`);\n } catch {\n // Ignore — env value isn't a parseable URL.\n }\n }\n return out;\n}\n\n/**\n * Get the origin from forwarded headers or Host.\n *\n * Defends against Host-header injection: in production we require the\n * resolved origin to match `APP_URL` / `BETTER_AUTH_URL`, falling back to\n * those values when the inbound headers are missing or don't match. In\n * dev we accept the inbound `Host` so localhost / ngrok / preview hosts\n * keep working without configuration. The protocol defaults to `https`\n * in production (so a TLS-terminating proxy that drops `x-forwarded-proto`\n * doesn't downgrade us to plain HTTP).\n */\nexport function getOrigin(event: H3Event): string {\n const headerHost =\n getHeader(event, \"x-forwarded-host\") || getHeader(event, \"host\");\n const isProd = process.env.NODE_ENV === \"production\";\n const headerProto =\n getHeader(event, \"x-forwarded-proto\") || (isProd ? \"https\" : \"http\");\n\n if (isProd) {\n const allow = getConfiguredOriginAllowlist();\n // If the deploy declares its public URL, prefer it over inbound headers.\n if (allow.size > 0) {\n const inbound = headerHost ? `${headerProto}://${headerHost}` : \"\";\n if (inbound && allow.has(inbound)) return inbound;\n // Inbound didn't match — fall back to the first configured origin.\n return [...allow][0];\n }\n // No allowlist configured: still default to https, but accept the\n // inbound Host (best we can do without a configured base URL).\n return `${headerProto}://${headerHost ?? \"\"}`;\n }\n\n return `${headerProto}://${headerHost ?? \"localhost\"}`;\n}\n\nfunction normalizeAppBasePath(value: string | undefined): string {\n if (!value || value === \"/\") return \"\";\n const trimmed = value.trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return `/${trimmed.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\")}`;\n}\n\n/** App mount prefix, if the template is served under APP_BASE_PATH. */\nexport function getAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\n/** Build an absolute same-origin URL that preserves APP_BASE_PATH. */\nexport function getAppUrl(event: H3Event, path = \"/\"): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${getOrigin(event)}${getAppBasePath()}${cleanPath}`;\n}\n\nfunction isWorkspaceOAuthCallbackRelayEnabled(): boolean {\n return (\n process.env.AGENT_NATIVE_WORKSPACE === \"1\" ||\n process.env.VITE_AGENT_NATIVE_WORKSPACE === \"1\"\n );\n}\n\nfunction isFrameworkOAuthCallbackPath(pathname: string): boolean {\n return (\n pathname.startsWith(\"/_agent-native/\") &&\n (pathname.endsWith(\"/callback\") || pathname.includes(\"/callback/\"))\n );\n}\n\nfunction getOriginalRequestPath(event: H3Event): string {\n const mountedPathname = (event as any).context?._mountedPathname;\n if (typeof mountedPathname === \"string\" && mountedPathname) {\n return mountedPathname;\n }\n\n const urlPathname = (event as any).url?.pathname;\n if (typeof urlPathname === \"string\" && urlPathname) return urlPathname;\n\n const nodeUrl = event.node?.req?.url;\n if (typeof nodeUrl === \"string\" && nodeUrl) {\n const queryStart = nodeUrl.indexOf(\"?\");\n return queryStart >= 0 ? nodeUrl.slice(0, queryStart) : nodeUrl;\n }\n\n const eventPath = (event as any).path;\n if (typeof eventPath === \"string\" && eventPath) {\n const queryStart = eventPath.indexOf(\"?\");\n return queryStart >= 0 ? eventPath.slice(0, queryStart) : eventPath;\n }\n\n return \"/\";\n}\n\nfunction isRequestUnderAppBasePath(event: H3Event): boolean {\n const basePath = getAppBasePath();\n if (!basePath) return false;\n const requestPath = getOriginalRequestPath(event);\n return (\n requestPath === `${basePath}/_agent-native` ||\n requestPath.startsWith(`${basePath}/_agent-native/`)\n );\n}\n\nfunction getDefaultOAuthRedirectUrl(event: H3Event, path: string): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n if (\n isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(cleanPath)\n ) {\n return `${getOrigin(event)}${cleanPath}`;\n }\n const basePath = isRequestUnderAppBasePath(event) ? getAppBasePath() : \"\";\n return `${getOrigin(event)}${basePath}${cleanPath}`;\n}\n\n// ─── redirect_uri Allowlist ──────────────────────────────────────────────────\n\n/**\n * Validate a user-supplied `redirect_uri` for OAuth flows.\n *\n * Defends against authorization-code interception (RFC 6819 §4.4.1.7):\n * even though the upstream provider (Google/Atlassian/Zoom) refuses\n * unregistered redirect URIs, prefix-style registrations and side\n * registrations on the same host let a malicious caller swap in an\n * attacker-controlled URI that the provider still accepts. We reject any\n * candidate that isn't on this server's own origin AND under the\n * framework's `/_agent-native/` namespace. Returns the validated URI on\n * success, or `undefined` on rejection — callers must treat `undefined`\n * as a 400.\n *\n * The intentional shape is exact-prefix:\n * - Origin must equal `getOrigin(event)` — no Host-header injection\n * reusing somebody else's registered redirect URI.\n * - Path must start with `${appBasePath}/_agent-native/` so we never\n * hand auth codes to a public marketing or open-redirect endpoint\n * on the same registered host.\n *\n * For desktop / native flows that need ephemeral `http://127.0.0.1:<port>`\n * loopback URIs, callers should validate those at the template level\n * with a dedicated allowlist — this helper rejects them by design.\n */\nexport function isAllowedOAuthRedirectUri(\n candidate: string,\n event: H3Event,\n): boolean {\n if (typeof candidate !== \"string\" || candidate.length === 0) return false;\n let url: URL;\n try {\n url = new URL(candidate);\n } catch {\n return false;\n }\n // Must be same origin as our server.\n const expectedOrigin = getOrigin(event);\n let expectedUrl: URL;\n try {\n expectedUrl = new URL(expectedOrigin);\n } catch {\n return false;\n }\n if (url.protocol !== expectedUrl.protocol) return false;\n if (url.host !== expectedUrl.host) return false;\n // Must live under the framework's namespace. Workspace deploys can route\n // root /_agent-native/* to Dispatch even when Dispatch itself is mounted at\n // /dispatch, but app-prefixed requests should not be able to swap their\n // callback to that root namespace.\n const basePath = getAppBasePath();\n const allowedPrefixes =\n basePath && isRequestUnderAppBasePath(event)\n ? [\n `${basePath}/_agent-native/`,\n ...(isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(url.pathname)\n ? [\"/_agent-native/\"]\n : []),\n ]\n : [\"/_agent-native/\"];\n if (!allowedPrefixes.some((prefix) => url.pathname.startsWith(prefix))) {\n return false;\n }\n return true;\n}\n\n/**\n * Resolve the `redirect_uri` for an outbound OAuth `auth-url` request.\n *\n * Reads `?redirect_uri=` from the query and validates it via\n * `isAllowedOAuthRedirectUri`. Returns:\n * - the validated URI when supplied and allowed, OR\n * - the framework default when no override was supplied, OR\n * - `null` when an override was supplied but rejected — callers must\n * respond with 400 in that case.\n *\n * Templates that need a non-default redirect path can pass it via\n * `defaultPath` (e.g. `\"/_agent-native/google/desktop-callback\"` for\n * desktop flows).\n */\nexport function resolveOAuthRedirectUri(\n event: H3Event,\n defaultPath = \"/_agent-native/google/callback\",\n): string | null {\n const supplied = getQuery(event).redirect_uri;\n if (typeof supplied === \"string\" && supplied.length > 0) {\n return isAllowedOAuthRedirectUri(supplied, event) ? supplied : null;\n }\n return getDefaultOAuthRedirectUrl(event, defaultPath);\n}\n\n// ─── OAuth State ─────────────────────────────────────────────────────────────\n\nexport interface OAuthStatePayload {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n /**\n * Same-origin path to redirect to after a successful web-flow sign-in.\n * Threaded through the (HMAC-signed) state so it survives the round trip\n * to Google. Validated again on decode via safeReturnPath as defence in\n * depth. Has no effect on desktop / mobile / add-account flows, which\n * use their own deep-link / close-tab handling.\n */\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Ephemeral in-memory state-signing key for development. Generated lazily\n * on first read so dev sessions don't depend on filesystem writability or\n * env-var configuration. Sessions reset on each restart, which is fine\n * for dev — no real users / production data are involved.\n */\nlet _devStateSigningKey: string | undefined;\n\n/**\n * Derive a server-only signing key for HMAC verification of OAuth state.\n *\n * Uses a dedicated secret — never an OAuth client secret. Reusing a\n * client_secret (which is shared with Google / GitHub / Atlassian) as our\n * own HMAC key conflates two trust domains: rotating the client secret\n * silently invalidates every in-flight OAuth state, and any leak of the\n * client secret also lets an attacker forge our state envelopes.\n *\n * Resolution order:\n * 1. OAUTH_STATE_SECRET (preferred — dedicated to this purpose)\n * 2. BETTER_AUTH_SECRET (already used by Better Auth as a server secret)\n * 3. In dev only, an ephemeral random key (per-process)\n *\n * In production, throws if neither secret is set.\n */\nfunction getStateSigningKey(): string {\n const secret =\n process.env.OAUTH_STATE_SECRET || process.env.BETTER_AUTH_SECRET;\n if (secret) return secret;\n\n const isProd = process.env.NODE_ENV === \"production\";\n if (isProd) {\n throw new Error(\n \"OAuth state signing requires a server secret. \" +\n \"Set OAUTH_STATE_SECRET or BETTER_AUTH_SECRET in production.\",\n );\n }\n\n if (!_devStateSigningKey) {\n _devStateSigningKey = crypto.randomBytes(32).toString(\"hex\");\n }\n return _devStateSigningKey;\n}\n\n/**\n * Options for the named-argument form of {@link encodeOAuthState}.\n * Prefer this form — the positional overload is easy to misuse (the mail\n * and calendar templates historically passed `flowId` in the `returnUrl`\n * slot, smuggling state into a defence-in-depth path).\n */\nexport interface EncodeOAuthStateOptions {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Encode OAuth state into a signed base64url string.\n * The state is HMAC-signed so the callback can verify it wasn't forged,\n * preventing CSRF attacks on the OAuth flow.\n *\n * Two call shapes are supported:\n * - Recommended: pass an options object — clear, mismatch-proof.\n * `encodeOAuthState({ redirectUri, owner, desktop, ... })`\n * - Legacy positional form (kept working for backward compatibility):\n * `encodeOAuthState(redirectUri, owner, desktop, addAccount, app, returnUrl, flowId)`.\n * Callers should migrate to the options form — see the audit on\n * templates/mail and templates/calendar where the positional shape\n * led to `flowId` being smuggled in via the `returnUrl` slot.\n */\nexport function encodeOAuthState(opts: EncodeOAuthStateOptions): string;\nexport function encodeOAuthState(\n redirectUri: string,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string;\nexport function encodeOAuthState(\n redirectUriOrOpts: string | EncodeOAuthStateOptions,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string {\n const opts: EncodeOAuthStateOptions =\n typeof redirectUriOrOpts === \"string\"\n ? {\n redirectUri: redirectUriOrOpts,\n owner,\n desktop,\n addAccount,\n app,\n returnUrl,\n flowId,\n }\n : redirectUriOrOpts;\n\n const nonce = crypto.randomBytes(8).toString(\"hex\");\n const payload: Record<string, string | boolean> = {\n n: nonce,\n r: opts.redirectUri,\n };\n if (opts.owner) payload.o = opts.owner;\n if (opts.desktop) payload.d = true;\n if (opts.addAccount) payload.a = true;\n if (opts.app) payload.app = opts.app;\n if (opts.returnUrl) payload.r2 = opts.returnUrl;\n if (opts.flowId) payload.f = opts.flowId;\n const data = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n const sig = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n return `${data}.${sig}`;\n}\n\n/**\n * Decode and verify OAuth state from the callback's state query parameter.\n * Rejects forged or tampered state by checking the HMAC signature.\n * Falls back to the provided URI if decoding or verification fails.\n */\nexport function decodeOAuthState(\n stateParam: string | undefined,\n fallbackUri: string,\n): OAuthStatePayload {\n if (stateParam) {\n try {\n const dotIdx = stateParam.lastIndexOf(\".\");\n if (dotIdx === -1) return { redirectUri: fallbackUri };\n\n const data = stateParam.slice(0, dotIdx);\n const sig = stateParam.slice(dotIdx + 1);\n const expected = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n\n if (\n sig.length !== expected.length ||\n !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))\n ) {\n return { redirectUri: fallbackUri };\n }\n\n const parsed = JSON.parse(Buffer.from(data, \"base64url\").toString());\n return {\n redirectUri: parsed.r || fallbackUri,\n owner: parsed.o || undefined,\n desktop: !!parsed.d,\n addAccount: !!parsed.a,\n app: typeof parsed.app === \"string\" ? parsed.app : undefined,\n // Pass returnUrl through as-is — same-origin validation runs at the\n // consumer (oauthCallbackResponse → safeReturnPath). The state is\n // HMAC-signed, but we still validate at consumption as defence in\n // depth in case the signing key ever leaks.\n returnUrl: typeof parsed.r2 === \"string\" ? parsed.r2 : undefined,\n flowId: parsed.f || undefined,\n };\n } catch {}\n }\n return { redirectUri: fallbackUri };\n}\n\n// ─── Session Creation ────────────────────────────────────────────────────────\n\nexport interface OAuthOwnerResult {\n owner: string | undefined;\n hasProductionSession: boolean;\n}\n\n/**\n * Determine the token owner from the current session and OAuth state.\n * Call this BEFORE exchangeCode to get the owner parameter.\n */\nexport async function resolveOAuthOwner(\n event: H3Event,\n stateOwner?: string,\n): Promise<OAuthOwnerResult> {\n const existingSession = await getSession(event);\n const hasProductionSession = !!existingSession?.email;\n const owner = hasProductionSession\n ? existingSession!.email\n : stateOwner || undefined;\n\n return { owner, hasProductionSession };\n}\n\nexport interface OAuthSessionResult {\n sessionToken: string | undefined;\n}\n\n/**\n * Create a session token after a successful OAuth exchange.\n *\n * Desktop and mobile apps have separate cookie jars from the system\n * browser, so they always get a fresh session token (even if the browser\n * already has one). The token is then passed via deep link so the native\n * app can inject it.\n */\nexport async function createOAuthSession(\n event: H3Event,\n email: string,\n opts: {\n hasProductionSession: boolean;\n desktop?: boolean;\n },\n): Promise<OAuthSessionResult> {\n const mobile = isMobile(event);\n const needsDeepLink = opts.desktop || mobile;\n const maxAge = getSessionMaxAge();\n\n let sessionToken: string | undefined;\n if (!opts.hasProductionSession || needsDeepLink) {\n sessionToken = crypto.randomBytes(32).toString(\"hex\");\n await addSession(sessionToken, email);\n setFrameworkSessionCookie(event, sessionToken);\n // Desktop SSO: record this session in the home-dir broker file so\n // sibling templates (each with its own database) can resolve the\n // same token without a DB row of their own. Only the PRIMARY\n // sign-in writes the broker — if a production session already\n // exists, this is an add-account flow (connecting a secondary\n // Google account for scraping) and must never switch the active\n // user across sibling templates.\n if (opts.desktop && !opts.hasProductionSession) {\n await writeDesktopSso({\n email,\n token: sessionToken,\n expiresAt: Date.now() + maxAge * 1000,\n });\n }\n }\n\n return { sessionToken };\n}\n\n// ─── Callback Responses ──────────────────────────────────────────────────────\n\n/**\n * Return the appropriate response after a successful OAuth callback.\n *\n * Handles mobile deep links, desktop deep links, add-account close-tab\n * pages, and plain web redirects — so templates don't have to.\n */\nexport function oauthCallbackResponse(\n event: H3Event,\n email: string,\n opts: {\n sessionToken?: string;\n desktop?: boolean;\n addAccount?: boolean;\n /**\n * Same-origin path to return the viewer to after a successful web\n * sign-in. Validated via safeReturnPath; falls back to \"/\" for any\n * shape that escapes same-origin. Has no effect on desktop / mobile\n * / add-account flows — those use their own deep-link handling.\n */\n returnUrl?: string;\n flowId?: string;\n appName?: string;\n },\n): Response | string | unknown | Promise<Response | string | unknown> {\n const mobile = isMobile(event);\n const query = getQuery(event);\n const callbackState =\n typeof query.state === \"string\" && query.state.length > 0\n ? query.state\n : undefined;\n\n // Mobile: deep link back to native app\n if (mobile) {\n const deepLink = buildOAuthCompleteDeepLink(\n opts.sessionToken,\n callbackState,\n );\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\"><title>Connected</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p>Connected! Returning to app…</p><script>window.location.href=${JSON.stringify(deepLink)};setTimeout(function(){window.location.href=\"/\"},1500)</script></body></html>`,\n );\n }\n\n // Desktop add-account: close-tab page (must come before general desktop check\n // to ensure no deep link fires and the existing session is never switched).\n if (opts.desktop && opts.addAccount) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n ),\n );\n }\n\n // Electron desktop exchange flow: mail/calendar still pass a flow id so the\n // renderer can poll as a fallback, but the main handoff should use the\n // protocol deep link so the popup returns focus to the desktop app.\n if (opts.desktop && opts.flowId && isElectron(event) && opts.sessionToken) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Desktop exchange flow (non-Electron tray app): the tray app polls the\n // desktop-exchange endpoint for the token — no deep link needed.\n if (opts.desktop && opts.flowId) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Signed in as ${safeEmail}!` : \"Signed in!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n ),\n );\n }\n\n // Desktop login: deep link back to Electron app — only when the callback\n // request actually carries the AgentNativeDesktop UA marker. Without this\n // check, any client whose OAuth state was minted with `desktop=true` (e.g.\n // a stale link, or an upstream that wrongly set `?desktop=1`) would land\n // on the `agentnative://` page where the deep link can't fire and the\n // \"Open Agent Native\" button does nothing — surfaces inside Builder.io's\n // Fusion webview hit this exact dead-end. Fall through to the web flow\n // for non-Agent-Native-Desktop clients so they get a real redirect.\n if (opts.desktop && isElectron(event)) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Add-account web flow: close-tab page. The email is rendered into the\n // page via DOM `textContent` (safe), but we still JSON-stringify so a\n // payload containing `</script>` can't break out of the script tag —\n // and explicitly assert it's a string so a callbacks like `null` or\n // an object won't end up serialised into the page.\n if (opts.addAccount) {\n const safeEmail = JSON.stringify(typeof email === \"string\" ? email : \"\");\n return htmlResponse(`<!DOCTYPE html><html><body><script>\n window.close();\n var p = document.createElement('p');\n p.style.cssText = 'font-family:system-ui;text-align:center;margin-top:40vh';\n p.textContent = 'Connected ' + ${safeEmail} + '! You can close this tab.';\n document.body.appendChild(p);\n </script></body></html>`);\n }\n\n // Web: redirect to the requested return path (validated same-origin) or\n // \"/\" if no return was supplied / the return failed validation. Returning\n // an empty string body keeps h3's `prepareResponseBody` → `FastResponse`\n // path, which merges the prepared event headers (Location + any cookies\n // set via `setCookie(event, ...)`).\n setResponseStatus(event, 302);\n setResponseHeader(event, \"Location\", safeReturnPath(opts.returnUrl));\n return \"\";\n}\n\n/** HTML error page for OAuth failures. The message is HTML-escaped — most\n * callers pass `error.message` from a token-exchange or userinfo failure,\n * which can echo upstream provider strings (and historically attacker-\n * controlled query params via the `error_description` field). */\nexport function oauthErrorPage(message: string): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connection failed</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;text-align:center\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#ef4444\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M15 9l-6 6\"/><path d=\"M9 9l6 6\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0;color:#ddd\">${safe}</p><p style=\"font-size:13px;color:#888;margin:0\"><a href=\"/\" style=\"color:#888;text-decoration:underline;text-underline-offset:3px\">Back to login</a></p></body></html>`,\n 400,\n );\n}\n\nexport function oauthDesktopExchangePage(\n message = \"Returning to the app...\",\n): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Returning</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p style=\"font-size:14px\">${safe}</p><script>window.close()</script></body></html>`,\n );\n}\n\n// ─── Internal ────────────────────────────────────────────────────────────────\n\nfunction resolveOAuthAppName(explicit?: string): string {\n const raw = explicit || getAppName() || \"Agent Native\";\n if (!/^[a-z0-9_-]+$/.test(raw)) return raw;\n return raw\n .split(/[-_]+/)\n .filter(Boolean)\n .map((word) => word[0].toUpperCase() + word.slice(1))\n .join(\" \");\n}\n\nfunction buildOAuthCompleteDeepLink(\n sessionToken?: string,\n state?: string,\n): string {\n const params = new URLSearchParams();\n if (sessionToken) params.set(\"token\", sessionToken);\n if (state) params.set(\"state\", state);\n const suffix = params.toString();\n return suffix\n ? `agentnative://oauth-complete?${suffix}`\n : \"agentnative://oauth-complete\";\n}\n\nfunction desktopSuccessPage(\n _event: H3Event,\n email?: string,\n sessionToken?: string,\n state?: string,\n): Response {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n if (sessionToken) {\n const deepLink = buildOAuthCompleteDeepLink(sessionToken, state);\n const deepLinkJson = JSON.stringify(deepLink);\n // Defence in depth: if this page somehow gets served to a UA that isn't\n // the Agent Native desktop app (server gate bypassed, stale link, etc.),\n // skip the `agentnative://` deep link entirely and bounce to the app\n // root. The deep link silently fails outside the desktop app and the\n // \"Open Agent Native\" button is a dead end in a generic browser/webview.\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title><style>@keyframes spin{to{transform:rotate(360deg)}}@keyframes fadeIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.spinner{width:28px;height:28px;border:2px solid #333;border-top-color:#fff;border-radius:50%;animation:spin .8s linear infinite}.fallback{display:none;flex-direction:column;align-items:center;gap:8px;animation:fadeIn .2s ease-out}.fallback.show{display:flex}</style></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;gap:16px\"><p style=\"font-size:16px;margin:0\">${msg}</p><div id=\"loading\" class=\"spinner\"></div><div id=\"fallback\" class=\"fallback\"><a href=${deepLinkJson} style=\"display:inline-block;padding:10px 24px;background:#fff;color:#000;border-radius:8px;text-decoration:none;font-size:14px;font-weight:500\">Open Agent Native</a><p style=\"font-size:12px;color:#666;margin:0\">If the app didn\\u2019t open automatically, click the button above.</p></div><script>(function(){var ua=(navigator.userAgent||\"\");if(ua.indexOf(\"AgentNativeDesktop\")===-1){window.location.replace(\"/\");return}window.location.href=${deepLinkJson};setTimeout(function(){document.getElementById(\"loading\").style.display=\"none\";document.getElementById(\"fallback\").classList.add(\"show\")},3000)})()</script></body></html>`,\n );\n }\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n \"You can close this tab and return to Agent Native.\",\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"google-oauth.js","sourceRoot":"","sources":["../../src/server/google-oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,SAAS,EACT,QAAQ,EACR,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,IAAI,CAAC;AACZ,OAAO,EACL,UAAU,EACV,UAAU,EACV,gBAAgB,EAChB,cAAc,EACd,yBAAyB,GAC1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnD,+EAA+E;AAE/E;;oDAEoD;AACpD,SAAS,YAAY,C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ACJ,CAAC","sourcesContent":["/**\n * Shared Google OAuth utilities for all templates.\n *\n * Handles platform detection (desktop/mobile), state encoding,\n * session token creation, and deep-link responses — the logic\n * that was previously copy-pasted across every template's\n * google-auth.ts handler.\n */\n\nimport crypto from \"node:crypto\";\nimport {\n getHeader,\n getQuery,\n setResponseStatus,\n setResponseHeader,\n type H3Event,\n} from \"h3\";\nimport {\n addSession,\n getSession,\n getSessionMaxAge,\n safeReturnPath,\n setFrameworkSessionCookie,\n} from \"./auth.js\";\nimport { getAppName } from \"./app-name.js\";\nimport { writeDesktopSso } from \"./desktop-sso.js\";\n\n// ─── Platform Detection ─────────────────────────────────────────────────────\n\n/** Return an HTML response with the correct Content-Type.\n * Uses a web-standard Response to ensure the header survives\n * Nitro dev mode's mock-node-response pipeline. */\nfunction htmlResponse(html: string, status = 200): Response {\n return new Response(html, {\n status,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Shared markup for OAuth success \"close this tab\" pages. Renders a green\n * check icon above the message, with a little breathing room between the\n * headline and secondary line. Used by every template that goes through the\n * shared Google OAuth flow. */\nfunction oauthDebugFlowId(flowId?: string): string | undefined {\n return flowId ? flowId.slice(-10) : undefined;\n}\n\nfunction oauthSuccessCloseTabHtml(\n headline: string,\n footnote: string,\n debugFlowId?: string,\n): string {\n const debug = debugFlowId\n ? `<p style=\"font-size:11px;color:#555;margin:12px 0 0 0\">Debug flow: ${escapeHtml(debugFlowId)}</p>`\n : \"\";\n return `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#22c55e\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M9 12l2 2l4 -4\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0\">${headline}</p><p style=\"font-size:13px;color:#888;margin:0\">${footnote}</p>${debug}<script>console.info(\"[agent-native][google-oauth] success page loaded\",{flow:${JSON.stringify(debugFlowId || null)}});setTimeout(function(){try{window.close()}catch(e){}},250)</script></body></html>`;\n}\n\n/**\n * HTML escape — minimal but covers the cases that matter when interpolating\n * user-controlled values into our OAuth callback HTML. Mirrors the helper in\n * email-template.ts; kept inline here to avoid a circular import.\n */\nfunction escapeHtml(s: string): string {\n return String(s ?? \"\")\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/**\n * Detect requests from the Agent Native desktop app specifically.\n *\n * The desktop app appends `AgentNativeDesktop/<version>` to its user-agent\n * (see `packages/desktop-app/src/main/index.ts`). We check for that marker\n * rather than matching generic `Electron`, which would also match other\n * Electron-based webviews like Builder.io's Fusion, Slack desktop, Discord,\n * etc. Falsely treating those as \"the desktop app\" sends users to the\n * `agentnative://oauth-complete` deep-link success page after Google sign-in,\n * where the protocol handler can't fire and the \"Open Agent Native\" button\n * does nothing.\n *\n * Kept exported as `isElectron` for backwards compatibility with consumers.\n */\nexport function isElectron(event: H3Event): boolean {\n return /AgentNativeDesktop/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/** Detect requests from a mobile browser (iOS/Android). */\nexport function isMobile(event: H3Event): boolean {\n return /iPhone|iPad|iPod|Android/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/**\n * Build the static allowlist of origins we trust for `getOrigin`. Reads\n * `APP_URL` and `BETTER_AUTH_URL` (both are deployment-known public URLs).\n * Each entry is normalised to `${proto}://${host}` (no path). Duplicates\n * collapse, invalid entries are dropped silently.\n */\nfunction getConfiguredOriginAllowlist(): Set<string> {\n const out = new Set<string>();\n for (const raw of [process.env.APP_URL, process.env.BETTER_AUTH_URL]) {\n if (!raw) continue;\n try {\n const u = new URL(raw);\n out.add(`${u.protocol}//${u.host}`);\n } catch {\n // Ignore — env value isn't a parseable URL.\n }\n }\n return out;\n}\n\n/**\n * Get the origin from forwarded headers or Host.\n *\n * Defends against Host-header injection: in production we require the\n * resolved origin to match `APP_URL` / `BETTER_AUTH_URL`, falling back to\n * those values when the inbound headers are missing or don't match. In\n * dev we accept the inbound `Host` so localhost / ngrok / preview hosts\n * keep working without configuration. The protocol defaults to `https`\n * in production (so a TLS-terminating proxy that drops `x-forwarded-proto`\n * doesn't downgrade us to plain HTTP).\n */\nexport function getOrigin(event: H3Event): string {\n const headerHost =\n getHeader(event, \"x-forwarded-host\") || getHeader(event, \"host\");\n const isProd = process.env.NODE_ENV === \"production\";\n const headerProto =\n getHeader(event, \"x-forwarded-proto\") || (isProd ? \"https\" : \"http\");\n\n if (isProd) {\n const allow = getConfiguredOriginAllowlist();\n // If the deploy declares its public URL, prefer it over inbound headers.\n if (allow.size > 0) {\n const inbound = headerHost ? `${headerProto}://${headerHost}` : \"\";\n if (inbound && allow.has(inbound)) return inbound;\n // Inbound didn't match — fall back to the first configured origin.\n return [...allow][0];\n }\n // No allowlist configured: still default to https, but accept the\n // inbound Host (best we can do without a configured base URL).\n return `${headerProto}://${headerHost ?? \"\"}`;\n }\n\n return `${headerProto}://${headerHost ?? \"localhost\"}`;\n}\n\nfunction normalizeAppBasePath(value: string | undefined): string {\n if (!value || value === \"/\") return \"\";\n const trimmed = value.trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return `/${trimmed.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\")}`;\n}\n\n/** App mount prefix, if the template is served under APP_BASE_PATH. */\nexport function getAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\n/** Build an absolute same-origin URL that preserves APP_BASE_PATH. */\nexport function getAppUrl(event: H3Event, path = \"/\"): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${getOrigin(event)}${getAppBasePath()}${cleanPath}`;\n}\n\nfunction isWorkspaceOAuthCallbackRelayEnabled(): boolean {\n return (\n process.env.AGENT_NATIVE_WORKSPACE === \"1\" ||\n process.env.VITE_AGENT_NATIVE_WORKSPACE === \"1\"\n );\n}\n\nfunction isFrameworkOAuthCallbackPath(pathname: string): boolean {\n return (\n pathname.startsWith(\"/_agent-native/\") &&\n (pathname.endsWith(\"/callback\") || pathname.includes(\"/callback/\"))\n );\n}\n\nfunction getOriginalRequestPath(event: H3Event): string {\n const mountedPathname = (event as any).context?._mountedPathname;\n if (typeof mountedPathname === \"string\" && mountedPathname) {\n return mountedPathname;\n }\n\n const urlPathname = (event as any).url?.pathname;\n if (typeof urlPathname === \"string\" && urlPathname) return urlPathname;\n\n const nodeUrl = event.node?.req?.url;\n if (typeof nodeUrl === \"string\" && nodeUrl) {\n const queryStart = nodeUrl.indexOf(\"?\");\n return queryStart >= 0 ? nodeUrl.slice(0, queryStart) : nodeUrl;\n }\n\n const eventPath = (event as any).path;\n if (typeof eventPath === \"string\" && eventPath) {\n const queryStart = eventPath.indexOf(\"?\");\n return queryStart >= 0 ? eventPath.slice(0, queryStart) : eventPath;\n }\n\n return \"/\";\n}\n\nfunction isRequestUnderAppBasePath(event: H3Event): boolean {\n const basePath = getAppBasePath();\n if (!basePath) return false;\n const requestPath = getOriginalRequestPath(event);\n return (\n requestPath === `${basePath}/_agent-native` ||\n requestPath.startsWith(`${basePath}/_agent-native/`)\n );\n}\n\nfunction getDefaultOAuthRedirectUrl(event: H3Event, path: string): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n if (\n isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(cleanPath)\n ) {\n return `${getOrigin(event)}${cleanPath}`;\n }\n const basePath = isRequestUnderAppBasePath(event) ? getAppBasePath() : \"\";\n return `${getOrigin(event)}${basePath}${cleanPath}`;\n}\n\n// ─── redirect_uri Allowlist ──────────────────────────────────────────────────\n\n/**\n * Validate a user-supplied `redirect_uri` for OAuth flows.\n *\n * Defends against authorization-code interception (RFC 6819 §4.4.1.7):\n * even though the upstream provider (Google/Atlassian/Zoom) refuses\n * unregistered redirect URIs, prefix-style registrations and side\n * registrations on the same host let a malicious caller swap in an\n * attacker-controlled URI that the provider still accepts. We reject any\n * candidate that isn't on this server's own origin AND under the\n * framework's `/_agent-native/` namespace. Returns the validated URI on\n * success, or `undefined` on rejection — callers must treat `undefined`\n * as a 400.\n *\n * The intentional shape is exact-prefix:\n * - Origin must equal `getOrigin(event)` — no Host-header injection\n * reusing somebody else's registered redirect URI.\n * - Path must start with `${appBasePath}/_agent-native/` so we never\n * hand auth codes to a public marketing or open-redirect endpoint\n * on the same registered host.\n *\n * For desktop / native flows that need ephemeral `http://127.0.0.1:<port>`\n * loopback URIs, callers should validate those at the template level\n * with a dedicated allowlist — this helper rejects them by design.\n */\nexport function isAllowedOAuthRedirectUri(\n candidate: string,\n event: H3Event,\n): boolean {\n if (typeof candidate !== \"string\" || candidate.length === 0) return false;\n let url: URL;\n try {\n url = new URL(candidate);\n } catch {\n return false;\n }\n // Must be same origin as our server.\n const expectedOrigin = getOrigin(event);\n let expectedUrl: URL;\n try {\n expectedUrl = new URL(expectedOrigin);\n } catch {\n return false;\n }\n if (url.protocol !== expectedUrl.protocol) return false;\n if (url.host !== expectedUrl.host) return false;\n // Must live under the framework's namespace. Workspace deploys can route\n // root /_agent-native/* to Dispatch even when Dispatch itself is mounted at\n // /dispatch, but app-prefixed requests should not be able to swap their\n // callback to that root namespace.\n const basePath = getAppBasePath();\n const allowedPrefixes =\n basePath && isRequestUnderAppBasePath(event)\n ? [\n `${basePath}/_agent-native/`,\n ...(isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(url.pathname)\n ? [\"/_agent-native/\"]\n : []),\n ]\n : [\"/_agent-native/\"];\n if (!allowedPrefixes.some((prefix) => url.pathname.startsWith(prefix))) {\n return false;\n }\n return true;\n}\n\n/**\n * Resolve the `redirect_uri` for an outbound OAuth `auth-url` request.\n *\n * Reads `?redirect_uri=` from the query and validates it via\n * `isAllowedOAuthRedirectUri`. Returns:\n * - the validated URI when supplied and allowed, OR\n * - the framework default when no override was supplied, OR\n * - `null` when an override was supplied but rejected — callers must\n * respond with 400 in that case.\n *\n * Templates that need a non-default redirect path can pass it via\n * `defaultPath` (e.g. `\"/_agent-native/google/desktop-callback\"` for\n * desktop flows).\n */\nexport function resolveOAuthRedirectUri(\n event: H3Event,\n defaultPath = \"/_agent-native/google/callback\",\n): string | null {\n const supplied = getQuery(event).redirect_uri;\n if (typeof supplied === \"string\" && supplied.length > 0) {\n return isAllowedOAuthRedirectUri(supplied, event) ? supplied : null;\n }\n return getDefaultOAuthRedirectUrl(event, defaultPath);\n}\n\n// ─── OAuth State ─────────────────────────────────────────────────────────────\n\nexport interface OAuthStatePayload {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n /**\n * Same-origin path to redirect to after a successful web-flow sign-in.\n * Threaded through the (HMAC-signed) state so it survives the round trip\n * to Google. Validated again on decode via safeReturnPath as defence in\n * depth. Has no effect on desktop / mobile / add-account flows, which\n * use their own deep-link / close-tab handling.\n */\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Ephemeral in-memory state-signing key for development. Generated lazily\n * on first read so dev sessions don't depend on filesystem writability or\n * env-var configuration. Sessions reset on each restart, which is fine\n * for dev — no real users / production data are involved.\n */\nlet _devStateSigningKey: string | undefined;\n\n/**\n * Derive a server-only signing key for HMAC verification of OAuth state.\n *\n * Uses a dedicated secret — never an OAuth client secret. Reusing a\n * client_secret (which is shared with Google / GitHub / Atlassian) as our\n * own HMAC key conflates two trust domains: rotating the client secret\n * silently invalidates every in-flight OAuth state, and any leak of the\n * client secret also lets an attacker forge our state envelopes.\n *\n * Resolution order:\n * 1. OAUTH_STATE_SECRET (preferred — dedicated to this purpose)\n * 2. BETTER_AUTH_SECRET (already used by Better Auth as a server secret)\n * 3. In dev only, an ephemeral random key (per-process)\n *\n * In production, throws if neither secret is set.\n */\nfunction getStateSigningKey(): string {\n const secret =\n process.env.OAUTH_STATE_SECRET || process.env.BETTER_AUTH_SECRET;\n if (secret) return secret;\n\n const isProd = process.env.NODE_ENV === \"production\";\n if (isProd) {\n throw new Error(\n \"OAuth state signing requires a server secret. \" +\n \"Set OAUTH_STATE_SECRET or BETTER_AUTH_SECRET in production.\",\n );\n }\n\n if (!_devStateSigningKey) {\n _devStateSigningKey = crypto.randomBytes(32).toString(\"hex\");\n }\n return _devStateSigningKey;\n}\n\n/**\n * Options for the named-argument form of {@link encodeOAuthState}.\n * Prefer this form — the positional overload is easy to misuse (the mail\n * and calendar templates historically passed `flowId` in the `returnUrl`\n * slot, smuggling state into a defence-in-depth path).\n */\nexport interface EncodeOAuthStateOptions {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Encode OAuth state into a signed base64url string.\n * The state is HMAC-signed so the callback can verify it wasn't forged,\n * preventing CSRF attacks on the OAuth flow.\n *\n * Two call shapes are supported:\n * - Recommended: pass an options object — clear, mismatch-proof.\n * `encodeOAuthState({ redirectUri, owner, desktop, ... })`\n * - Legacy positional form (kept working for backward compatibility):\n * `encodeOAuthState(redirectUri, owner, desktop, addAccount, app, returnUrl, flowId)`.\n * Callers should migrate to the options form — see the audit on\n * templates/mail and templates/calendar where the positional shape\n * led to `flowId` being smuggled in via the `returnUrl` slot.\n */\nexport function encodeOAuthState(opts: EncodeOAuthStateOptions): string;\nexport function encodeOAuthState(\n redirectUri: string,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string;\nexport function encodeOAuthState(\n redirectUriOrOpts: string | EncodeOAuthStateOptions,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string {\n const opts: EncodeOAuthStateOptions =\n typeof redirectUriOrOpts === \"string\"\n ? {\n redirectUri: redirectUriOrOpts,\n owner,\n desktop,\n addAccount,\n app,\n returnUrl,\n flowId,\n }\n : redirectUriOrOpts;\n\n const nonce = crypto.randomBytes(8).toString(\"hex\");\n const payload: Record<string, string | boolean> = {\n n: nonce,\n r: opts.redirectUri,\n };\n if (opts.owner) payload.o = opts.owner;\n if (opts.desktop) payload.d = true;\n if (opts.addAccount) payload.a = true;\n if (opts.app) payload.app = opts.app;\n if (opts.returnUrl) payload.r2 = opts.returnUrl;\n if (opts.flowId) payload.f = opts.flowId;\n const data = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n const sig = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n return `${data}.${sig}`;\n}\n\n/**\n * Decode and verify OAuth state from the callback's state query parameter.\n * Rejects forged or tampered state by checking the HMAC signature.\n * Falls back to the provided URI if decoding or verification fails.\n */\nexport function decodeOAuthState(\n stateParam: string | undefined,\n fallbackUri: string,\n): OAuthStatePayload {\n if (stateParam) {\n try {\n const dotIdx = stateParam.lastIndexOf(\".\");\n if (dotIdx === -1) return { redirectUri: fallbackUri };\n\n const data = stateParam.slice(0, dotIdx);\n const sig = stateParam.slice(dotIdx + 1);\n const expected = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n\n if (\n sig.length !== expected.length ||\n !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))\n ) {\n return { redirectUri: fallbackUri };\n }\n\n const parsed = JSON.parse(Buffer.from(data, \"base64url\").toString());\n return {\n redirectUri: parsed.r || fallbackUri,\n owner: parsed.o || undefined,\n desktop: !!parsed.d,\n addAccount: !!parsed.a,\n app: typeof parsed.app === \"string\" ? parsed.app : undefined,\n // Pass returnUrl through as-is — same-origin validation runs at the\n // consumer (oauthCallbackResponse → safeReturnPath). The state is\n // HMAC-signed, but we still validate at consumption as defence in\n // depth in case the signing key ever leaks.\n returnUrl: typeof parsed.r2 === \"string\" ? parsed.r2 : undefined,\n flowId: parsed.f || undefined,\n };\n } catch {}\n }\n return { redirectUri: fallbackUri };\n}\n\n// ─── Session Creation ────────────────────────────────────────────────────────\n\nexport interface OAuthOwnerResult {\n owner: string | undefined;\n hasProductionSession: boolean;\n}\n\n/**\n * Determine the token owner from the current session and OAuth state.\n * Call this BEFORE exchangeCode to get the owner parameter.\n */\nexport async function resolveOAuthOwner(\n event: H3Event,\n stateOwner?: string,\n): Promise<OAuthOwnerResult> {\n const existingSession = await getSession(event);\n const hasProductionSession = !!existingSession?.email;\n const owner = hasProductionSession\n ? existingSession!.email\n : stateOwner || undefined;\n\n return { owner, hasProductionSession };\n}\n\nexport interface OAuthSessionResult {\n sessionToken: string | undefined;\n}\n\n/**\n * Create a session token after a successful OAuth exchange.\n *\n * Desktop and mobile apps have separate cookie jars from the system\n * browser, so they always get a fresh session token (even if the browser\n * already has one). The token is then passed via deep link so the native\n * app can inject it.\n */\nexport async function createOAuthSession(\n event: H3Event,\n email: string,\n opts: {\n hasProductionSession: boolean;\n desktop?: boolean;\n },\n): Promise<OAuthSessionResult> {\n const mobile = isMobile(event);\n const needsDeepLink = opts.desktop || mobile;\n const maxAge = getSessionMaxAge();\n\n let sessionToken: string | undefined;\n if (!opts.hasProductionSession || needsDeepLink) {\n sessionToken = crypto.randomBytes(32).toString(\"hex\");\n await addSession(sessionToken, email);\n setFrameworkSessionCookie(event, sessionToken);\n // Desktop SSO: record this session in the home-dir broker file so\n // sibling templates (each with its own database) can resolve the\n // same token without a DB row of their own. Only the PRIMARY\n // sign-in writes the broker — if a production session already\n // exists, this is an add-account flow (connecting a secondary\n // Google account for scraping) and must never switch the active\n // user across sibling templates.\n if (opts.desktop && !opts.hasProductionSession) {\n await writeDesktopSso({\n email,\n token: sessionToken,\n expiresAt: Date.now() + maxAge * 1000,\n });\n }\n }\n\n return { sessionToken };\n}\n\n// ─── Callback Responses ──────────────────────────────────────────────────────\n\n/**\n * Return the appropriate response after a successful OAuth callback.\n *\n * Handles mobile deep links, desktop deep links, add-account close-tab\n * pages, and plain web redirects — so templates don't have to.\n */\nexport function oauthCallbackResponse(\n event: H3Event,\n email: string,\n opts: {\n sessionToken?: string;\n desktop?: boolean;\n addAccount?: boolean;\n /**\n * Same-origin path to return the viewer to after a successful web\n * sign-in. Validated via safeReturnPath; falls back to \"/\" for any\n * shape that escapes same-origin. Has no effect on desktop / mobile\n * / add-account flows — those use their own deep-link handling.\n */\n returnUrl?: string;\n flowId?: string;\n appName?: string;\n },\n): Response | string | unknown | Promise<Response | string | unknown> {\n const mobile = isMobile(event);\n const query = getQuery(event);\n const callbackState =\n typeof query.state === \"string\" && query.state.length > 0\n ? query.state\n : undefined;\n\n // Mobile: deep link back to native app\n if (mobile) {\n const deepLink = buildOAuthCompleteDeepLink(\n opts.sessionToken,\n callbackState,\n );\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\"><title>Connected</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p>Connected! Returning to app…</p><script>window.location.href=${JSON.stringify(deepLink)};setTimeout(function(){window.location.href=\"/\"},1500)</script></body></html>`,\n );\n }\n\n // Desktop add-account: close-tab page (must come before general desktop check\n // to ensure no deep link fires and the existing session is never switched).\n if (opts.desktop && opts.addAccount) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n oauthDebugFlowId(opts.flowId),\n ),\n );\n }\n\n // Electron desktop exchange flow: mail/calendar still pass a flow id so the\n // renderer can poll as a fallback, but the main handoff should use the\n // protocol deep link so the popup returns focus to the desktop app.\n if (opts.desktop && opts.flowId && isElectron(event) && opts.sessionToken) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Desktop exchange flow (non-Electron tray app): the tray app polls the\n // desktop-exchange endpoint for the token — no deep link needed.\n if (opts.desktop && opts.flowId) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Signed in as ${safeEmail}!` : \"Signed in!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n oauthDebugFlowId(opts.flowId),\n ),\n );\n }\n\n // Desktop login: deep link back to Electron app — only when the callback\n // request actually carries the AgentNativeDesktop UA marker. Without this\n // check, any client whose OAuth state was minted with `desktop=true` (e.g.\n // a stale link, or an upstream that wrongly set `?desktop=1`) would land\n // on the `agentnative://` page where the deep link can't fire and the\n // \"Open Agent Native\" button does nothing — surfaces inside Builder.io's\n // Fusion webview hit this exact dead-end. Fall through to the web flow\n // for non-Agent-Native-Desktop clients so they get a real redirect.\n if (opts.desktop && isElectron(event)) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Add-account web flow: close-tab page. The email is rendered into the\n // page via DOM `textContent` (safe), but we still JSON-stringify so a\n // payload containing `</script>` can't break out of the script tag —\n // and explicitly assert it's a string so a callbacks like `null` or\n // an object won't end up serialised into the page.\n if (opts.addAccount) {\n const safeEmail = JSON.stringify(typeof email === \"string\" ? email : \"\");\n return htmlResponse(`<!DOCTYPE html><html><body><script>\n window.close();\n var p = document.createElement('p');\n p.style.cssText = 'font-family:system-ui;text-align:center;margin-top:40vh';\n p.textContent = 'Connected ' + ${safeEmail} + '! You can close this tab.';\n document.body.appendChild(p);\n </script></body></html>`);\n }\n\n // Web: redirect to the requested return path (validated same-origin) or\n // \"/\" if no return was supplied / the return failed validation. Returning\n // an empty string body keeps h3's `prepareResponseBody` → `FastResponse`\n // path, which merges the prepared event headers (Location + any cookies\n // set via `setCookie(event, ...)`).\n setResponseStatus(event, 302);\n setResponseHeader(event, \"Location\", safeReturnPath(opts.returnUrl));\n return \"\";\n}\n\n/** HTML error page for OAuth failures. The message is HTML-escaped — most\n * callers pass `error.message` from a token-exchange or userinfo failure,\n * which can echo upstream provider strings (and historically attacker-\n * controlled query params via the `error_description` field). */\nexport function oauthErrorPage(message: string): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connection failed</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;text-align:center\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#ef4444\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M15 9l-6 6\"/><path d=\"M9 9l6 6\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0;color:#ddd\">${safe}</p><p style=\"font-size:13px;color:#888;margin:0\"><a href=\"/\" style=\"color:#888;text-decoration:underline;text-underline-offset:3px\">Back to login</a></p></body></html>`,\n 400,\n );\n}\n\nexport function oauthDesktopExchangePage(\n message = \"Returning to the app...\",\n): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Returning</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p style=\"font-size:14px\">${safe}</p><script>window.close()</script></body></html>`,\n );\n}\n\n// ─── Internal ────────────────────────────────────────────────────────────────\n\nfunction resolveOAuthAppName(explicit?: string): string {\n const raw = explicit || getAppName() || \"Agent Native\";\n if (!/^[a-z0-9_-]+$/.test(raw)) return raw;\n return raw\n .split(/[-_]+/)\n .filter(Boolean)\n .map((word) => word[0].toUpperCase() + word.slice(1))\n .join(\" \");\n}\n\nfunction buildOAuthCompleteDeepLink(\n sessionToken?: string,\n state?: string,\n): string {\n const params = new URLSearchParams();\n if (sessionToken) params.set(\"token\", sessionToken);\n if (state) params.set(\"state\", state);\n const suffix = params.toString();\n return suffix\n ? `agentnative://oauth-complete?${suffix}`\n : \"agentnative://oauth-complete\";\n}\n\nfunction desktopSuccessPage(\n _event: H3Event,\n email?: string,\n sessionToken?: string,\n state?: string,\n): Response {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n if (sessionToken) {\n const deepLink = buildOAuthCompleteDeepLink(sessionToken, state);\n const deepLinkJson = JSON.stringify(deepLink);\n // Defence in depth: if this page somehow gets served to a UA that isn't\n // the Agent Native desktop app (server gate bypassed, stale link, etc.),\n // skip the `agentnative://` deep link entirely and bounce to the app\n // root. The deep link silently fails outside the desktop app and the\n // \"Open Agent Native\" button is a dead end in a generic browser/webview.\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title><style>@keyframes spin{to{transform:rotate(360deg)}}@keyframes fadeIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.spinner{width:28px;height:28px;border:2px solid #333;border-top-color:#fff;border-radius:50%;animation:spin .8s linear infinite}.fallback{display:none;flex-direction:column;align-items:center;gap:8px;animation:fadeIn .2s ease-out}.fallback.show{display:flex}</style></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;gap:16px\"><p style=\"font-size:16px;margin:0\">${msg}</p><div id=\"loading\" class=\"spinner\"></div><div id=\"fallback\" class=\"fallback\"><a href=${deepLinkJson} style=\"display:inline-block;padding:10px 24px;background:#fff;color:#000;border-radius:8px;text-decoration:none;font-size:14px;font-weight:500\">Open Agent Native</a><p style=\"font-size:12px;color:#666;margin:0\">If the app didn\\u2019t open automatically, click the button above.</p></div><script>(function(){var ua=(navigator.userAgent||\"\");if(ua.indexOf(\"AgentNativeDesktop\")===-1){window.location.replace(\"/\");return}window.location.href=${deepLinkJson};setTimeout(function(){document.getElementById(\"loading\").style.display=\"none\";document.getElementById(\"fallback\").classList.add(\"show\")},3000)})()</script></body></html>`,\n );\n }\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n \"You can close this tab and return to Agent Native.\",\n ),\n );\n}\n"]}
@@ -4,7 +4,7 @@ export { createSSEHandler, type SSEHandlerOptions } from "./sse.js";
4
4
  export { mountAuthMiddleware, autoMountAuth, getSession, addSession, removeSession, getSessionEmail, runAuthGuard, setDesktopExchange, setDesktopExchangeError, safeReturnPath, type DesktopExchangeErrorPayload, type AuthSession, type AuthOptions, } from "./auth.js";
5
5
  export { requireEnvKey, type MissingKeyResponse } from "./missing-key.js";
6
6
  export { verifyCaptcha, type CaptchaVerifyResult } from "./captcha.js";
7
- export { createProductionAgentHandler, type ActionEntry, type ScriptEntry, type ProductionAgentOptions, type ActionTool, type ScriptTool, type AgentMessage, type AgentChatRequest, type AgentChatEvent, type AgentChatReference, type MentionProvider, type MentionProviderItem, type AgentLoopFinalResponseGuard, type AgentLoopFinalResponseGuardContext, type AgentLoopFinalResponseGuardResult, type AgentLoopToolCallSummary, type AgentLoopToolResultSummary, } from "../agent/index.js";
7
+ export { createProductionAgentHandler, type ActionEntry, type ScriptEntry, type ProductionAgentOptions, type ActionTool, type ScriptTool, type AgentMessage, type AgentChatRequest, type AgentChatEvent, type AgentChatAttachment, type AgentChatReference, type MentionProvider, type MentionProviderItem, type AgentLoopFinalResponseGuard, type AgentLoopFinalResponseGuardContext, type AgentLoopFinalResponseGuardResult, type AgentLoopToolCallSummary, type AgentLoopToolResultSummary, } from "../agent/index.js";
8
8
  export { createDevScriptRegistry } from "../scripts/dev/index.js";
9
9
  export { createPollHandler, recordChange, getVersion, getChangesSince, } from "./poll.js";
10
10
  export { createAuthPlugin, defaultAuthPlugin } from "./auth-plugin.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,aAAa,EACb,KAAK,mBAAmB,EACxB,KAAK,YAAY,GAClB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,MAAM,UAAU,CAAC;AACpE,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,UAAU,EACV,UAAU,EACV,aAAa,EACb,eAAe,EACf,YAAY,EACZ,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,EACd,KAAK,2BAA2B,EAChC,KAAK,WAAW,EAChB,KAAK,WAAW,GACjB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,aAAa,EAAE,KAAK,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,KAAK,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EACL,4BAA4B,EAC5B,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,sBAAsB,EAC3B,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,kBAAkB,EACvB,KAAK,eAAe,EACpB,KAAK,mBAAmB,EACxB,KAAK,2BAA2B,EAChC,KAAK,kCAAkC,EACvC,KAAK,iCAAiC,EACtC,KAAK,wBAAwB,EAC7B,KAAK,0BAA0B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAElE,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,eAAe,GAChB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,k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AAwB,EACxB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,GACxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,mBAAmB,EACnB,qBAAqB,EACrB,gCAAgC,EAChC,oBAAoB,EACpB,wBAAwB,EACxB,wBAAwB,EACxB,2BAA2B,EAC3B,yBAAyB,EACzB,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,EACxB,aAAa,GACd,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,yBAAyB,EACzB,yBAAyB,EACzB,6BAA6B,EAC7B,gCAAgC,EAChC,eAAe,EACf,KAAK,qBAAqB,GAC3B,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,aAAa,EAClB,KAAK,aAAa,GACnB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,WAAW,EACX,WAAW,EACX,SAAS,EACT,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,QAAQ,GACd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACpB,yBAAyB,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,YAAY,IAAI,2BAA2B,GACjD,MAAM,wBAAwB,CAAC;AAUhC,MAAM,MAAM,cAAc,GAAG,CAAC,QAAQ,EAAE,GAAG,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AACrE,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,cAAc,GAAG,cAAc,CAErE"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EAC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AAE3B,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,mBAAmB,EACnB,qBAAqB,EACrB,gCAAgC,EAChC,oBAAoB,EACpB,wBAAwB,EACxB,wBAAwB,EACxB,2BAA2B,EAC3B,yBAAyB,EACzB,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,EACxB,aAAa,GACd,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,yBAAyB,EACzB,yBAAyB,EACzB,6BAA6B,EAC7B,gCAAgC,EAChC,eAAe,EACf,KAAK,qBAAqB,GAC3B,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,aAAa,EAClB,KAAK,aAAa,GACnB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,WAAW,EACX,WAAW,EACX,SAAS,EACT,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,QAAQ,GACd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACpB,yBAAyB,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,YAAY,IAAI,2BAA2B,GACjD,MAAM,wBAAwB,CAAC;AAUhC,MAAM,MAAM,cAAc,GAAG,CAAC,QAAQ,EAAE,GAAG,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AACrE,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,cAAc,GAAG,cAAc,CAErE"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,aAAa,GAGd,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAA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Q,EACR,SAAS,EACT,cAAc,EACd,SAAS,EACT,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,kBAAkB,EAClB,qBAAqB,EACrB,cAAc,EACd,wBAAwB,GAIzB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,mBAAmB,EACnB,qBAAqB,EACrB,gCAAgC,EAChC,oBAAoB,EACpB,wBAAwB,EACxB,wBAAwB,EACxB,2BAA2B,EAC3B,yBAAyB,EACzB,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,EACxB,aAAa,GACd,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,yBAAyB,EACzB,yBAAyB,EACzB,6BAA6B,EAC7B,gCAAgC,EAChC,eAAe,GAEhB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,gBAAgB,GAGjB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,WAAW,EACX,WAAW,EACX,SAAS,GAIV,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACpB,yBAAyB,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GAGtB,MAAM,wBAAwB,CAAC;AAWhC,MAAM,UAAU,iBAAiB,CAAC,GAAmB;IACnD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["export {\n createServer,\n upsertEnvFile,\n type CreateServerOptions,\n type EnvKeyConfig,\n} from \"./create-server.js\";\n\nexport { readBody, streamFile } from \"./h3-helpers.js\";\nexport { createSSEHandler, type SSEHandlerOptions } from \"./sse.js\";\nexport {\n mountAuthMiddleware,\n autoMountAuth,\n getSession,\n addSession,\n removeSession,\n getSessionEmail,\n runAuthGuard,\n setDesktopExchange,\n setDesktopExchangeError,\n safeReturnPath,\n type DesktopExchangeErrorPayload,\n type AuthSession,\n type AuthOptions,\n} from \"./auth.js\";\nexport { requireEnvKey, type MissingKeyResponse } from \"./missing-key.js\";\nexport { verifyCaptcha, type CaptchaVerifyResult } from \"./captcha.js\";\nexport {\n createProductionAgentHandler,\n type ActionEntry,\n type ScriptEntry,\n type ProductionAgentOptions,\n type ActionTool,\n type ScriptTool,\n type AgentMessage,\n type AgentChatRequest,\n type AgentChatEvent,\n type AgentChatReference,\n type MentionProvider,\n type MentionProviderItem,\n type AgentLoopFinalResponseGuard,\n type AgentLoopFinalResponseGuardContext,\n type AgentLoopFinalResponseGuardResult,\n type AgentLoopToolCallSummary,\n type AgentLoopToolResultSummary,\n} from \"../agent/index.js\";\nexport { createDevScriptRegistry } from \"../scripts/dev/index.js\";\n\nexport {\n createPollHandler,\n recordChange,\n getVersion,\n getChangesSince,\n} from \"./poll.js\";\nexport { createAuthPlugin, defaultAuthPlugin } from \"./auth-plugin.js\";\nexport {\n initServerSentry,\n isServerSentryEnabled,\n setSentryUserForRequest,\n captureRouteError,\n type RouteErrorContext,\n} from \"./sentry.js\";\nexport {\n captureError,\n captureServerError,\n registerErrorCaptureProvider,\n type CaptureErrorContext,\n type CaptureErrorProvider,\n} from \"./capture-error.js\";\nexport { createSentryPlugin, defaultSentryPlugin } from \"./sentry-plugin.js\";\n// Re-export the org plugin so the auto-discovery's DEFAULT_PLUGIN_REGISTRY\n// (which references \"defaultOrgPlugin\" from @agent-native/core/server) can\n// resolve it during the deploy build worker-entry generation.\nexport { createOrgPlugin, defaultOrgPlugin } from \"../org/plugin.js\";\nexport {\n createGoogleAuthPlugin,\n type GoogleAuthPluginOptions,\n} from \"./google-auth-plugin.js\";\nexport {\n createAgentChatPlugin,\n defaultAgentChatPlugin,\n type AgentChatPluginOptions,\n} from \"./agent-chat-plugin.js\";\nexport {\n createThread,\n getThread,\n listThreads,\n updateThreadData,\n deleteThread,\n type ChatThread,\n type ChatThreadSummary,\n} from \"../chat-threads/store.js\";\nexport {\n createResourcesPlugin,\n defaultResourcesPlugin,\n} from \"./resources-plugin.js\";\nexport {\n createCoreRoutesPlugin,\n defaultCoreRoutesPlugin,\n FRAMEWORK_ROUTE_PREFIX,\n type CoreRoutesPluginOptions,\n} from \"./core-routes-plugin.js\";\nexport {\n createTerminalPlugin,\n defaultTerminalPlugin,\n type TerminalPluginOptions,\n} from \"../terminal/terminal-plugin.js\";\nexport {\n createCollabPlugin,\n type CollabPluginOptions,\n} from \"./collab-plugin.js\";\n\nexport {\n spawnTask,\n getTask,\n getTaskByThread,\n listTasks,\n sendToTask,\n markTaskErrored,\n type AgentTask,\n type SpawnTaskOptions,\n} from \"./agent-teams.js\";\nexport { isOAuthConnected, getOAuthAccounts } from \"./oauth-helpers.js\";\nexport { wrapWithAnalytics } from \"./analytics.js\";\nexport {\n getH3App,\n awaitBootstrap,\n type H3AppShim,\n} from \"./framework-request-handler.js\";\nexport {\n autoDiscoverActions,\n autoDiscoverScripts,\n loadActionsFromStaticRegistry,\n mergeCoreSharingActions,\n registerPackageActions,\n} from \"./action-discovery.js\";\nexport {\n mountActionRoutes,\n type MountActionRoutesOptions,\n} from \"./action-routes.js\";\nexport {\n runWithRequestContext,\n hasRequestContext,\n getRequestContext,\n getRequestUserEmail,\n getRequestUserName,\n getRequestOrgId,\n getRequestTimezone,\n getRequestRunContext,\n getCredentialContext,\n isIntegrationCallerRequest,\n type RequestContext,\n type RequestRunContext,\n} from \"./request-context.js\";\nexport { formatDateInTimezone, todayInTimezone } from \"./date-utils.js\";\n\nexport {\n createOnboardingPlugin,\n defaultOnboardingPlugin,\n} from \"../onboarding/plugin.js\";\n\nexport {\n registerFileUploadProvider,\n unregisterFileUploadProvider,\n listFileUploadProviders,\n getActiveFileUploadProvider,\n uploadFile,\n builderFileUploadProvider,\n type FileUploadInput,\n type FileUploadProvider,\n type FileUploadResult,\n} from \"../file-upload/index.js\";\n\nexport {\n createIntegrationsPlugin,\n defaultIntegrationsPlugin,\n slackAdapter,\n telegramAdapter,\n whatsappAdapter,\n emailAdapter,\n type PlatformAdapter,\n type IncomingMessage,\n type OutgoingMessage,\n type IntegrationStatus,\n type IntegrationsPluginOptions,\n} from \"../integrations/index.js\";\n\nexport {\n isElectron,\n isMobile,\n getOrigin,\n getAppBasePath,\n getAppUrl,\n resolveOAuthRedirectUri,\n isAllowedOAuthRedirectUri,\n encodeOAuthState,\n decodeOAuthState,\n resolveOAuthOwner,\n createOAuthSession,\n oauthCallbackResponse,\n oauthErrorPage,\n oauthDesktopExchangePage,\n type OAuthStatePayload,\n type OAuthOwnerResult,\n type OAuthSessionResult,\n} from \"./google-oauth.js\";\n\nexport {\n FeatureNotConfiguredError,\n hasBuilderPrivateKey,\n isBuilderEnvManaged,\n getBuilderProxyOrigin,\n getBuilderImageGenerationBaseUrl,\n getBuilderAuthHeader,\n resolveBuilderPrivateKey,\n resolveBuilderAuthHeader,\n resolveHasBuilderPrivateKey,\n resolveBuilderCredentials,\n resolveBuilderCredential,\n writeBuilderCredentials,\n deleteBuilderCredentials,\n resolveSecret,\n} from \"./credential-provider.js\";\nexport {\n getBuilderBranchProjectId,\n isBuilderBranchingEnabled,\n resolveBuilderBranchProjectId,\n resolveIsBuilderBranchingEnabled,\n runBuilderAgent,\n type RunBuilderAgentResult,\n} from \"./builder-browser.js\";\n\nexport {\n sendEmail,\n isEmailConfigured,\n getEmailProvider,\n type EmailProvider,\n type SendEmailArgs,\n} from \"./email.js\";\nexport {\n renderEmail,\n emailStrong,\n emailLink,\n type RenderEmailArgs,\n type RenderedEmail,\n type EmailCta,\n} from \"./email-template.js\";\nexport { getAppProductionUrl, getFirstPartyProdUrl } from \"./app-url.js\";\nexport {\n getConfiguredAppBasePath,\n normalizeAppBasePath,\n withConfiguredAppBasePath,\n} from \"./app-base-path.js\";\nexport {\n signShortLivedToken,\n verifyShortLivedToken,\n type ShortLivedTokenClaims,\n type VerifyResult as ShortLivedTokenVerifyResult,\n} from \"./short-lived-token.js\";\n\n// SSR handler is NOT re-exported here — it uses a virtual module\n// (virtual:react-router/server-build) that only exists at Vite dev/build time.\n// Including it in this barrel would break the esbuild CF Pages bundler.\n// Templates import directly: import { ssrHandler } from \"@agent-native/core/server/ssr-handler\"\n\n// Nitro plugin helper — re-exported so templates don't need nitro as a direct dependency.\n// defineNitroPlugin is an identity function; this typed wrapper lets templates use it\n// without resolving `nitro/runtime` (which requires Nitro's virtual modules at runtime).\nexport type NitroPluginDef = (nitroApp: any) => void | Promise<void>;\nexport function defineNitroPlugin(def: NitroPluginDef): NitroPluginDef {\n return def;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,aAAa,GAGd,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAA0B,MAAM,UAAU,CAAC;AACpE,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,UAAU,EACV,UAAU,EACV,aAAa,EACb,eAAe,EACf,YAAY,EACZ,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,GAIf,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,aAAa,EAA2B,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAA4B,MAAM,cAAc,CAAC;AACvE,OAAO,EACL,4BAA4B,GAkB7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAElE,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,eAAe,GAChB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACvE,OAAO,EACL,gBAAgB,EAChB,qBAAqB,EACrB,uBAAuB,EACvB,iBAAiB,GAElB,MAAM,aAAa,CAAC;AAC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C;AAC7B,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACpB,yBAAyB,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GAGtB,MAAM,wBAAwB,CAAC;AAWhC,MAAM,UAAU,iBAAiB,CAAC,GAAmB;IACnD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["export {\n createServer,\n upsertEnvFile,\n type CreateServerOptions,\n type EnvKeyConfig,\n} from \"./create-server.js\";\n\nexport { readBody, streamFile } from \"./h3-helpers.js\";\nexport { createSSEHandler, type SSEHandlerOptions } from \"./sse.js\";\nexport {\n mountAuthMiddleware,\n autoMountAuth,\n getSession,\n addSession,\n removeSession,\n getSessionEmail,\n runAuthGuard,\n setDesktopExchange,\n setDesktopExchangeError,\n safeReturnPath,\n type DesktopExchangeErrorPayload,\n type AuthSession,\n type AuthOptions,\n} from \"./auth.js\";\nexport { requireEnvKey, type MissingKeyResponse } from \"./missing-key.js\";\nexport { verifyCaptcha, type CaptchaVerifyResult } from \"./captcha.js\";\nexport {\n createProductionAgentHandler,\n type ActionEntry,\n type ScriptEntry,\n type ProductionAgentOptions,\n type ActionTool,\n type ScriptTool,\n type AgentMessage,\n type AgentChatRequest,\n type AgentChatEvent,\n type AgentChatAttachment,\n type AgentChatReference,\n type MentionProvider,\n type MentionProviderItem,\n type AgentLoopFinalResponseGuard,\n type AgentLoopFinalResponseGuardContext,\n type AgentLoopFinalResponseGuardResult,\n type AgentLoopToolCallSummary,\n type AgentLoopToolResultSummary,\n} from \"../agent/index.js\";\nexport { createDevScriptRegistry } from \"../scripts/dev/index.js\";\n\nexport {\n createPollHandler,\n recordChange,\n getVersion,\n getChangesSince,\n} from \"./poll.js\";\nexport { createAuthPlugin, defaultAuthPlugin } from \"./auth-plugin.js\";\nexport {\n initServerSentry,\n isServerSentryEnabled,\n setSentryUserForRequest,\n captureRouteError,\n type RouteErrorContext,\n} from \"./sentry.js\";\nexport {\n captureError,\n captureServerError,\n registerErrorCaptureProvider,\n type CaptureErrorContext,\n type CaptureErrorProvider,\n} from \"./capture-error.js\";\nexport { createSentryPlugin, defaultSentryPlugin } from \"./sentry-plugin.js\";\n// Re-export the org plugin so the auto-discovery's DEFAULT_PLUGIN_REGISTRY\n// (which references \"defaultOrgPlugin\" from @agent-native/core/server) can\n// resolve it during the deploy build worker-entry generation.\nexport { createOrgPlugin, defaultOrgPlugin } from \"../org/plugin.js\";\nexport {\n createGoogleAuthPlugin,\n type GoogleAuthPluginOptions,\n} from \"./google-auth-plugin.js\";\nexport {\n createAgentChatPlugin,\n defaultAgentChatPlugin,\n type AgentChatPluginOptions,\n} from \"./agent-chat-plugin.js\";\nexport {\n createThread,\n getThread,\n listThreads,\n updateThreadData,\n deleteThread,\n type ChatThread,\n type ChatThreadSummary,\n} from \"../chat-threads/store.js\";\nexport {\n createResourcesPlugin,\n defaultResourcesPlugin,\n} from \"./resources-plugin.js\";\nexport {\n createCoreRoutesPlugin,\n defaultCoreRoutesPlugin,\n FRAMEWORK_ROUTE_PREFIX,\n type CoreRoutesPluginOptions,\n} from \"./core-routes-plugin.js\";\nexport {\n createTerminalPlugin,\n defaultTerminalPlugin,\n type TerminalPluginOptions,\n} from \"../terminal/terminal-plugin.js\";\nexport {\n createCollabPlugin,\n type CollabPluginOptions,\n} from \"./collab-plugin.js\";\n\nexport {\n spawnTask,\n getTask,\n getTaskByThread,\n listTasks,\n sendToTask,\n markTaskErrored,\n type AgentTask,\n type SpawnTaskOptions,\n} from \"./agent-teams.js\";\nexport { isOAuthConnected, getOAuthAccounts } from \"./oauth-helpers.js\";\nexport { wrapWithAnalytics } from \"./analytics.js\";\nexport {\n getH3App,\n awaitBootstrap,\n type H3AppShim,\n} from \"./framework-request-handler.js\";\nexport {\n autoDiscoverActions,\n autoDiscoverScripts,\n loadActionsFromStaticRegistry,\n mergeCoreSharingActions,\n registerPackageActions,\n} from \"./action-discovery.js\";\nexport {\n mountActionRoutes,\n type MountActionRoutesOptions,\n} from \"./action-routes.js\";\nexport {\n runWithRequestContext,\n hasRequestContext,\n getRequestContext,\n getRequestUserEmail,\n getRequestUserName,\n getRequestOrgId,\n getRequestTimezone,\n getRequestRunContext,\n getCredentialContext,\n isIntegrationCallerRequest,\n type RequestContext,\n type RequestRunContext,\n} from \"./request-context.js\";\nexport { formatDateInTimezone, todayInTimezone } from \"./date-utils.js\";\n\nexport {\n createOnboardingPlugin,\n defaultOnboardingPlugin,\n} from \"../onboarding/plugin.js\";\n\nexport {\n registerFileUploadProvider,\n unregisterFileUploadProvider,\n listFileUploadProviders,\n getActiveFileUploadProvider,\n uploadFile,\n builderFileUploadProvider,\n type FileUploadInput,\n type FileUploadProvider,\n type FileUploadResult,\n} from \"../file-upload/index.js\";\n\nexport {\n createIntegrationsPlugin,\n defaultIntegrationsPlugin,\n slackAdapter,\n telegramAdapter,\n whatsappAdapter,\n emailAdapter,\n type PlatformAdapter,\n type IncomingMessage,\n type OutgoingMessage,\n type IntegrationStatus,\n type IntegrationsPluginOptions,\n} from \"../integrations/index.js\";\n\nexport {\n isElectron,\n isMobile,\n getOrigin,\n getAppBasePath,\n getAppUrl,\n resolveOAuthRedirectUri,\n isAllowedOAuthRedirectUri,\n encodeOAuthState,\n decodeOAuthState,\n resolveOAuthOwner,\n createOAuthSession,\n oauthCallbackResponse,\n oauthErrorPage,\n oauthDesktopExchangePage,\n type OAuthStatePayload,\n type OAuthOwnerResult,\n type OAuthSessionResult,\n} from \"./google-oauth.js\";\n\nexport {\n FeatureNotConfiguredError,\n hasBuilderPrivateKey,\n isBuilderEnvManaged,\n getBuilderProxyOrigin,\n getBuilderImageGenerationBaseUrl,\n getBuilderAuthHeader,\n resolveBuilderPrivateKey,\n resolveBuilderAuthHeader,\n resolveHasBuilderPrivateKey,\n resolveBuilderCredentials,\n resolveBuilderCredential,\n writeBuilderCredentials,\n deleteBuilderCredentials,\n resolveSecret,\n} from \"./credential-provider.js\";\nexport {\n getBuilderBranchProjectId,\n isBuilderBranchingEnabled,\n resolveBuilderBranchProjectId,\n resolveIsBuilderBranchingEnabled,\n runBuilderAgent,\n type RunBuilderAgentResult,\n} from \"./builder-browser.js\";\n\nexport {\n sendEmail,\n isEmailConfigured,\n getEmailProvider,\n type EmailProvider,\n type SendEmailArgs,\n} from \"./email.js\";\nexport {\n renderEmail,\n emailStrong,\n emailLink,\n type RenderEmailArgs,\n type RenderedEmail,\n type EmailCta,\n} from \"./email-template.js\";\nexport { getAppProductionUrl, getFirstPartyProdUrl } from \"./app-url.js\";\nexport {\n getConfiguredAppBasePath,\n normalizeAppBasePath,\n withConfiguredAppBasePath,\n} from \"./app-base-path.js\";\nexport {\n signShortLivedToken,\n verifyShortLivedToken,\n type ShortLivedTokenClaims,\n type VerifyResult as ShortLivedTokenVerifyResult,\n} from \"./short-lived-token.js\";\n\n// SSR handler is NOT re-exported here — it uses a virtual module\n// (virtual:react-router/server-build) that only exists at Vite dev/build time.\n// Including it in this barrel would break the esbuild CF Pages bundler.\n// Templates import directly: import { ssrHandler } from \"@agent-native/core/server/ssr-handler\"\n\n// Nitro plugin helper — re-exported so templates don't need nitro as a direct dependency.\n// defineNitroPlugin is an identity function; this typed wrapper lets templates use it\n// without resolving `nitro/runtime` (which requires Nitro's virtual modules at runtime).\nexport type NitroPluginDef = (nitroApp: any) => void | Promise<void>;\nexport function defineNitroPlugin(def: NitroPluginDef): NitroPluginDef {\n return def;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"onboarding-html.d.ts","sourceRoot":"","sources":["../../src/server/onboarding-html.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAkCH,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;OAIG;IACH,SAAS,CAAC,EAAE;QACV,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,EAAE,MAAM,CAAC;QA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