@agent-native/core 0.35.2 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/README.md +1 -1
  2. package/dist/cli/context-xray-local.d.ts +2 -2
  3. package/dist/cli/context-xray-local.d.ts.map +1 -1
  4. package/dist/cli/context-xray-local.js +1449 -53
  5. package/dist/cli/context-xray-local.js.map +1 -1
  6. package/dist/cli/index.js +1 -1
  7. package/dist/cli/index.js.map +1 -1
  8. package/dist/cli/skills.d.ts.map +1 -1
  9. package/dist/cli/skills.js +381 -73
  10. package/dist/cli/skills.js.map +1 -1
  11. package/dist/cli/templates-meta.d.ts.map +1 -1
  12. package/dist/cli/templates-meta.js +8 -4
  13. package/dist/cli/templates-meta.js.map +1 -1
  14. package/dist/client/AgentPanel.d.ts.map +1 -1
  15. package/dist/client/AgentPanel.js +5 -11
  16. package/dist/client/AgentPanel.js.map +1 -1
  17. package/dist/client/AssistantChat.d.ts +6 -0
  18. package/dist/client/AssistantChat.d.ts.map +1 -1
  19. package/dist/client/AssistantChat.js +50 -26
  20. package/dist/client/AssistantChat.js.map +1 -1
  21. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  22. package/dist/client/MultiTabAssistantChat.js +81 -8
  23. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  24. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  25. package/dist/client/agent-chat-adapter.js +68 -24
  26. package/dist/client/agent-chat-adapter.js.map +1 -1
  27. package/dist/client/agent-chat.d.ts +39 -3
  28. package/dist/client/agent-chat.d.ts.map +1 -1
  29. package/dist/client/agent-chat.js +168 -33
  30. package/dist/client/agent-chat.js.map +1 -1
  31. package/dist/client/application-state.d.ts +13 -0
  32. package/dist/client/application-state.d.ts.map +1 -0
  33. package/dist/client/application-state.js +99 -0
  34. package/dist/client/application-state.js.map +1 -0
  35. package/dist/client/composer/ComposerPlusMenu.d.ts.map +1 -1
  36. package/dist/client/composer/ComposerPlusMenu.js +174 -8
  37. package/dist/client/composer/ComposerPlusMenu.js.map +1 -1
  38. package/dist/client/composer/PromptComposer.d.ts +2 -0
  39. package/dist/client/composer/PromptComposer.d.ts.map +1 -1
  40. package/dist/client/composer/PromptComposer.js +2 -2
  41. package/dist/client/composer/PromptComposer.js.map +1 -1
  42. package/dist/client/composer/TiptapComposer.js +1 -1
  43. package/dist/client/composer/TiptapComposer.js.map +1 -1
  44. package/dist/client/context-xray/ContextMeter.d.ts +2 -1
  45. package/dist/client/context-xray/ContextMeter.d.ts.map +1 -1
  46. package/dist/client/context-xray/ContextMeter.js +19 -25
  47. package/dist/client/context-xray/ContextMeter.js.map +1 -1
  48. package/dist/client/context-xray/ContextXRayPanel.d.ts +1 -3
  49. package/dist/client/context-xray/ContextXRayPanel.d.ts.map +1 -1
  50. package/dist/client/context-xray/ContextXRayPanel.js +27 -24
  51. package/dist/client/context-xray/ContextXRayPanel.js.map +1 -1
  52. package/dist/client/conversation/AgentConversation.d.ts.map +1 -1
  53. package/dist/client/conversation/AgentConversation.js +2 -1
  54. package/dist/client/conversation/AgentConversation.js.map +1 -1
  55. package/dist/client/frame-protocol.d.ts +11 -3
  56. package/dist/client/frame-protocol.d.ts.map +1 -1
  57. package/dist/client/frame-protocol.js.map +1 -1
  58. package/dist/client/index.d.ts +4 -2
  59. package/dist/client/index.d.ts.map +1 -1
  60. package/dist/client/index.js +4 -2
  61. package/dist/client/index.js.map +1 -1
  62. package/dist/client/progress/RunsTray.d.ts +1 -0
  63. package/dist/client/progress/RunsTray.d.ts.map +1 -1
  64. package/dist/client/progress/RunsTray.js +50 -16
  65. package/dist/client/progress/RunsTray.js.map +1 -1
  66. package/dist/client/sse-event-processor.d.ts +1 -0
  67. package/dist/client/sse-event-processor.d.ts.map +1 -1
  68. package/dist/client/sse-event-processor.js +62 -15
  69. package/dist/client/sse-event-processor.js.map +1 -1
  70. package/dist/client/tool-display.d.ts +4 -0
  71. package/dist/client/tool-display.d.ts.map +1 -0
  72. package/dist/client/tool-display.js +28 -0
  73. package/dist/client/tool-display.js.map +1 -0
  74. package/dist/client/use-action.d.ts +12 -0
  75. package/dist/client/use-action.d.ts.map +1 -1
  76. package/dist/client/use-action.js +14 -2
  77. package/dist/client/use-action.js.map +1 -1
  78. package/dist/client/use-agent-chat-context.d.ts +15 -0
  79. package/dist/client/use-agent-chat-context.d.ts.map +1 -0
  80. package/dist/client/use-agent-chat-context.js +32 -0
  81. package/dist/client/use-agent-chat-context.js.map +1 -0
  82. package/dist/client/use-chat-threads.d.ts.map +1 -1
  83. package/dist/client/use-chat-threads.js +40 -31
  84. package/dist/client/use-chat-threads.js.map +1 -1
  85. package/dist/client/use-external-value.d.ts.map +1 -1
  86. package/dist/client/use-external-value.js +14 -7
  87. package/dist/client/use-external-value.js.map +1 -1
  88. package/dist/deploy/build.d.ts.map +1 -1
  89. package/dist/deploy/build.js +1 -2
  90. package/dist/deploy/build.js.map +1 -1
  91. package/dist/extensions/html-shell.d.ts +3 -2
  92. package/dist/extensions/html-shell.d.ts.map +1 -1
  93. package/dist/extensions/html-shell.js +12 -2
  94. package/dist/extensions/html-shell.js.map +1 -1
  95. package/dist/extensions/routes.js +2 -7
  96. package/dist/extensions/routes.js.map +1 -1
  97. package/dist/index.browser.d.ts +1 -1
  98. package/dist/index.browser.d.ts.map +1 -1
  99. package/dist/index.browser.js +1 -1
  100. package/dist/index.browser.js.map +1 -1
  101. package/dist/index.d.ts +1 -1
  102. package/dist/index.d.ts.map +1 -1
  103. package/dist/index.js +1 -1
  104. package/dist/index.js.map +1 -1
  105. package/dist/mcp/server.d.ts +4 -2
  106. package/dist/mcp/server.d.ts.map +1 -1
  107. package/dist/mcp/server.js +33 -4
  108. package/dist/mcp/server.js.map +1 -1
  109. package/dist/provider-api/index.d.ts.map +1 -1
  110. package/dist/provider-api/index.js +14 -6
  111. package/dist/provider-api/index.js.map +1 -1
  112. package/dist/server/agent-teams.d.ts +4 -1
  113. package/dist/server/agent-teams.d.ts.map +1 -1
  114. package/dist/server/agent-teams.js +104 -28
  115. package/dist/server/agent-teams.js.map +1 -1
  116. package/dist/server/auth.d.ts.map +1 -1
  117. package/dist/server/auth.js +21 -11
  118. package/dist/server/auth.js.map +1 -1
  119. package/dist/server/core-routes-plugin.js +2 -2
  120. package/dist/server/core-routes-plugin.js.map +1 -1
  121. package/dist/server/request-context.d.ts +3 -4
  122. package/dist/server/request-context.d.ts.map +1 -1
  123. package/dist/server/request-context.js.map +1 -1
  124. package/dist/server/security-headers.d.ts +16 -19
  125. package/dist/server/security-headers.d.ts.map +1 -1
  126. package/dist/server/security-headers.js +24 -25
  127. package/dist/server/security-headers.js.map +1 -1
  128. package/dist/server/self-dispatch.d.ts.map +1 -1
  129. package/dist/server/self-dispatch.js +17 -1
  130. package/dist/server/self-dispatch.js.map +1 -1
  131. package/dist/server/ssr-handler.d.ts.map +1 -1
  132. package/dist/server/ssr-handler.js +9 -18
  133. package/dist/server/ssr-handler.js.map +1 -1
  134. package/dist/templates/default/AGENTS.md +1 -1
  135. package/dist/templates/default/DEVELOPING.md +7 -13
  136. package/dist/templates/workspace-core/AGENTS.md +6 -4
  137. package/dist/templates/workspace-root/AGENTS.md +6 -4
  138. package/docs/content/actions.md +5 -7
  139. package/docs/content/client.md +49 -44
  140. package/docs/content/context-awareness.md +20 -33
  141. package/docs/content/creating-templates.md +2 -2
  142. package/docs/content/external-agents.md +1 -1
  143. package/docs/content/key-concepts.md +3 -3
  144. package/docs/content/sharing.md +1 -1
  145. package/docs/content/template-mail.md +1 -1
  146. package/docs/content/voice-input.md +1 -1
  147. package/package.json +5 -1
  148. package/src/templates/default/AGENTS.md +1 -1
  149. package/src/templates/default/DEVELOPING.md +7 -13
  150. package/src/templates/workspace-core/AGENTS.md +6 -4
  151. package/src/templates/workspace-root/AGENTS.md +6 -4
@@ -50,10 +50,9 @@ export interface RequestContext {
50
50
  orgId?: string;
51
51
  timezone?: string;
52
52
  /**
53
- * Set when SSR code reads authenticated request context. The SSR cache layer
54
- * uses this as a last-resort leak guard: public shell/data should not read
55
- * user/org state during render, but older templates still do. Routes that
56
- * need CDN caching should move those reads behind client-side actions/API.
53
+ * Set when code reads authenticated request context. Public SSR shell/data
54
+ * should not depend on this value; user/org-specific reads belong behind
55
+ * client-side actions/API after hydration.
57
56
  */
58
57
  authContextAccessed?: boolean;
59
58
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"request-context.d.ts","sourceRoot":"","sources":["../../src/server/request-context.ts"],"names":[],"mappings":"AAmBA;;;;;;;;;;GAUG;AACH,MAAM,WAAW,iBAAiB;IAChC,wEAAwE;IACxE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,mEAAmE;IACnE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,wEAAwE;IACxE,SAAS,CAAC,EAAE;QACV,IAAI,EAAE,MAAM,CAAC;QACb,EAAE,EAAE,MAAM,CAAC;QACX,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,GAAG,IAAI,CAAC;IACT,gDAAgD;IAChD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4DAA4D;IAC5D,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,yDAAyD;IACzD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6DAA6D;IAC7D,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,8DAA8D;IAC9D,MAAM,CAAC,EAAE,OAAO,0BAA0B,EAAE,WAAW,CAAC;IACxD,yDAAyD;IACzD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,SAAS,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IACpD,8DAA8D;IAC9D,WAAW,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC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;GAMG;AACH,wBAAgB,eAAe,IAAI,MAAM,GAAG,SAAS,CAOpD;AASD,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,cAAc,GAAG,SAAS,GAAG,OAAO,CAE7E;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,GAAG,SAAS,CAIvD;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,IAAI,OAAO,CAEpD;AAED,wBAAgB,4BAA4B,IACxC,WAAW,CAAC,cAAc,CAAC,aAAa,CAAC,CAAC,GAC1C,SAAS,CAEZ;AAED;;;;;;;;;GASG;AACH,wBAAgB,oBAAoB,IAAI;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB,GAAG,IAAI,CAIP;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,IAAI,iBAAiB,GAAG,SAAS,CAIpE;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,IAAI,iBAAiB,GAAG,SAAS,CAKvE"}
1
+ {"version":3,"file":"request-context.d.ts","sourceRoot":"","sources":["../../src/server/request-context.ts"],"names":[],"mappings":"AAmBA;;;;;;;;;;GAUG;AACH,MAAM,WAAW,iBAAiB;IAChC,wEAAwE;IACxE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,mEAAmE;IACnE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,wEAAwE;IACxE,SAAS,CAAC,EAAE;QACV,IAAI,EAAE,MAAM,CAAC;QACb,EAAE,EAAE,MAAM,CAAC;QACX,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,GAAG,IAAI,CAAC;IACT,gDAAgD;IAChD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4DAA4D;IAC5D,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,yDAAyD;IACzD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6DAA6D;IAC7D,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,8DA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EAAE,cAAc,EACnB,EAAE,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GACvB,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAahB;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,IAAI,cAAc,GAAG,SAAS,CAI9D;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,IAAI,OAAO,CAE3C;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,GAAG,SAAS,CAOxD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,GAAG,SAAS,CAOvD;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,IAAI,MAAM,GAAG,SAAS,CAOpD;AASD,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,cAAc,GAAG,SAAS,GAAG,OAAO,CAE7E;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,GAAG,SAAS,CAIvD;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,IAAI,OAAO,CAEpD;AAED,wBAAgB,4BAA4B,IACxC,WAAW,CAAC,cAAc,CAAC,aAAa,CAAC,CAAC,GAC1C,SAAS,CAEZ;AAED;;;;;;;;;GASG;AACH,wBAAgB,oBAAoB,IAAI;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB,GAAG,IAAI,CAIP;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,IAAI,iBAAiB,GAAG,SAAS,CAIpE;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,IAAI,iBAAiB,GAAG,SAAS,CAKvE"}
@@ -1 +1 @@
1
- {"version":3,"file":"request-context.js","sourceRoot":"","sources":["../../src/server/request-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAwFrD,MAAM,UAAU,GAAG,g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ACrC,MAAM,KAAK,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAC;IAC7B,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,IAAI,CAAC,KAAK,CAAC,GAAG;QAAE,KAAK,CAAC,GAAG,GAAG,EAAE,CAAC;IAC/B,OAAO,KAAK,CAAC,GAAG,CAAC;AACnB,CAAC","sourcesContent":["/**\n * Per-request context using AsyncLocalStorage.\n *\n * Replaces the unsafe pattern of mutating `process.env.AGENT_USER_EMAIL` /\n * `process.env.AGENT_ORG_ID` on every request. On Node.js (Netlify, self-hosted)\n * concurrent requests would overwrite each other's env vars. AsyncLocalStorage\n * gives each async call-chain its own isolated context.\n *\n * Supported on all deployment targets:\n * - Node.js (native)\n * - Cloudflare Workers (via nodejs_compat flag)\n * - Deno Deploy (via node:async_hooks compat)\n *\n * For CLI scripts that run outside a request context, the getters fall back to\n * process.env so existing `AGENT_USER_EMAIL=x pnpm action foo` invocations\n * continue to work.\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\n/**\n * Per-request agent-run state. Lives on `RequestContext.run` so the\n * agent-chat plugin can populate fields as the run progresses (owner,\n * resolved API key, system prompt, engine, model, threadId) without\n * mutating module-scope `let` bindings — those leak across concurrent\n * requests on a single Node.js process.\n *\n * Mutated in-place by `prepareRun`, `onEngineResolved`, `onRunStart` so\n * tool factory closures (automation, fetch, team, builder-browser) read\n * the live per-request value via `getRequestRunContext()`.\n */\nexport interface RequestRunContext {\n /** Origin of the current request (used by the builder-browser tool). */\n requestOrigin?: string;\n /** Stable browser tab id for tab-scoped app-state reads/writes. */\n browserTabId?: string;\n /** Resource scope for the current chat thread, e.g. the active deck. */\n chatScope?: {\n type: string;\n id: string;\n label?: string;\n } | null;\n /** Resolved owner email (set by prepareRun). */\n owner?: string;\n /** Owner's active Anthropic API key (set by prepareRun). */\n userApiKey?: string;\n /** Thread ID for the current run (set by onRunStart). */\n threadId?: string;\n /** System prompt actually sent to the model for this run. */\n systemPrompt?: string;\n /** Engine instance for this run (set by onEngineResolved). */\n engine?: import(\"../agent/engine/types.js\").AgentEngine;\n /** Model name for this run (set by onEngineResolved). */\n model?: string;\n /** Tool calls made so far in the current agent loop. */\n toolCalls?: Array<{ name: string; input: unknown }>;\n /** Tool results returned so far in the current agent loop. */\n toolResults?: Array<{ name: string; content: string; isError: boolean }>;\n}\n\nexport interface RequestContext {\n userEmail?: string;\n userName?: string;\n orgId?: string;\n timezone?: string;\n /**\n * Set when SSR code reads authenticated request context. The SSR cache layer\n * uses this as a last-resort leak guard: public shell/data should not read\n * user/org state during render, but older templates still do. Routes that\n * need CDN caching should move those reads behind client-side actions/API.\n */\n authContextAccessed?: boolean;\n /**\n * Origin of the inbound request (e.g. `http://127.0.0.1:8100`). Set by the\n * MCP mount from the request headers so actions that build externally\n * fetchable URLs (e.g. design `export-coding-handoff`'s signed raw-code URL)\n * resolve the real local-workspace origin instead of a prod/localhost\n * fallback. Optional — absent on paths that don't populate it.\n */\n requestOrigin?: string;\n /**\n * True when this request is being processed by an integration-platform\n * webhook (Slack, Telegram, etc.) where the function timeout is the\n * binding constraint. Code that calls slow remote APIs can use this to apply\n * tighter budgets on this path while leaving normal agent-chat callers\n * (5+ min budget) unaffected.\n */\n isIntegrationCaller?: boolean;\n /**\n * Metadata for the currently-processing integration task. This lets tools\n * that start long-running remote work persist a continuation that can update\n * the originating platform thread after the current function budget ends.\n */\n integration?: {\n taskId: string;\n attempts?: number;\n incoming: import(\"../integrations/types.js\").IncomingMessage;\n placeholderRef?: string;\n };\n /**\n * Mutable per-request agent-run state. Populated by the agent-chat plugin\n * during a run; tool closures dereference it on each invocation.\n */\n run?: RequestRunContext;\n}\n\nconst GLOBAL_KEY = \"__agentNativeRequestContextAls\" as const;\nconst OBSERVERS_KEY = \"__agentNativeRequestContextObservers\" as const;\ntype RequestContextObserver = (ctx: RequestContext) => void;\ntype GlobalWithRequestContext = typeof globalThis & {\n [GLOBAL_KEY]?: AsyncLocalStorage<RequestContext>;\n [OBSERVERS_KEY]?: RequestContextObserver[];\n};\nconst globalRef = globalThis as GlobalWithRequestContext;\nif (!globalRef[GLOBAL_KEY]) {\n globalRef[GLOBAL_KEY] = new AsyncLocalStorage<RequestContext>();\n}\nif (!globalRef[OBSERVERS_KEY]) {\n globalRef[OBSERVERS_KEY] = [];\n}\nconst als = globalRef[GLOBAL_KEY]!;\nconst observers = globalRef[OBSERVERS_KEY]!;\n\n/**\n * Register a callback fired every time `runWithRequestContext` enters a new\n * scope. The hook runs INSIDE the AsyncLocalStorage scope, so observability\n * helpers that read the current isolation scope (e.g. Sentry) attach to the\n * right per-request context.\n *\n * Returned function unregisters the observer. Observers must never throw —\n * any error is swallowed so a misbehaving observer can't break the request\n * path.\n */\nexport function addRequestContextObserver(\n observer: RequestContextObserver,\n): () => void {\n observers.push(observer);\n return () => {\n const i = observers.indexOf(observer);\n if (i !== -1) observers.splice(i, 1);\n };\n}\n\n/**\n * Run a callback within a per-request context. The context is available to all\n * async operations spawned from `fn` via `getRequestUserEmail()` / `getRequestOrgId()`.\n *\n * Any registered `addRequestContextObserver` callbacks fire inside the new\n * scope before `fn` runs, so observability code can pin user/org info onto\n * isolation-scoped backends (Sentry, OpenTelemetry, etc.).\n */\nexport function runWithRequestContext<T>(\n ctx: RequestContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return als.run(ctx, () => {\n if (observers.length > 0) {\n for (const obs of observers) {\n try {\n obs(ctx);\n } catch {\n // Observers must never break the request path.\n }\n }\n }\n return fn();\n });\n}\n\n/**\n * Return the active request context, if this call chain is running under one.\n *\n * This is intentionally distinct from `getRequestUserEmail()`: callers that\n * have an active context with no authenticated user must not fall through to\n * process-wide CLI fallbacks such as `AGENT_USER_EMAIL` or \"latest session\".\n */\nexport function getRequestContext(): RequestContext | undefined {\n const store = als.getStore();\n markAuthContextAccess(store);\n return store;\n}\n\n/**\n * True when AsyncLocalStorage has an active context for this call chain.\n * Useful for helpers that support both HTTP requests and standalone CLI runs.\n */\nexport function hasRequestContext(): boolean {\n return als.getStore() !== undefined;\n}\n\n/**\n * Get the current request's user email.\n *\n * - If a request context exists (HTTP/A2A path), returns its `userEmail` —\n * even when that value is `undefined`. The env fallback MUST NOT fire here:\n * a stale process-wide `AGENT_USER_EMAIL` from a CLI run or previous bug\n * would leak into an unauthenticated A2A/API call (e.g. unsigned or API-key\n * modes where `runWithRequestContext({ userEmail: undefined })` is used).\n * - Only when there is NO request context (CLI scripts) do we fall back to\n * `process.env.AGENT_USER_EMAIL`.\n */\nexport function getRequestUserEmail(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) {\n if (store.userEmail) markAuthContextAccess(store);\n return store.userEmail;\n }\n return process.env.AGENT_USER_EMAIL;\n}\n\n/**\n * Get the current request's display name, when the auth provider supplied one.\n *\n * The same request-context fallback rules as `getRequestUserEmail()` apply:\n * HTTP/A2A calls only read AsyncLocalStorage, while CLI scripts may opt in via\n * `AGENT_USER_NAME`.\n */\nexport function getRequestUserName(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) {\n if (store.userName) markAuthContextAccess(store);\n return store.userName;\n }\n return process.env.AGENT_USER_NAME;\n}\n\n/**\n * Get the current request's org ID.\n *\n * Same store-aware semantics as `getRequestUserEmail()` — env fallback is\n * CLI-only, so a request that explicitly has no org doesn't inherit a stale\n * `process.env.AGENT_ORG_ID` from a prior request on the same Lambda instance.\n */\nexport function getRequestOrgId(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) {\n if (store.orgId) markAuthContextAccess(store);\n return store.orgId;\n }\n return process.env.AGENT_ORG_ID;\n}\n\nfunction markAuthContextAccess(ctx: RequestContext | undefined) {\n if (!ctx) return;\n if (ctx.userEmail || ctx.userName || ctx.orgId) {\n ctx.authContextAccessed = true;\n }\n}\n\nexport function hasAuthContextAccess(ctx: RequestContext | undefined): boolean {\n return Boolean(ctx?.authContextAccessed);\n}\n\n/**\n * Get the current request's IANA timezone (e.g. \"America/Los_Angeles\").\n * The UI sends this via the `x-user-timezone` header on every action call, and\n * the agent chat plugin propagates it into the request context so that\n * agent-initiated tool calls also see the user's timezone. Falls back to\n * `process.env.AGENT_USER_TIMEZONE` only for CLI scripts (no request context).\n */\nexport function getRequestTimezone(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) return store.timezone;\n return process.env.AGENT_USER_TIMEZONE;\n}\n\n/**\n * Returns true when this request is on an integration-platform path (Slack,\n * Telegram, etc.) — i.e. we're inside the integration plugin's processor\n * function and the platform's deliver-by deadline plus the host's function\n * timeout are the binding budget. Non-integration callers (CLI, normal\n * agent chat) should treat this as `false`.\n */\nexport function isIntegrationCallerRequest(): boolean {\n return als.getStore()?.isIntegrationCaller === true;\n}\n\nexport function getIntegrationRequestContext():\n | NonNullable<RequestContext[\"integration\"]>\n | undefined {\n return als.getStore()?.integration;\n}\n\n/**\n * Convenience: returns `{ userEmail, orgId }` from the active request context,\n * suitable for passing to `resolveCredential(key, ctx)`. Returns `null` when\n * no user is associated with the call (e.g. an unauthenticated public route).\n *\n * For framework actions auto-mounted at `/_agent-native/actions/...` this is\n * always populated because action-routes wraps every invocation in\n * `runWithRequestContext`. For hand-written `/api/*` routes the calling code\n * is responsible for setting up the context (see `runWithRequestContext`).\n */\nexport function getCredentialContext(): {\n userEmail: string;\n orgId: string | null;\n} | null {\n const userEmail = getRequestUserEmail();\n if (!userEmail) return null;\n return { userEmail, orgId: getRequestOrgId() ?? null };\n}\n\n/**\n * Get the active request's mutable agent-run state. Returns `undefined` when\n * called outside an agent run (e.g. before `prepareRun` or in a non-agent\n * code path). Callers must tolerate the field absence; use the helper\n * `requireRequestRunContext()` if missing context is a programming error.\n */\nexport function getRequestRunContext(): RequestRunContext | undefined {\n const store = als.getStore();\n if (!store) return undefined;\n return store.run;\n}\n\n/**\n * Ensure a `RequestRunContext` exists on the active request store and\n * return it. Used by the agent-chat handler to attach run state once it\n * starts processing a chat request. Returns `undefined` if there is no\n * active request store (caller should not be invoking this outside ALS).\n */\nexport function ensureRequestRunContext(): RequestRunContext | undefined {\n const store = als.getStore();\n if (!store) return undefined;\n if (!store.run) store.run = {};\n return store.run;\n}\n"]}
1
+ {"version":3,"file":"request-context.js","sourceRoot":"","sources":["../../src/server/request-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAuFrD,MAAM,UAAU,GAAG,gCAAyC,CAAC;AAC7D,MAAM,aAAa,GAAG,sCAA+C,CAAC;AAMtE,MAAM,SAAS,GAAG,UAAsC,CAAC;AACzD,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC;IAC3B,SAAS,CAAC,UAAU,CAAC,GAAG,IAAI,iBAAiB,EAAkB,CAAC;AAClE,CAAC;AACD,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,EAAE,CAAC;IAC9B,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,CAAC;AAChC,CAAC;AACD,MAAM,GAAG,GAAG,SAAS,CAAC,UAAU,CAAE,CAAC;AACnC,MAAM,SAAS,GAAG,SAAS,CAAC,aAAa,CAAE,CAAC;AAE5C;;;;;;;;;GASG;AACH,MAAM,UAAU,yBAAyB,CACvC,QAAgC;IAEhC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACzB,OAAO,GAAG,EAAE;QACV,MAAM,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACtC,IAAI,CAAC,KAAK,CAAC,CAAC;YAAE,SAAS,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACvC,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,qBAAqB,CACnC,GAAmB,EACnB,EAAwB;IAExB,OAAO,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE;QACvB,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzB,KAAK,MAAM,GAAG,IA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;AACzD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB;IAClC,MAAM,KAAK,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAC;IAC7B,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,KAAK,CAAC,GAAG,CAAC;AACnB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB;IACrC,MAAM,KAAK,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAC;IAC7B,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,IAAI,CAAC,KAAK,CAAC,GAAG;QAAE,KAAK,CAAC,GAAG,GAAG,EAAE,CAAC;IAC/B,OAAO,KAAK,CAAC,GAAG,CAAC;AACnB,CAAC","sourcesContent":["/**\n * Per-request context using AsyncLocalStorage.\n *\n * Replaces the unsafe pattern of mutating `process.env.AGENT_USER_EMAIL` /\n * `process.env.AGENT_ORG_ID` on every request. On Node.js (Netlify, self-hosted)\n * concurrent requests would overwrite each other's env vars. AsyncLocalStorage\n * gives each async call-chain its own isolated context.\n *\n * Supported on all deployment targets:\n * - Node.js (native)\n * - Cloudflare Workers (via nodejs_compat flag)\n * - Deno Deploy (via node:async_hooks compat)\n *\n * For CLI scripts that run outside a request context, the getters fall back to\n * process.env so existing `AGENT_USER_EMAIL=x pnpm action foo` invocations\n * continue to work.\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\n/**\n * Per-request agent-run state. Lives on `RequestContext.run` so the\n * agent-chat plugin can populate fields as the run progresses (owner,\n * resolved API key, system prompt, engine, model, threadId) without\n * mutating module-scope `let` bindings — those leak across concurrent\n * requests on a single Node.js process.\n *\n * Mutated in-place by `prepareRun`, `onEngineResolved`, `onRunStart` so\n * tool factory closures (automation, fetch, team, builder-browser) read\n * the live per-request value via `getRequestRunContext()`.\n */\nexport interface RequestRunContext {\n /** Origin of the current request (used by the builder-browser tool). */\n requestOrigin?: string;\n /** Stable browser tab id for tab-scoped app-state reads/writes. */\n browserTabId?: string;\n /** Resource scope for the current chat thread, e.g. the active deck. */\n chatScope?: {\n type: string;\n id: string;\n label?: string;\n } | null;\n /** Resolved owner email (set by prepareRun). */\n owner?: string;\n /** Owner's active Anthropic API key (set by prepareRun). */\n userApiKey?: string;\n /** Thread ID for the current run (set by onRunStart). */\n threadId?: string;\n /** System prompt actually sent to the model for this run. */\n systemPrompt?: string;\n /** Engine instance for this run (set by onEngineResolved). */\n engine?: import(\"../agent/engine/types.js\").AgentEngine;\n /** Model name for this run (set by onEngineResolved). */\n model?: string;\n /** Tool calls made so far in the current agent loop. */\n toolCalls?: Array<{ name: string; input: unknown }>;\n /** Tool results returned so far in the current agent loop. */\n toolResults?: Array<{ name: string; content: string; isError: boolean }>;\n}\n\nexport interface RequestContext {\n userEmail?: string;\n userName?: string;\n orgId?: string;\n timezone?: string;\n /**\n * Set when code reads authenticated request context. Public SSR shell/data\n * should not depend on this value; user/org-specific reads belong behind\n * client-side actions/API after hydration.\n */\n authContextAccessed?: boolean;\n /**\n * Origin of the inbound request (e.g. `http://127.0.0.1:8100`). Set by the\n * MCP mount from the request headers so actions that build externally\n * fetchable URLs (e.g. design `export-coding-handoff`'s signed raw-code URL)\n * resolve the real local-workspace origin instead of a prod/localhost\n * fallback. Optional — absent on paths that don't populate it.\n */\n requestOrigin?: string;\n /**\n * True when this request is being processed by an integration-platform\n * webhook (Slack, Telegram, etc.) where the function timeout is the\n * binding constraint. Code that calls slow remote APIs can use this to apply\n * tighter budgets on this path while leaving normal agent-chat callers\n * (5+ min budget) unaffected.\n */\n isIntegrationCaller?: boolean;\n /**\n * Metadata for the currently-processing integration task. This lets tools\n * that start long-running remote work persist a continuation that can update\n * the originating platform thread after the current function budget ends.\n */\n integration?: {\n taskId: string;\n attempts?: number;\n incoming: import(\"../integrations/types.js\").IncomingMessage;\n placeholderRef?: string;\n };\n /**\n * Mutable per-request agent-run state. Populated by the agent-chat plugin\n * during a run; tool closures dereference it on each invocation.\n */\n run?: RequestRunContext;\n}\n\nconst GLOBAL_KEY = \"__agentNativeRequestContextAls\" as const;\nconst OBSERVERS_KEY = \"__agentNativeRequestContextObservers\" as const;\ntype RequestContextObserver = (ctx: RequestContext) => void;\ntype GlobalWithRequestContext = typeof globalThis & {\n [GLOBAL_KEY]?: AsyncLocalStorage<RequestContext>;\n [OBSERVERS_KEY]?: RequestContextObserver[];\n};\nconst globalRef = globalThis as GlobalWithRequestContext;\nif (!globalRef[GLOBAL_KEY]) {\n globalRef[GLOBAL_KEY] = new AsyncLocalStorage<RequestContext>();\n}\nif (!globalRef[OBSERVERS_KEY]) {\n globalRef[OBSERVERS_KEY] = [];\n}\nconst als = globalRef[GLOBAL_KEY]!;\nconst observers = globalRef[OBSERVERS_KEY]!;\n\n/**\n * Register a callback fired every time `runWithRequestContext` enters a new\n * scope. The hook runs INSIDE the AsyncLocalStorage scope, so observability\n * helpers that read the current isolation scope (e.g. Sentry) attach to the\n * right per-request context.\n *\n * Returned function unregisters the observer. Observers must never throw —\n * any error is swallowed so a misbehaving observer can't break the request\n * path.\n */\nexport function addRequestContextObserver(\n observer: RequestContextObserver,\n): () => void {\n observers.push(observer);\n return () => {\n const i = observers.indexOf(observer);\n if (i !== -1) observers.splice(i, 1);\n };\n}\n\n/**\n * Run a callback within a per-request context. The context is available to all\n * async operations spawned from `fn` via `getRequestUserEmail()` / `getRequestOrgId()`.\n *\n * Any registered `addRequestContextObserver` callbacks fire inside the new\n * scope before `fn` runs, so observability code can pin user/org info onto\n * isolation-scoped backends (Sentry, OpenTelemetry, etc.).\n */\nexport function runWithRequestContext<T>(\n ctx: RequestContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return als.run(ctx, () => {\n if (observers.length > 0) {\n for (const obs of observers) {\n try {\n obs(ctx);\n } catch {\n // Observers must never break the request path.\n }\n }\n }\n return fn();\n });\n}\n\n/**\n * Return the active request context, if this call chain is running under one.\n *\n * This is intentionally distinct from `getRequestUserEmail()`: callers that\n * have an active context with no authenticated user must not fall through to\n * process-wide CLI fallbacks such as `AGENT_USER_EMAIL` or \"latest session\".\n */\nexport function getRequestContext(): RequestContext | undefined {\n const store = als.getStore();\n markAuthContextAccess(store);\n return store;\n}\n\n/**\n * True when AsyncLocalStorage has an active context for this call chain.\n * Useful for helpers that support both HTTP requests and standalone CLI runs.\n */\nexport function hasRequestContext(): boolean {\n return als.getStore() !== undefined;\n}\n\n/**\n * Get the current request's user email.\n *\n * - If a request context exists (HTTP/A2A path), returns its `userEmail` —\n * even when that value is `undefined`. The env fallback MUST NOT fire here:\n * a stale process-wide `AGENT_USER_EMAIL` from a CLI run or previous bug\n * would leak into an unauthenticated A2A/API call (e.g. unsigned or API-key\n * modes where `runWithRequestContext({ userEmail: undefined })` is used).\n * - Only when there is NO request context (CLI scripts) do we fall back to\n * `process.env.AGENT_USER_EMAIL`.\n */\nexport function getRequestUserEmail(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) {\n if (store.userEmail) markAuthContextAccess(store);\n return store.userEmail;\n }\n return process.env.AGENT_USER_EMAIL;\n}\n\n/**\n * Get the current request's display name, when the auth provider supplied one.\n *\n * The same request-context fallback rules as `getRequestUserEmail()` apply:\n * HTTP/A2A calls only read AsyncLocalStorage, while CLI scripts may opt in via\n * `AGENT_USER_NAME`.\n */\nexport function getRequestUserName(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) {\n if (store.userName) markAuthContextAccess(store);\n return store.userName;\n }\n return process.env.AGENT_USER_NAME;\n}\n\n/**\n * Get the current request's org ID.\n *\n * Same store-aware semantics as `getRequestUserEmail()` — env fallback is\n * CLI-only, so a request that explicitly has no org doesn't inherit a stale\n * `process.env.AGENT_ORG_ID` from a prior request on the same Lambda instance.\n */\nexport function getRequestOrgId(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) {\n if (store.orgId) markAuthContextAccess(store);\n return store.orgId;\n }\n return process.env.AGENT_ORG_ID;\n}\n\nfunction markAuthContextAccess(ctx: RequestContext | undefined) {\n if (!ctx) return;\n if (ctx.userEmail || ctx.userName || ctx.orgId) {\n ctx.authContextAccessed = true;\n }\n}\n\nexport function hasAuthContextAccess(ctx: RequestContext | undefined): boolean {\n return Boolean(ctx?.authContextAccessed);\n}\n\n/**\n * Get the current request's IANA timezone (e.g. \"America/Los_Angeles\").\n * The UI sends this via the `x-user-timezone` header on every action call, and\n * the agent chat plugin propagates it into the request context so that\n * agent-initiated tool calls also see the user's timezone. Falls back to\n * `process.env.AGENT_USER_TIMEZONE` only for CLI scripts (no request context).\n */\nexport function getRequestTimezone(): string | undefined {\n const store = als.getStore();\n if (store !== undefined) return store.timezone;\n return process.env.AGENT_USER_TIMEZONE;\n}\n\n/**\n * Returns true when this request is on an integration-platform path (Slack,\n * Telegram, etc.) — i.e. we're inside the integration plugin's processor\n * function and the platform's deliver-by deadline plus the host's function\n * timeout are the binding budget. Non-integration callers (CLI, normal\n * agent chat) should treat this as `false`.\n */\nexport function isIntegrationCallerRequest(): boolean {\n return als.getStore()?.isIntegrationCaller === true;\n}\n\nexport function getIntegrationRequestContext():\n | NonNullable<RequestContext[\"integration\"]>\n | undefined {\n return als.getStore()?.integration;\n}\n\n/**\n * Convenience: returns `{ userEmail, orgId }` from the active request context,\n * suitable for passing to `resolveCredential(key, ctx)`. Returns `null` when\n * no user is associated with the call (e.g. an unauthenticated public route).\n *\n * For framework actions auto-mounted at `/_agent-native/actions/...` this is\n * always populated because action-routes wraps every invocation in\n * `runWithRequestContext`. For hand-written `/api/*` routes the calling code\n * is responsible for setting up the context (see `runWithRequestContext`).\n */\nexport function getCredentialContext(): {\n userEmail: string;\n orgId: string | null;\n} | null {\n const userEmail = getRequestUserEmail();\n if (!userEmail) return null;\n return { userEmail, orgId: getRequestOrgId() ?? null };\n}\n\n/**\n * Get the active request's mutable agent-run state. Returns `undefined` when\n * called outside an agent run (e.g. before `prepareRun` or in a non-agent\n * code path). Callers must tolerate the field absence; use the helper\n * `requireRequestRunContext()` if missing context is a programming error.\n */\nexport function getRequestRunContext(): RequestRunContext | undefined {\n const store = als.getStore();\n if (!store) return undefined;\n return store.run;\n}\n\n/**\n * Ensure a `RequestRunContext` exists on the active request store and\n * return it. Used by the agent-chat handler to attach run state once it\n * starts processing a chat request. Returns `undefined` if there is no\n * active request store (caller should not be invoking this outside ALS).\n */\nexport function ensureRequestRunContext(): RequestRunContext | undefined {\n const store = als.getStore();\n if (!store) return undefined;\n if (!store.run) store.run = {};\n return store.run;\n}\n"]}
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * Sets a baseline set of "no-brainer" security headers on every framework HTTP
5
5
  * response. These headers are layered defenses: each one mitigates a specific
6
- * class of attack, and together they harden the surface against clickjacking,
7
- * MIME-sniffing, referrer leakage, mixed-content downgrades, and cross-origin
8
- * window/embed access.
6
+ * class of attack, and together they harden the surface against MIME-sniffing,
7
+ * referrer leakage, mixed-content downgrades, and cross-origin window/embed
8
+ * access.
9
9
  *
10
10
  * The headers we emit:
11
11
  *
@@ -16,15 +16,6 @@
16
16
  * - `X-Content-Type-Options: nosniff` — disables browser MIME sniffing so
17
17
  * a tool /render route serving user-authored HTML can't be misinterpreted
18
18
  * as some other content type by a clever Accept header.
19
- * - `X-Frame-Options: DENY` — prevents the entire app from being iframed by
20
- * other origins (clickjacking the agent chat, booking pages, etc.). The
21
- * tool /render endpoint and any other route that legitimately needs to be
22
- * embedded in the same-origin app shell can opt out by setting its own
23
- * header inside the route handler — h3's `setResponseHeader` overwrites,
24
- * so a route emitting `SAMEORIGIN` wins over our middleware default.
25
- * We skip this header entirely in dev (NODE_ENV !== "production") so the
26
- * desktop app's local dev frame (localhost:3334) can iframe templates
27
- * running on other localhost ports (e.g. mail at 8085).
28
19
  * - `Referrer-Policy: strict-origin-when-cross-origin` — strips path/query
29
20
  * from outbound Referer headers when the request crosses origin, so a
30
21
  * public-share viewer's outbound link clicks never leak the share token.
@@ -36,25 +27,31 @@
36
27
  * - `Cross-Origin-Opener-Policy: same-origin` — isolates window.opener so
37
28
  * a popup-window opener reference can't read or modify our document.
38
29
  * - `Cross-Origin-Embedder-Policy: require-corp` — emitted only for
39
- * validated MCP embed-session page loads. COEP hosts such as Claude's MCP
40
- * Apps proxy require framed cross-origin documents to opt in explicitly.
30
+ * validated MCP embed-session page loads and browser iframe navigations.
31
+ * COEP hosts such as Claude's MCP Apps proxy require framed cross-origin
32
+ * documents to opt in explicitly.
41
33
  * - `Cross-Origin-Resource-Policy: same-site` — prevents other origins from
42
34
  * embedding our endpoints as `<img>` / `<script>` / `<audio>`, blocking
43
35
  * the simplest data-leak chain when combined with auth cookies. Validated
44
- * MCP embed-session page loads use `cross-origin` so COEP hosts such as
45
- * Claude's MCP Apps proxy can frame the short-lived app document.
36
+ * MCP embed-session page loads and browser iframe navigations use
37
+ * `cross-origin` so COEP hosts can frame app documents.
46
38
  *
47
39
  * NOTE: `Cross-Origin-Embedder-Policy` is NOT set by default because it
48
40
  * requires every embedded subresource to opt in via CORP/CORS, which would
49
41
  * break Builder's iframe editor and template embed use cases. COOP + CORP
50
42
  * without COEP gives us most of the protection on normal responses; COEP is
51
- * only added for validated MCP embed-session page loads (see above).
43
+ * only added for validated MCP embed-session page loads and browser iframe
44
+ * navigations (see above).
45
+ *
46
+ * NOTE: `X-Frame-Options` is intentionally not set globally. Agent-native apps
47
+ * are expected to run inside iframe hosts such as Builder, Design, and MCP app
48
+ * shells. Routes that render especially sensitive iframe-only documents should
49
+ * set their own route-specific CSP / frame policy.
52
50
  */
53
51
  /**
54
52
  * Create the security-headers h3 middleware. Mount this BEFORE other route
55
53
  * handlers so the headers are present on every response (including 4xx/5xx
56
- * error pages). Route handlers that need to relax a specific header (e.g.
57
- * `X-Frame-Options: SAMEORIGIN` on the tool render route) can call
54
+ * error pages). Route handlers that need to tighten a specific header can call
58
55
  * `setResponseHeader` after this runs — the latest write wins.
59
56
  */
60
57
  export declare function createSecurityHeadersMiddleware(): import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, any>;
@@ -1 +1 @@
1
- {"version":3,"file":"security-headers.d.ts","sourceRoot":"","sources":["../../src/server/security-headers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AA2CH;;;;;;GAMG;AACH,wBAAgB,+BAA+B,8EA6C9C"}
1
+ {"version":3,"file":"security-headers.d.ts","sourceRoot":"","sources":["../../src/server/security-headers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AA+CH;;;;;GAKG;AACH,wBAAgB,+BAA+B,8EA4C9C"}
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * Sets a baseline set of "no-brainer" security headers on every framework HTTP
5
5
  * response. These headers are layered defenses: each one mitigates a specific
6
- * class of attack, and together they harden the surface against clickjacking,
7
- * MIME-sniffing, referrer leakage, mixed-content downgrades, and cross-origin
8
- * window/embed access.
6
+ * class of attack, and together they harden the surface against MIME-sniffing,
7
+ * referrer leakage, mixed-content downgrades, and cross-origin window/embed
8
+ * access.
9
9
  *
10
10
  * The headers we emit:
11
11
  *
@@ -16,15 +16,6 @@
16
16
  * - `X-Content-Type-Options: nosniff` — disables browser MIME sniffing so
17
17
  * a tool /render route serving user-authored HTML can't be misinterpreted
18
18
  * as some other content type by a clever Accept header.
19
- * - `X-Frame-Options: DENY` — prevents the entire app from being iframed by
20
- * other origins (clickjacking the agent chat, booking pages, etc.). The
21
- * tool /render endpoint and any other route that legitimately needs to be
22
- * embedded in the same-origin app shell can opt out by setting its own
23
- * header inside the route handler — h3's `setResponseHeader` overwrites,
24
- * so a route emitting `SAMEORIGIN` wins over our middleware default.
25
- * We skip this header entirely in dev (NODE_ENV !== "production") so the
26
- * desktop app's local dev frame (localhost:3334) can iframe templates
27
- * running on other localhost ports (e.g. mail at 8085).
28
19
  * - `Referrer-Policy: strict-origin-when-cross-origin` — strips path/query
29
20
  * from outbound Referer headers when the request crosses origin, so a
30
21
  * public-share viewer's outbound link clicks never leak the share token.
@@ -36,19 +27,26 @@
36
27
  * - `Cross-Origin-Opener-Policy: same-origin` — isolates window.opener so
37
28
  * a popup-window opener reference can't read or modify our document.
38
29
  * - `Cross-Origin-Embedder-Policy: require-corp` — emitted only for
39
- * validated MCP embed-session page loads. COEP hosts such as Claude's MCP
40
- * Apps proxy require framed cross-origin documents to opt in explicitly.
30
+ * validated MCP embed-session page loads and browser iframe navigations.
31
+ * COEP hosts such as Claude's MCP Apps proxy require framed cross-origin
32
+ * documents to opt in explicitly.
41
33
  * - `Cross-Origin-Resource-Policy: same-site` — prevents other origins from
42
34
  * embedding our endpoints as `<img>` / `<script>` / `<audio>`, blocking
43
35
  * the simplest data-leak chain when combined with auth cookies. Validated
44
- * MCP embed-session page loads use `cross-origin` so COEP hosts such as
45
- * Claude's MCP Apps proxy can frame the short-lived app document.
36
+ * MCP embed-session page loads and browser iframe navigations use
37
+ * `cross-origin` so COEP hosts can frame app documents.
46
38
  *
47
39
  * NOTE: `Cross-Origin-Embedder-Policy` is NOT set by default because it
48
40
  * requires every embedded subresource to opt in via CORP/CORS, which would
49
41
  * break Builder's iframe editor and template embed use cases. COOP + CORP
50
42
  * without COEP gives us most of the protection on normal responses; COEP is
51
- * only added for validated MCP embed-session page loads (see above).
43
+ * only added for validated MCP embed-session page loads and browser iframe
44
+ * navigations (see above).
45
+ *
46
+ * NOTE: `X-Frame-Options` is intentionally not set globally. Agent-native apps
47
+ * are expected to run inside iframe hosts such as Builder, Design, and MCP app
48
+ * shells. Routes that render especially sensitive iframe-only documents should
49
+ * set their own route-specific CSP / frame policy.
52
50
  */
53
51
  import { defineEventHandler, getHeader, setResponseHeader } from "h3";
54
52
  import { requestHasEmbedAuthMarker } from "./embed-session.js";
@@ -82,30 +80,31 @@ function isMcpEndpointRequest(event) {
82
80
  String(event?.node?.req?.url ?? event?.path ?? "/").split("?")[0];
83
81
  return (pathname === "/_agent-native/mcp" || pathname.endsWith("/_agent-native/mcp"));
84
82
  }
83
+ function isIframeNavigationRequest(event) {
84
+ return getHeader(event, "sec-fetch-dest") === "iframe";
85
+ }
85
86
  /**
86
87
  * Create the security-headers h3 middleware. Mount this BEFORE other route
87
88
  * handlers so the headers are present on every response (including 4xx/5xx
88
- * error pages). Route handlers that need to relax a specific header (e.g.
89
- * `X-Frame-Options: SAMEORIGIN` on the tool render route) can call
89
+ * error pages). Route handlers that need to tighten a specific header can call
90
90
  * `setResponseHeader` after this runs — the latest write wins.
91
91
  */
92
92
  export function createSecurityHeadersMiddleware() {
93
- const isProduction = process.env.NODE_ENV === "production";
94
93
  return defineEventHandler((event) => {
95
94
  const embedFrameRequest = requestHasEmbedAuthMarker(event);
96
95
  const mcpEndpointRequest = isMcpEndpointRequest(event);
96
+ const iframeNavigationRequest = isIframeNavigationRequest(event);
97
97
  const requestOrigin = getHeader(event, "origin");
98
98
  setResponseHeader(event, "X-Content-Type-Options", "nosniff");
99
- if (isProduction && !embedFrameRequest) {
100
- setResponseHeader(event, "X-Frame-Options", "DENY");
101
- }
102
99
  setResponseHeader(event, "Referrer-Policy", embedFrameRequest ? "no-referrer" : "strict-origin-when-cross-origin");
103
100
  setResponseHeader(event, "Permissions-Policy", PERMISSIONS_POLICY);
104
101
  setResponseHeader(event, "Cross-Origin-Opener-Policy", "same-origin");
105
- if (embedFrameRequest) {
102
+ if (embedFrameRequest || iframeNavigationRequest) {
106
103
  setResponseHeader(event, "Cross-Origin-Embedder-Policy", "require-corp");
107
104
  }
108
- setResponseHeader(event, "Cross-Origin-Resource-Policy", embedFrameRequest || mcpEndpointRequest ? "cross-origin" : "same-site");
105
+ setResponseHeader(event, "Cross-Origin-Resource-Policy", embedFrameRequest || mcpEndpointRequest || iframeNavigationRequest
106
+ ? "cross-origin"
107
+ : "same-site");
109
108
  if (embedFrameRequest && isMcpEmbedCorsOrigin(requestOrigin)) {
110
109
  setResponseHeader(event, "Access-Control-Allow-Origin", requestOrigin);
111
110
  setResponseHeader(event, "Vary", "Origin");
@@ -1 +1 @@
1
- {"version":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,iBAAiB,IAAI,kBAAkB,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,WAAW,CACvE,CAAC;QACF,IAAI,iBAAiB,IAAI,oBAAoB,CAAC,aAAa,CAAC,EAAE,CAAC;YAC7D,iBAAiB,CAAC,KAAK,EAAE,6BAA6B,EAAE,aAAa,CAAC,CAAC;YACvE,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC3C,iBAAiB,CACf,KAAK,EACL,8BAA8B,EAC9B,wCAAwC,CACzC,CAAC;YACF,iBAAiB,CACf,KAAK,EACL,8BAA8B,EAC9B,4BAA4B,CAC7B,CAAC;QACJ,CAAC;QACD,IAAI,cAAc,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1B,iBAAiB,CAAC,KAAK,EAAE,2BAA2B,EAAE,IAAI,CAAC,CAAC;QAC9D,CAAC;QACD,2EAA2E;QAC3E,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Security response headers middleware.\n *\n * Sets a baseline set of \"no-brainer\" security headers on every framework HTTP\n * response. These headers are layered defenses: each one mitigates a specific\n * class of attack, and together they harden the surface against clickjacking,\n * MIME-sniffing, referrer leakage, mixed-content downgrades, and cross-origin\n * window/embed access.\n *\n * The headers we emit:\n *\n * - `Strict-Transport-Security` — forces HTTPS for the browser's lifetime\n * of the cached value, preventing SSL-strip MITM. Only emitted when the\n * request scheme is `https` (we don't want to break local-dev HTTP, and\n * emitting HSTS over HTTP is a no-op per the spec but causes confusion).\n * - `X-Content-Type-Options: nosniff` — disables browser MIME sniffing so\n * a tool /render route serving user-authored HTML can't be misinterpreted\n * as some other content type by a clever Accept header.\n * - `X-Frame-Options: DENY` — prevents the entire app from being iframed by\n * other origins (clickjacking the agent chat, booking pages, etc.). The\n * tool /render endpoint and any other route that legitimately needs to be\n * embedded in the same-origin app shell can opt out by setting its own\n * header inside the route handler — h3's `setResponseHeader` overwrites,\n * so a route emitting `SAMEORIGIN` wins over our middleware default.\n * We skip this header entirely in dev (NODE_ENV !== \"production\") so the\n * desktop app's local dev frame (localhost:3334) can iframe templates\n * running on other localhost ports (e.g. mail at 8085).\n * - `Referrer-Policy: strict-origin-when-cross-origin` — strips path/query\n * from outbound Referer headers when the request crosses origin, so a\n * public-share viewer's outbound link clicks never leak the share token.\n * - `Permissions-Policy: camera=(), microphone=(self), geolocation=(),\n * screen-wake-lock=()` — allows the app shell to request microphone access\n * for composer dictation while keeping camera/location/wake-lock blocked\n * by default. Templates that need broader media capture for recording UI\n * override this on their own routes.\n * - `Cross-Origin-Opener-Policy: same-origin` — isolates window.opener so\n * a popup-window opener reference can't read or modify our document.\n * - `Cross-Origin-Embedder-Policy: require-corp` — emitted only for\n * validated MCP embed-session page loads. COEP hosts such as Claude's MCP\n * Apps proxy require framed cross-origin documents to opt in explicitly.\n * - `Cross-Origin-Resource-Policy: same-site` — prevents other origins from\n * embedding our endpoints as `<img>` / `<script>` / `<audio>`, blocking\n * the simplest data-leak chain when combined with auth cookies. Validated\n * MCP embed-session page loads use `cross-origin` so COEP hosts such as\n * Claude's MCP Apps proxy can frame the short-lived app document.\n *\n * NOTE: `Cross-Origin-Embedder-Policy` is NOT set by default because it\n * requires every embedded subresource to opt in via CORP/CORS, which would\n * break Builder's iframe editor and template embed use cases. COOP + CORP\n * without COEP gives us most of the protection on normal responses; COEP is\n * only added for validated MCP embed-session page loads (see above).\n */\n\nimport { defineEventHandler, getHeader, setResponseHeader } from \"h3\";\nimport { requestHasEmbedAuthMarker } from \"./embed-session.js\";\nimport {\n isMcpEmbedCorsOrigin,\n MCP_EMBED_CORS_ALLOW_HEADERS,\n} from \"../shared/mcp-embed-headers.js\";\n\nconst HSTS = \"max-age=31536000; includeSubDomains; preload\";\nconst PERMISSIONS_POLICY =\n \"camera=(), microphone=(self), geolocation=(), screen-wake-lock=()\";\n\n/**\n * Returns true when the request was received over HTTPS. We trust both the\n * underlying connection (when the server is terminating TLS itself) and the\n * `x-forwarded-proto` header (set by Netlify, Vercel, Cloudflare, and any\n * other reverse proxy that fronts the framework).\n */\nfunction isHttpsRequest(event: any): boolean {\n const xfp =\n event?.node?.req?.headers?.[\"x-forwarded-proto\"] ??\n event?.headers?.get?.(\"x-forwarded-proto\");\n if (typeof xfp === \"string\" && xfp.split(\",\")[0].trim() === \"https\")\n return true;\n if (Array.isArray(xfp) && xfp[0] === \"https\") return true;\n // h3 sets `event.url.protocol` to \"http:\" or \"https:\".\n const proto = event?.url?.protocol;\n if (proto === \"https:\") return true;\n // Direct Node `req.connection.encrypted` (older runtimes).\n if (event?.node?.req?.connection?.encrypted) return true;\n return false;\n}\n\nfunction isMcpEndpointRequest(event: any): boolean {\n const pathname =\n event?.url?.pathname ??\n String(event?.node?.req?.url ?? event?.path ?? \"/\").split(\"?\")[0];\n return (\n pathname === \"/_agent-native/mcp\" || pathname.endsWith(\"/_agent-native/mcp\")\n );\n}\n\n/**\n * Create the security-headers h3 middleware. Mount this BEFORE other route\n * handlers so the headers are present on every response (including 4xx/5xx\n * error pages). Route handlers that need to relax a specific header (e.g.\n * `X-Frame-Options: SAMEORIGIN` on the tool render route) can call\n * `setResponseHeader` after this runs — the latest write wins.\n */\nexport function createSecurityHeadersMiddleware() {\n const isProduction = process.env.NODE_ENV === \"production\";\n return defineEventHandler((event) => {\n const embedFrameRequest = requestHasEmbedAuthMarker(event);\n const mcpEndpointRequest = isMcpEndpointRequest(event);\n const requestOrigin = getHeader(event, \"origin\");\n setResponseHeader(event, \"X-Content-Type-Options\", \"nosniff\");\n if (isProduction && !embedFrameRequest) {\n setResponseHeader(event, \"X-Frame-Options\", \"DENY\");\n }\n setResponseHeader(\n event,\n \"Referrer-Policy\",\n embedFrameRequest ? \"no-referrer\" : \"strict-origin-when-cross-origin\",\n );\n setResponseHeader(event, \"Permissions-Policy\", PERMISSIONS_POLICY);\n setResponseHeader(event, \"Cross-Origin-Opener-Policy\", \"same-origin\");\n if (embedFrameRequest) {\n setResponseHeader(event, \"Cross-Origin-Embedder-Policy\", \"require-corp\");\n }\n setResponseHeader(\n event,\n \"Cross-Origin-Resource-Policy\",\n embedFrameRequest || mcpEndpointRequest ? \"cross-origin\" : \"same-site\",\n );\n if (embedFrameRequest && isMcpEmbedCorsOrigin(requestOrigin)) {\n setResponseHeader(event, \"Access-Control-Allow-Origin\", requestOrigin);\n setResponseHeader(event, \"Vary\", \"Origin\");\n setResponseHeader(\n event,\n \"Access-Control-Allow-Methods\",\n \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n );\n setResponseHeader(\n event,\n \"Access-Control-Allow-Headers\",\n MCP_EMBED_CORS_ALLOW_HEADERS,\n );\n }\n if (isHttpsRequest(event)) {\n setResponseHeader(event, \"Strict-Transport-Security\", HSTS);\n }\n // Continue to the next handler — we only set headers, don't return a body.\n return undefined;\n });\n}\n"]}
1
+ {"version":3,"file":"security-headers.js","sourceRoot":"","sources":["../../src/server/security-headers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AAEH,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EACL,oBAAoB,EACpB,4BAA4B,GAC7B,MAAM,gCAAgC,CAAC;AAExC,MAAM,IAAI,GAAG,8CAA8C,CAAC;AAC5D,MAAM,kBAAkB,GACtB,mEAAmE,CAAC;AAEtE;;;;;GAKG;AACH,SAAS,cAAc,CAAC,KAAU;IAChC,MAAM,GAAG,GACP,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,mBAAmB,CAAC;QAChD,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,mBAAmB,CAAC,CAAC;IAC7C,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,CAAC,KAAK,CAAC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AG,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;QACjD,iBAAiB,CAAC,KAAK,EAAE,wBAAwB,EAAE,SAAS,CAAC,CAAC;QAC9D,iBAAiB,CACf,KAAK,EACL,iBAAiB,EACjB,iBAAiB,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,iCAAiC,CACtE,CAAC;QACF,iBAAiB,CAAC,KAAK,EAAE,oBAAoB,EAAE,kBAAkB,CAAC,CAAC;QACnE,iBAAiB,CAAC,KAAK,EAAE,4BAA4B,EAAE,aAAa,CAAC,CAAC;QACtE,IAAI,iBAAiB,IAAI,uBAAuB,EAAE,CAAC;YACjD,iBAAiB,CAAC,KAAK,EAAE,8BAA8B,EAAE,cAAc,CAAC,CAAC;QAC3E,CAAC;QACD,iBAAiB,CACf,KAAK,EACL,8BAA8B,EAC9B,iBAAiB,IAAI,kBAAkB,IAAI,uBAAuB;YAChE,CAAC,CAAC,cAAc;YAChB,CAAC,CAAC,WAAW,CAChB,CAAC;QACF,IAAI,iBAAiB,IAAI,oBAAoB,CAAC,aAAa,CAAC,EAAE,CAAC;YAC7D,iBAAiB,CAAC,KAAK,EAAE,6BAA6B,EAAE,aAAa,CAAC,CAAC;YACvE,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC3C,iBAAiB,CACf,KAAK,EACL,8BAA8B,EAC9B,wCAAwC,CACzC,CAAC;YACF,iBAAiB,CACf,KAAK,EACL,8BAA8B,EAC9B,4BAA4B,CAC7B,CAAC;QACJ,CAAC;QACD,IAAI,cAAc,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1B,iBAAiB,CAAC,KAAK,EAAE,2BAA2B,EAAE,IAAI,CAAC,CAAC;QAC9D,CAAC;QACD,2EAA2E;QAC3E,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Security response headers middleware.\n *\n * Sets a baseline set of \"no-brainer\" security headers on every framework HTTP\n * response. These headers are layered defenses: each one mitigates a specific\n * class of attack, and together they harden the surface against MIME-sniffing,\n * referrer leakage, mixed-content downgrades, and cross-origin window/embed\n * access.\n *\n * The headers we emit:\n *\n * - `Strict-Transport-Security` — forces HTTPS for the browser's lifetime\n * of the cached value, preventing SSL-strip MITM. Only emitted when the\n * request scheme is `https` (we don't want to break local-dev HTTP, and\n * emitting HSTS over HTTP is a no-op per the spec but causes confusion).\n * - `X-Content-Type-Options: nosniff` — disables browser MIME sniffing so\n * a tool /render route serving user-authored HTML can't be misinterpreted\n * as some other content type by a clever Accept header.\n * - `Referrer-Policy: strict-origin-when-cross-origin` — strips path/query\n * from outbound Referer headers when the request crosses origin, so a\n * public-share viewer's outbound link clicks never leak the share token.\n * - `Permissions-Policy: camera=(), microphone=(self), geolocation=(),\n * screen-wake-lock=()` — allows the app shell to request microphone access\n * for composer dictation while keeping camera/location/wake-lock blocked\n * by default. Templates that need broader media capture for recording UI\n * override this on their own routes.\n * - `Cross-Origin-Opener-Policy: same-origin` — isolates window.opener so\n * a popup-window opener reference can't read or modify our document.\n * - `Cross-Origin-Embedder-Policy: require-corp` — emitted only for\n * validated MCP embed-session page loads and browser iframe navigations.\n * COEP hosts such as Claude's MCP Apps proxy require framed cross-origin\n * documents to opt in explicitly.\n * - `Cross-Origin-Resource-Policy: same-site` — prevents other origins from\n * embedding our endpoints as `<img>` / `<script>` / `<audio>`, blocking\n * the simplest data-leak chain when combined with auth cookies. Validated\n * MCP embed-session page loads and browser iframe navigations use\n * `cross-origin` so COEP hosts can frame app documents.\n *\n * NOTE: `Cross-Origin-Embedder-Policy` is NOT set by default because it\n * requires every embedded subresource to opt in via CORP/CORS, which would\n * break Builder's iframe editor and template embed use cases. COOP + CORP\n * without COEP gives us most of the protection on normal responses; COEP is\n * only added for validated MCP embed-session page loads and browser iframe\n * navigations (see above).\n *\n * NOTE: `X-Frame-Options` is intentionally not set globally. Agent-native apps\n * are expected to run inside iframe hosts such as Builder, Design, and MCP app\n * shells. Routes that render especially sensitive iframe-only documents should\n * set their own route-specific CSP / frame policy.\n */\n\nimport { defineEventHandler, getHeader, setResponseHeader } from \"h3\";\nimport { requestHasEmbedAuthMarker } from \"./embed-session.js\";\nimport {\n isMcpEmbedCorsOrigin,\n MCP_EMBED_CORS_ALLOW_HEADERS,\n} from \"../shared/mcp-embed-headers.js\";\n\nconst HSTS = \"max-age=31536000; includeSubDomains; preload\";\nconst PERMISSIONS_POLICY =\n \"camera=(), microphone=(self), geolocation=(), screen-wake-lock=()\";\n\n/**\n * Returns true when the request was received over HTTPS. We trust both the\n * underlying connection (when the server is terminating TLS itself) and the\n * `x-forwarded-proto` header (set by Netlify, Vercel, Cloudflare, and any\n * other reverse proxy that fronts the framework).\n */\nfunction isHttpsRequest(event: any): boolean {\n const xfp =\n event?.node?.req?.headers?.[\"x-forwarded-proto\"] ??\n event?.headers?.get?.(\"x-forwarded-proto\");\n if (typeof xfp === \"string\" && xfp.split(\",\")[0].trim() === \"https\")\n return true;\n if (Array.isArray(xfp) && xfp[0] === \"https\") return true;\n // h3 sets `event.url.protocol` to \"http:\" or \"https:\".\n const proto = event?.url?.protocol;\n if (proto === \"https:\") return true;\n // Direct Node `req.connection.encrypted` (older runtimes).\n if (event?.node?.req?.connection?.encrypted) return true;\n return false;\n}\n\nfunction isMcpEndpointRequest(event: any): boolean {\n const pathname =\n event?.url?.pathname ??\n String(event?.node?.req?.url ?? event?.path ?? \"/\").split(\"?\")[0];\n return (\n pathname === \"/_agent-native/mcp\" || pathname.endsWith(\"/_agent-native/mcp\")\n );\n}\n\nfunction isIframeNavigationRequest(event: any): boolean {\n return getHeader(event, \"sec-fetch-dest\") === \"iframe\";\n}\n\n/**\n * Create the security-headers h3 middleware. Mount this BEFORE other route\n * handlers so the headers are present on every response (including 4xx/5xx\n * error pages). Route handlers that need to tighten a specific header can call\n * `setResponseHeader` after this runs — the latest write wins.\n */\nexport function createSecurityHeadersMiddleware() {\n return defineEventHandler((event) => {\n const embedFrameRequest = requestHasEmbedAuthMarker(event);\n const mcpEndpointRequest = isMcpEndpointRequest(event);\n const iframeNavigationRequest = isIframeNavigationRequest(event);\n const requestOrigin = getHeader(event, \"origin\");\n setResponseHeader(event, \"X-Content-Type-Options\", \"nosniff\");\n setResponseHeader(\n event,\n \"Referrer-Policy\",\n embedFrameRequest ? \"no-referrer\" : \"strict-origin-when-cross-origin\",\n );\n setResponseHeader(event, \"Permissions-Policy\", PERMISSIONS_POLICY);\n setResponseHeader(event, \"Cross-Origin-Opener-Policy\", \"same-origin\");\n if (embedFrameRequest || iframeNavigationRequest) {\n setResponseHeader(event, \"Cross-Origin-Embedder-Policy\", \"require-corp\");\n }\n setResponseHeader(\n event,\n \"Cross-Origin-Resource-Policy\",\n embedFrameRequest || mcpEndpointRequest || iframeNavigationRequest\n ? \"cross-origin\"\n : \"same-site\",\n );\n if (embedFrameRequest && isMcpEmbedCorsOrigin(requestOrigin)) {\n setResponseHeader(event, \"Access-Control-Allow-Origin\", requestOrigin);\n setResponseHeader(event, \"Vary\", \"Origin\");\n setResponseHeader(\n event,\n \"Access-Control-Allow-Methods\",\n \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n );\n setResponseHeader(\n event,\n \"Access-Control-Allow-Headers\",\n MCP_EMBED_CORS_ALLOW_HEADERS,\n );\n }\n if (isHttpsRequest(event)) {\n setResponseHeader(event, \"Strict-Transport-Security\", HSTS);\n }\n // Continue to the next handler — we only set headers, don't return a body.\n return undefined;\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"self-dispatch.d.ts","sourceRoot":"","sources":["../../src/server/self-dispatch.ts"],"names":[],"mappings":"AA0BA;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,MAAM,CAAC;AAgB9C;;;;;;;;GAQG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,CAAC,EAAE,GAAG,GAAG,MAAM,CAoB9D;AAED,MAAM,WAAW,2BAA2B;IAC1C,oFAAoF;IACpF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,2EAA2E;IAC3E,KAAK,CAAC,EAAE,GAAG,CAAC;IACZ,wFAAwF;IACxF,IAAI,EAAE,MAAM,CAAC;IACb,iGAAiG;IACjG,MAAM,EAAE,MAAM,CAAC;IACf,qEAAqE;IACrE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,+EAA+E;IAC/E,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;;;GASG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,IAAI,CAAC,CAgCf"}
1
+ {"version":3,"file":"self-dispatch.d.ts","sourceRoot":"","sources":["../../src/server/self-dispatch.ts"],"names":[],"mappings":"AA0BA;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,MAAM,CAAC;AAgB9C;;;;;;;;GAQG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,CAAC,EAAE,GAAG,GAAG,MAAM,CAoB9D;AAED,MAAM,WAAW,2BAA2B;IAC1C,oFAAoF;IACpF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,2EAA2E;IAC3E,KAAK,CAAC,EAAE,GAAG,CAAC;IACZ,wFAAwF;IACxF,IAAI,EAAE,MAAM,CAAC;IACb,iGAAiG;IACjG,MAAM,EAAE,MAAM,CAAC;IACf,qEAAqE;IACrE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,+EAA+E;IAC/E,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAkBD;;;;;;;;;GASG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,IAAI,CAAC,CAqCf"}
@@ -71,6 +71,17 @@ export function resolveSelfDispatchBaseUrl(event) {
71
71
  const host = readHeader(event, "host") || `localhost:${process.env.PORT || 3000}`;
72
72
  return withConfiguredAppBasePath(`${proto}://${host}`);
73
73
  }
74
+ async function dispatchResponseError(path, res) {
75
+ let body = "";
76
+ try {
77
+ body = (await res.text()).trim();
78
+ }
79
+ catch {
80
+ body = "";
81
+ }
82
+ const detail = body ? `: ${body.slice(0, 300)}` : "";
83
+ return new Error(`Self-dispatch to ${path} returned HTTP ${res.status} ${res.statusText}${detail}`);
84
+ }
74
85
  /**
75
86
  * Fire a fresh, HMAC-signed POST to a processor route on this same deployment.
76
87
  * Fire-and-forget: the dispatch is NOT awaited to completion (the processed run
@@ -101,7 +112,12 @@ export async function fireInternalDispatch(options) {
101
112
  method: "POST",
102
113
  headers,
103
114
  body: JSON.stringify({ taskId: options.taskId, ...(options.body ?? {}) }),
104
- }).catch((err) => {
115
+ }).then(async (res) => {
116
+ if (!res.ok) {
117
+ throw await dispatchResponseError(options.path, res);
118
+ }
119
+ });
120
+ dispatchPromise.catch((err) => {
105
121
  console.error(`[self-dispatch] dispatch to ${options.path} failed:`, err);
106
122
  });
107
123
  const settleMs = options.settleMs ?? DEFAULT_DISPATCH_SETTLE_MS;
@@ -1 +1 @@
1
- {"version":3,"file":"self-dispatch.js","sourceRoot":"","sources":["../../src/server/self-dispatch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAEtE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,GAAG,CAAC;AAE9C,SAAS,UAAU,CAAC,KAAU,EAAE,IAAY;IAC1C,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,IAAI,KAAK,EAAE,OAAO,CAAC;QAC5D,IAAI,CAAC,OAAO;YAAE,OAAO,SAAS,CAAC;QAC/B,IAAI,OAAO,OAA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ch helper for the framework's serverless background-work\n * pattern: enqueue a unit of work to SQL, then fire a fresh HTTP POST back to\n * this same deployment so the work runs in its own function invocation (with\n * its own full timeout budget) instead of riding on the request that created\n * it.\n *\n * This is the single mechanism that makes background work portable across every\n * host Nitro deploys to:\n * - Netlify Lambda / Vercel Functions / AWS Lambda — the dispatched request\n * hits a fresh function with its own budget; no `waitUntil` needed.\n * - Cloudflare Workers — same (and `waitUntil` still works as a belt-and-\n * suspenders fallback where the in-process path is used).\n * - Self-hosted / long-lived Node — the dispatch comes back as another\n * request to the same process; each handler still runs to completion.\n *\n * Originally inlined in both `a2a/handlers.ts` (`resolveSelfBaseUrl` +\n * `fireProcessTaskDispatch`) and `integrations/webhook-handler.ts`\n * (`resolveBaseUrl` + the dispatch in `enqueueAndDispatch`). Extracted here so\n * A2A, integration webhooks, and Agent Teams sub-agents share one tested\n * implementation.\n */\nimport { withConfiguredAppBasePath } from \"./app-base-path.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\nimport { signInternalToken } from \"../integrations/internal-token.js\";\n\n/**\n * On serverless, returning from the dispatching handler before the outbound\n * TCP handshake starts can freeze the function with the dispatch request stuck\n * in the queue. Racing the fetch against a short timer gives the request a\n * chance to leave the box at the cost of a little added latency on the\n * dispatching call. Mirrors the 250ms used by the A2A/webhook paths.\n */\nexport const DEFAULT_DISPATCH_SETTLE_MS = 250;\n\nfunction readHeader(event: any, name: string): string | undefined {\n try {\n const headers = event?.node?.req?.headers ?? event?.headers;\n if (!headers) return undefined;\n if (typeof headers.get === \"function\") {\n return headers.get(name) ?? undefined;\n }\n const map = headers as Record<string, string | undefined>;\n return map[name] ?? map[String(name).toLowerCase()];\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolve the base URL to fire a self-dispatch request at. Prefers explicit env\n * vars (most reliable on serverless, where inbound host headers can be the\n * platform's internal hostname), falling back to the inbound request headers\n * and finally localhost in dev.\n *\n * Throws in production / shared deployments when no env var is set — a silent\n * fallback to a bad host there would drop background work invisibly.\n */\nexport function resolveSelfDispatchBaseUrl(event?: any): string {\n const fromEnv =\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL;\n if (fromEnv) return withConfiguredAppBasePath(String(fromEnv));\n\n if (process.env.NODE_ENV === \"production\" || !isLocalDatabase()) {\n throw new Error(\n \"Self-dispatch requires APP_URL, URL, DEPLOY_URL, or BETTER_AUTH_URL in \" +\n \"production/shared deployments so background work can reach this \" +\n \"deployment's own URL.\",\n );\n }\n\n const proto = readHeader(event, \"x-forwarded-proto\") || \"http\";\n const host =\n readHeader(event, \"host\") || `localhost:${process.env.PORT || 3000}`;\n return withConfiguredAppBasePath(`${proto}://${host}`);\n}\n\nexport interface FireInternalDispatchOptions {\n /** Base URL of this deployment. Defaults to `resolveSelfDispatchBaseUrl(event)`. */\n baseUrl?: string;\n /** Request event used to derive the base URL when `baseUrl` is omitted. */\n event?: any;\n /** Framework route path to POST to (e.g. \"/_agent-native/agent-teams/_process-run\"). */\n path: string;\n /** Task/run id the processor will claim. Used to sign the HMAC token and as the default body. */\n taskId: string;\n /** Extra fields merged into the JSON body alongside `{ taskId }`. */\n body?: Record<string, unknown>;\n /** Max ms to wait for the outbound request to leave the box. Default 250ms. */\n settleMs?: number;\n}\n\n/**\n * Fire a fresh, HMAC-signed POST to a processor route on this same deployment.\n * Fire-and-forget: the dispatch is NOT awaited to completion (the processed run\n * may take minutes); it is only raced against a short settle timer so the\n * request reliably leaves a serverless box before it freezes.\n *\n * When `A2A_SECRET` is unset (local dev), the request is sent unsigned — the\n * processor accepts unsigned dispatches in dev and relies on the SQL atomic\n * claim for double-processing protection, mirroring the A2A/webhook flow.\n */\nexport async function fireInternalDispatch(\n options: FireInternalDispatchOptions,\n): Promise<void> {\n const baseUrl = options.baseUrl ?? resolveSelfDispatchBaseUrl(options.event);\n const url = `${baseUrl}${options.path}`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(options.taskId)}`;\n } catch (err) {\n // Distinguish the documented \"no A2A_SECRET in dev\" path from a real\n // signing failure, so a malformed secret doesn't fail invisibly.\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[self-dispatch] signInternalToken failed unexpectedly for ${options.taskId}:`,\n err,\n );\n }\n }\n\n const dispatchPromise = fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ taskId: options.taskId, ...(options.body ?? {}) }),\n }).catch((err) => {\n console.error(`[self-dispatch] dispatch to ${options.path} failed:`, err);\n });\n\n const settleMs = options.settleMs ?? DEFAULT_DISPATCH_SETTLE_MS;\n await Promise.race([\n dispatchPromise,\n new Promise<void>((resolve) => setTimeout(resolve, settleMs)),\n ]);\n}\n"]}
1
+ {"version":3,"file":"self-dispatch.js","sourceRoot":"","sources":["../../src/server/self-dispatch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAEtE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,GAAG,CAAC;AAE9C,SAAS,UAAU,CAAC,KAAU,EAAE,IAAY;IAC1C,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,IAAI,KAAK,EAAE,OAAO,CAAC;QAC5D,IAAI,CAAC,OAAO;YAAE,OAAO,SAAS,CAAC;QAC/B,IAAI,OAAO,OAAO,CAAC,GAAG,KAAK,UAAU,EAAE,CAAC;YACtC,OAAO,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,SAAS,CAAC;QACxC,CAAC;QACD,MAAM,GAAG,GAAG,OAA6C,CAAC;QAC1D,OAAO,GAAG,CA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AC,GAAG,CAAC,EAAE,EAAE,CAAC;YACZ,MAAM,MAAM,qBAAqB,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QACvD,CAAC;IACH,CAAC,CAAC,CAAC;IACH,eAAe,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;QAC5B,OAAO,CAAC,KAAK,CAAC,+BAA+B,OAAO,CAAC,IAAI,UAAU,EAAE,GAAG,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;IAEH,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,0BAA0B,CAAC;IAChE,MAAM,OAAO,CAAC,IAAI,CAAC;QACjB,eAAe;QACf,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;KAC9D,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Shared self-dispatch helper for the framework's serverless background-work\n * pattern: enqueue a unit of work to SQL, then fire a fresh HTTP POST back to\n * this same deployment so the work runs in its own function invocation (with\n * its own full timeout budget) instead of riding on the request that created\n * it.\n *\n * This is the single mechanism that makes background work portable across every\n * host Nitro deploys to:\n * - Netlify Lambda / Vercel Functions / AWS Lambda — the dispatched request\n * hits a fresh function with its own budget; no `waitUntil` needed.\n * - Cloudflare Workers — same (and `waitUntil` still works as a belt-and-\n * suspenders fallback where the in-process path is used).\n * - Self-hosted / long-lived Node — the dispatch comes back as another\n * request to the same process; each handler still runs to completion.\n *\n * Originally inlined in both `a2a/handlers.ts` (`resolveSelfBaseUrl` +\n * `fireProcessTaskDispatch`) and `integrations/webhook-handler.ts`\n * (`resolveBaseUrl` + the dispatch in `enqueueAndDispatch`). Extracted here so\n * A2A, integration webhooks, and Agent Teams sub-agents share one tested\n * implementation.\n */\nimport { withConfiguredAppBasePath } from \"./app-base-path.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\nimport { signInternalToken } from \"../integrations/internal-token.js\";\n\n/**\n * On serverless, returning from the dispatching handler before the outbound\n * TCP handshake starts can freeze the function with the dispatch request stuck\n * in the queue. Racing the fetch against a short timer gives the request a\n * chance to leave the box at the cost of a little added latency on the\n * dispatching call. Mirrors the 250ms used by the A2A/webhook paths.\n */\nexport const DEFAULT_DISPATCH_SETTLE_MS = 250;\n\nfunction readHeader(event: any, name: string): string | undefined {\n try {\n const headers = event?.node?.req?.headers ?? event?.headers;\n if (!headers) return undefined;\n if (typeof headers.get === \"function\") {\n return headers.get(name) ?? undefined;\n }\n const map = headers as Record<string, string | undefined>;\n return map[name] ?? map[String(name).toLowerCase()];\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolve the base URL to fire a self-dispatch request at. Prefers explicit env\n * vars (most reliable on serverless, where inbound host headers can be the\n * platform's internal hostname), falling back to the inbound request headers\n * and finally localhost in dev.\n *\n * Throws in production / shared deployments when no env var is set — a silent\n * fallback to a bad host there would drop background work invisibly.\n */\nexport function resolveSelfDispatchBaseUrl(event?: any): string {\n const fromEnv =\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL;\n if (fromEnv) return withConfiguredAppBasePath(String(fromEnv));\n\n if (process.env.NODE_ENV === \"production\" || !isLocalDatabase()) {\n throw new Error(\n \"Self-dispatch requires APP_URL, URL, DEPLOY_URL, or BETTER_AUTH_URL in \" +\n \"production/shared deployments so background work can reach this \" +\n \"deployment's own URL.\",\n );\n }\n\n const proto = readHeader(event, \"x-forwarded-proto\") || \"http\";\n const host =\n readHeader(event, \"host\") || `localhost:${process.env.PORT || 3000}`;\n return withConfiguredAppBasePath(`${proto}://${host}`);\n}\n\nexport interface FireInternalDispatchOptions {\n /** Base URL of this deployment. Defaults to `resolveSelfDispatchBaseUrl(event)`. */\n baseUrl?: string;\n /** Request event used to derive the base URL when `baseUrl` is omitted. */\n event?: any;\n /** Framework route path to POST to (e.g. \"/_agent-native/agent-teams/_process-run\"). */\n path: string;\n /** Task/run id the processor will claim. Used to sign the HMAC token and as the default body. */\n taskId: string;\n /** Extra fields merged into the JSON body alongside `{ taskId }`. */\n body?: Record<string, unknown>;\n /** Max ms to wait for the outbound request to leave the box. Default 250ms. */\n settleMs?: number;\n}\n\nasync function dispatchResponseError(\n path: string,\n res: Response,\n): Promise<Error> {\n let body = \"\";\n try {\n body = (await res.text()).trim();\n } catch {\n body = \"\";\n }\n const detail = body ? `: ${body.slice(0, 300)}` : \"\";\n return new Error(\n `Self-dispatch to ${path} returned HTTP ${res.status} ${res.statusText}${detail}`,\n );\n}\n\n/**\n * Fire a fresh, HMAC-signed POST to a processor route on this same deployment.\n * Fire-and-forget: the dispatch is NOT awaited to completion (the processed run\n * may take minutes); it is only raced against a short settle timer so the\n * request reliably leaves a serverless box before it freezes.\n *\n * When `A2A_SECRET` is unset (local dev), the request is sent unsigned — the\n * processor accepts unsigned dispatches in dev and relies on the SQL atomic\n * claim for double-processing protection, mirroring the A2A/webhook flow.\n */\nexport async function fireInternalDispatch(\n options: FireInternalDispatchOptions,\n): Promise<void> {\n const baseUrl = options.baseUrl ?? resolveSelfDispatchBaseUrl(options.event);\n const url = `${baseUrl}${options.path}`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(options.taskId)}`;\n } catch (err) {\n // Distinguish the documented \"no A2A_SECRET in dev\" path from a real\n // signing failure, so a malformed secret doesn't fail invisibly.\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[self-dispatch] signInternalToken failed unexpectedly for ${options.taskId}:`,\n err,\n );\n }\n }\n\n const dispatchPromise = fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ taskId: options.taskId, ...(options.body ?? {}) }),\n }).then(async (res) => {\n if (!res.ok) {\n throw await dispatchResponseError(options.path, res);\n }\n });\n dispatchPromise.catch((err) => {\n console.error(`[self-dispatch] dispatch to ${options.path} failed:`, err);\n });\n\n const settleMs = options.settleMs ?? DEFAULT_DISPATCH_SETTLE_MS;\n await Promise.race([\n dispatchPromise,\n new Promise<void>((resolve) => setTimeout(resolve, settleMs)),\n ]);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-handler.d.ts","sourceRoot":"","sources":["../../src/server/ssr-handler.ts"],"names":[],"mappings":"AA4CA,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AAyWpC;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,2FAyE5E"}
1
+ {"version":3,"file":"ssr-handler.d.ts","sourceRoot":"","sources":["../../src/server/ssr-handler.ts"],"names":[],"mappings":"AAwCA,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AAiVpC;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,2FAuE5E"}
@@ -19,7 +19,7 @@ import { createRequestHandler } from "react-router";
19
19
  import { defineEventHandler } from "h3";
20
20
  import { getSentryClientConfigScript } from "./sentry-config.js";
21
21
  import { BETTER_AUTH_COOKIE_PREFIX, COOKIE_NAME, getSession } from "./auth.js";
22
- import { hasAuthContextAccess, runWithRequestContext, } from "./request-context.js";
22
+ import { runWithRequestContext } from "./request-context.js";
23
23
  import { requestHasEmbedAuthMarker } from "./embed-session.js";
24
24
  import { EMBED_SESSION_COOKIE, EMBED_TOKEN_QUERY_PARAM, } from "../shared/embed-auth.js";
25
25
  import { AGENT_NATIVE_SOCIAL_IMAGE_ALT, AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT, AGENT_NATIVE_SOCIAL_IMAGE_PATH, AGENT_NATIVE_SOCIAL_IMAGE_TYPE, AGENT_NATIVE_SOCIAL_IMAGE_WIDTH, } from "../shared/social-meta.js";
@@ -190,17 +190,9 @@ function isAuthenticatedCookieName(name) {
190
190
  bareName === `${BETTER_AUTH_COOKIE_PREFIX}.session_data` ||
191
191
  BETTER_AUTH_SESSION_COOKIE_RE.test(bareName));
192
192
  }
193
- function shouldUseDefaultSsrCacheHeader(headers, status, pathname, authContextAccessed) {
193
+ function shouldUseDefaultSsrCacheHeader(headers, status, pathname) {
194
194
  if (status < 200 || status >= 400)
195
195
  return false;
196
- if (authContextAccessed) {
197
- // Do not bypass cache just because a browser carries an auth-looking
198
- // cookie: public docs/pages can receive stale workspace cookies and should
199
- // still warm the CDN. But if SSR code actually reads user/org context,
200
- // that route is rendering private data and must not be public-cached.
201
- // Move those reads to client-side actions/API to regain CDN caching.
202
- return false;
203
- }
204
196
  const contentType = headers.get("content-type")?.toLowerCase() ?? "";
205
197
  if (contentType.includes("text/html")) {
206
198
  // SSR HTML is public app shell in this framework; any per-user state is
@@ -219,15 +211,14 @@ function shouldUseDefaultSsrCacheHeader(headers, status, pathname, authContextAc
219
211
  // routes. Keep `.data` on the same short-fresh/long-SWR policy as HTML so
220
212
  // route data fetches warm the CDN instead of hammering origin.
221
213
  // Do not re-add a blanket cookie/auth-signal bypass here: logged-in browsers
222
- // still need CDN-cached public route data. The auth-context leak guard above
223
- // is the narrow protection for old SSR loaders that still read user/org data.
214
+ // still need CDN-cached public route data.
224
215
  // Also do not preserve route-level private/no-store for React Router .data:
225
216
  // if a route needs per-user data, it belongs behind a client-side action/API
226
217
  // call rather than in the shared SSR payload.
227
218
  return true;
228
219
  }
229
- function applyDefaultSsrCacheHeader(headers, status, pathname, authContextAccessed) {
230
- if (!shouldUseDefaultSsrCacheHeader(headers, status, pathname, authContextAccessed)) {
220
+ function applyDefaultSsrCacheHeader(headers, status, pathname) {
221
+ if (!shouldUseDefaultSsrCacheHeader(headers, status, pathname)) {
231
222
  return;
232
223
  }
233
224
  // Netlify Functions/proxies are not cached by default, and production docs
@@ -272,10 +263,10 @@ function isFrameworkOrAssetPath(pathname) {
272
263
  pathname === "/favicon.png" ||
273
264
  (/\.\w+$/.test(pathname) && !pathname.endsWith(".data")));
274
265
  }
275
- async function rewriteMountedResponse(response, basePath, pathname, requestUrl, requestContext) {
266
+ async function rewriteMountedResponse(response, basePath, pathname, requestUrl) {
276
267
  const sentryClientConfigScript = getSentryClientConfigScript();
277
268
  const headers = new Headers(response.headers);
278
- applyDefaultSsrCacheHeader(headers, response.status, pathname, hasAuthContextAccess(requestContext));
269
+ applyDefaultSsrCacheHeader(headers, response.status, pathname);
279
270
  applyDefaultSpeculationRulesHeader(headers, response.status, basePath);
280
271
  const location = headers.get("location");
281
272
  if (location?.startsWith("/") && !location.startsWith("//")) {
@@ -342,9 +333,9 @@ export function createH3SSRHandler(getBuild) {
342
333
  status: response.status,
343
334
  statusText: response.statusText,
344
335
  headers: response.headers,
345
- }), basePath, p, request.url, ctx);
336
+ }), basePath, p, request.url);
346
337
  }
347
- return await rewriteMountedResponse(await runWithRequestContext(ctx, () => handler(request)), basePath, p, request.url, ctx);
338
+ return await rewriteMountedResponse(await runWithRequestContext(ctx, () => handler(request)), basePath, p, request.url);
348
339
  }
349
340
  catch (err) {
350
341
  // Log the full stack server-side, but never leak it to the client.