@frontmcp/sdk 1.9.7 → 1.10.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 (833) hide show
  1. package/agent/agent.registry.d.ts +3 -1
  2. package/agent/agent.registry.d.ts.map +1 -1
  3. package/agent/hooks/agent.hooks.d.ts +4 -4
  4. package/app/app.registry.d.ts.map +1 -1
  5. package/auth/auth.registry.d.ts +4 -6
  6. package/auth/auth.registry.d.ts.map +1 -1
  7. package/auth/direct-public-auth.d.ts +10 -0
  8. package/auth/direct-public-auth.d.ts.map +1 -0
  9. package/auth/primary-auth.factory.d.ts +4 -0
  10. package/auth/primary-auth.factory.d.ts.map +1 -0
  11. package/browser/adapter/adapter.instance.mjs +166 -0
  12. package/browser/adapter/adapter.registry.mjs +97 -0
  13. package/browser/adapter/adapter.utils.mjs +85 -0
  14. package/browser/agent/adapters/adapter.factory.mjs +168 -0
  15. package/browser/agent/adapters/anthropic.adapter.mjs +332 -0
  16. package/browser/agent/adapters/base.adapter.mjs +120 -0
  17. package/browser/agent/adapters/index.mjs +30 -0
  18. package/browser/agent/adapters/openai.adapter.mjs +551 -0
  19. package/browser/agent/adapters/providers/index.mjs +84 -0
  20. package/browser/agent/adapters/providers/types.mjs +0 -0
  21. package/browser/agent/agent-builtin-tools.mjs +193 -0
  22. package/browser/agent/agent-call-chain.mjs +22 -0
  23. package/browser/agent/agent-execution-loop.mjs +371 -0
  24. package/browser/agent/agent.events.mjs +133 -0
  25. package/browser/agent/agent.instance.mjs +869 -0
  26. package/browser/agent/agent.registry.mjs +398 -0
  27. package/browser/agent/agent.scope.mjs +352 -0
  28. package/browser/agent/agent.utils.mjs +161 -0
  29. package/browser/agent/flows/call-agent.flow.mjs +559 -0
  30. package/browser/agent/flows/index.mjs +5 -0
  31. package/browser/agent/hooks/agent.hooks.mjs +10 -0
  32. package/browser/agent/hooks/index.mjs +2 -0
  33. package/browser/agent/index.mjs +32 -0
  34. package/browser/app/app.registry.mjs +88 -0
  35. package/browser/app/app.utils.mjs +84 -0
  36. package/browser/app/instances/app.esm.instance.mjs +303 -0
  37. package/browser/app/instances/app.local.instance.mjs +120 -0
  38. package/browser/app/instances/app.remote.instance.mjs +397 -0
  39. package/browser/app/instances/esm-normalize.utils.mjs +100 -0
  40. package/browser/app/remote-capabilities.utils.mjs +18 -0
  41. package/browser/auth/auth-ui/auth-ui.contract.mjs +16 -0
  42. package/browser/auth/auth-ui/auth-ui.registry.mjs +262 -0
  43. package/browser/auth/auth-ui/auth-ui.render.mjs +127 -0
  44. package/browser/auth/auth-ui/auth-ui.state.mjs +86 -0
  45. package/browser/auth/auth-ui/index.mjs +35 -0
  46. package/browser/auth/auth.registry.mjs +200 -0
  47. package/browser/auth/auth.utils.mjs +80 -0
  48. package/browser/auth/authorization/orchestrated.context-extension.mjs +23 -0
  49. package/browser/auth/authorized-apps.utils.mjs +23 -0
  50. package/browser/auth/cimd/index.mjs +53 -0
  51. package/browser/auth/consent-tools.helper.mjs +32 -0
  52. package/browser/auth/consent.utils.mjs +31 -0
  53. package/browser/auth/credentials/credentials.context-extension.mjs +18 -0
  54. package/browser/auth/credentials/credentials.providers.mjs +45 -0
  55. package/browser/auth/credentials/index.mjs +11 -0
  56. package/browser/auth/direct-public-auth.mjs +21 -0
  57. package/browser/auth/flows/form-body.utils.mjs +14 -0
  58. package/browser/auth/flows/oauth.auth-ui.flow.mjs +135 -0
  59. package/browser/auth/flows/oauth.authorize.flow.mjs +1053 -0
  60. package/browser/auth/flows/oauth.callback.flow.mjs +1149 -0
  61. package/browser/auth/flows/oauth.connect.flow.mjs +296 -0
  62. package/browser/auth/flows/oauth.provider-callback.flow.mjs +829 -0
  63. package/browser/auth/flows/oauth.register.flow.mjs +304 -0
  64. package/browser/auth/flows/oauth.token.flow.mjs +417 -0
  65. package/browser/auth/flows/oauth.userinfo.flow.mjs +126 -0
  66. package/browser/auth/flows/session.verify.flow.mjs +529 -0
  67. package/browser/auth/flows/signin-binding.utils.mjs +72 -0
  68. package/browser/auth/flows/well-known.jwks.flow.mjs +113 -0
  69. package/browser/auth/flows/well-known.oauth-authorization-server.flow.mjs +215 -0
  70. package/browser/auth/flows/well-known.prm.flow.mjs +150 -0
  71. package/browser/auth/instances/instance.local-primary-auth.mjs +1466 -0
  72. package/browser/auth/instances/instance.remote-primary-auth.mjs +52 -0
  73. package/browser/auth/primary-auth.factory.mjs +34 -0
  74. package/browser/auth/public-access.utils.mjs +32 -0
  75. package/browser/auth/secure-store/index.mjs +11 -0
  76. package/browser/auth/secure-store/secure-store.context-extension.mjs +18 -0
  77. package/browser/auth/secure-store/secure-store.providers.mjs +46 -0
  78. package/browser/auth/session/session-store.factory.mjs +107 -0
  79. package/browser/auth/session/utils/session-id.utils.mjs +137 -0
  80. package/browser/auth/session-scope-identity.mjs +15 -0
  81. package/browser/builtin/config/config-resolver.mjs +82 -0
  82. package/browser/builtin/config/config.plugin.mjs +104 -0
  83. package/browser/builtin/config/config.symbols.mjs +7 -0
  84. package/browser/builtin/config/index.mjs +62 -0
  85. package/browser/builtin/config/providers/config-loader.mjs +99 -0
  86. package/browser/builtin/config/providers/config.service.mjs +153 -0
  87. package/browser/builtin/config/providers/env-loader.mjs +172 -0
  88. package/browser/channel/channel-notification.service.mjs +142 -0
  89. package/browser/channel/channel-scope.helper.mjs +175 -0
  90. package/browser/channel/channel.events.mjs +14 -0
  91. package/browser/channel/channel.instance.mjs +254 -0
  92. package/browser/channel/channel.registry.mjs +149 -0
  93. package/browser/channel/channel.utils.mjs +42 -0
  94. package/browser/channel/flows/list-channels.flow.mjs +78 -0
  95. package/browser/channel/flows/send-channel-notification.flow.mjs +121 -0
  96. package/browser/channel/index.mjs +20 -0
  97. package/browser/channel/reply/channel-reply.tool.mjs +80 -0
  98. package/browser/channel/reply/reply.types.mjs +10 -0
  99. package/browser/channel/sources/agent-completion.source.mjs +26 -0
  100. package/browser/channel/sources/app-event.source.mjs +74 -0
  101. package/browser/channel/sources/completion-events.mjs +45 -0
  102. package/browser/channel/sources/job-completion.source.mjs +24 -0
  103. package/browser/channel/sources/webhook.source.mjs +32 -0
  104. package/browser/common/availability/availability.utils.mjs +87 -0
  105. package/browser/common/availability/index.mjs +15 -0
  106. package/browser/common/decorators/adapter.decorator.mjs +17 -0
  107. package/browser/common/decorators/agent.decorator.mjs +87 -0
  108. package/browser/common/decorators/app.decorator.mjs +128 -0
  109. package/browser/common/decorators/auth-provider.decorator.mjs +17 -0
  110. package/browser/common/decorators/channel.decorator.mjs +49 -0
  111. package/browser/common/decorators/decorator-utils.mjs +116 -0
  112. package/browser/common/decorators/flow.decorator.mjs +16 -0
  113. package/browser/common/decorators/front-mcp.decorator.mjs +103 -0
  114. package/browser/common/decorators/hook.decorator.mjs +111 -0
  115. package/browser/common/decorators/index.mjs +18 -0
  116. package/browser/common/decorators/job.decorator.mjs +82 -0
  117. package/browser/common/decorators/logger.decorator.mjs +17 -0
  118. package/browser/common/decorators/plugin.decorator.mjs +41 -0
  119. package/browser/common/decorators/prompt.decorator.mjs +80 -0
  120. package/browser/common/decorators/provider.decorator.mjs +17 -0
  121. package/browser/common/decorators/resource.decorator.mjs +121 -0
  122. package/browser/common/decorators/skill.decorator.mjs +111 -0
  123. package/browser/common/decorators/tool.decorator.mjs +82 -0
  124. package/browser/common/decorators/workflow.decorator.mjs +36 -0
  125. package/browser/common/dynamic/dynamic.adapter.mjs +91 -0
  126. package/browser/common/dynamic/dynamic.plugin.mjs +64 -0
  127. package/browser/common/dynamic/dynamic.utils.mjs +67 -0
  128. package/browser/common/dynamic/index.mjs +3 -0
  129. package/browser/common/entries/adapter.entry.mjs +7 -0
  130. package/browser/common/entries/agent.entry.mjs +54 -0
  131. package/browser/common/entries/app.entry.mjs +17 -0
  132. package/browser/common/entries/auth-provider.entry.mjs +7 -0
  133. package/browser/common/entries/base.entry.mjs +16 -0
  134. package/browser/common/entries/channel.entry.mjs +43 -0
  135. package/browser/common/entries/flow.entry.mjs +21 -0
  136. package/browser/common/entries/hook.entry.mjs +19 -0
  137. package/browser/common/entries/index.mjs +19 -0
  138. package/browser/common/entries/job.entry.mjs +59 -0
  139. package/browser/common/entries/logger.entry.mjs +7 -0
  140. package/browser/common/entries/plugin.entry.mjs +7 -0
  141. package/browser/common/entries/prompt.entry.mjs +16 -0
  142. package/browser/common/entries/provider.entry.mjs +7 -0
  143. package/browser/common/entries/resource.entry.mjs +36 -0
  144. package/browser/common/entries/scope.entry.mjs +86 -0
  145. package/browser/common/entries/skill.entry.mjs +131 -0
  146. package/browser/common/entries/tool.entry.mjs +125 -0
  147. package/browser/common/entries/workflow.entry.mjs +29 -0
  148. package/browser/common/flow/flow.utils.mjs +58 -0
  149. package/browser/common/index.mjs +16 -0
  150. package/browser/common/interfaces/adapter.interface.mjs +0 -0
  151. package/browser/common/interfaces/agent.interface.mjs +577 -0
  152. package/browser/common/interfaces/app.interface.mjs +0 -0
  153. package/browser/common/interfaces/auth-hook.interface.mjs +24 -0
  154. package/browser/common/interfaces/auth-provider.interface.mjs +7 -0
  155. package/browser/common/interfaces/base.interface.mjs +0 -0
  156. package/browser/common/interfaces/channel.interface.mjs +90 -0
  157. package/browser/common/interfaces/execution-context.interface.mjs +388 -0
  158. package/browser/common/interfaces/flow.interface.mjs +114 -0
  159. package/browser/common/interfaces/front-mcp.interface.mjs +0 -0
  160. package/browser/common/interfaces/hook.interface.mjs +0 -0
  161. package/browser/common/interfaces/index.mjs +24 -0
  162. package/browser/common/interfaces/internal/flow.utils.mjs +81 -0
  163. package/browser/common/interfaces/internal/index.mjs +3 -0
  164. package/browser/common/interfaces/internal/primary-auth-provider.interface.mjs +69 -0
  165. package/browser/common/interfaces/internal/registry.interface.mjs +0 -0
  166. package/browser/common/interfaces/job.interface.mjs +81 -0
  167. package/browser/common/interfaces/llm-adapter.interface.mjs +9 -0
  168. package/browser/common/interfaces/logger.interface.mjs +9 -0
  169. package/browser/common/interfaces/plugin.interface.mjs +0 -0
  170. package/browser/common/interfaces/prompt.interface.mjs +47 -0
  171. package/browser/common/interfaces/provider.interface.mjs +7 -0
  172. package/browser/common/interfaces/resource.interface.mjs +91 -0
  173. package/browser/common/interfaces/scope.interface.mjs +0 -0
  174. package/browser/common/interfaces/server.interface.mjs +23 -0
  175. package/browser/common/interfaces/session-hook.interface.mjs +24 -0
  176. package/browser/common/interfaces/skill.interface.mjs +63 -0
  177. package/browser/common/interfaces/tool-hook.interface.mjs +39 -0
  178. package/browser/common/interfaces/tool.interface.mjs +350 -0
  179. package/browser/common/interfaces/workflow.interface.mjs +31 -0
  180. package/browser/common/metadata/adapter.metadata.mjs +10 -0
  181. package/browser/common/metadata/agent.metadata.mjs +110 -0
  182. package/browser/common/metadata/app-filter.metadata.mjs +29 -0
  183. package/browser/common/metadata/app.metadata.mjs +120 -0
  184. package/browser/common/metadata/auth-provider.metadata.mjs +17 -0
  185. package/browser/common/metadata/channel.metadata.mjs +73 -0
  186. package/browser/common/metadata/flow.metadata.mjs +15 -0
  187. package/browser/common/metadata/front-mcp.metadata.mjs +237 -0
  188. package/browser/common/metadata/hook.metadata.mjs +0 -0
  189. package/browser/common/metadata/index.mjs +26 -0
  190. package/browser/common/metadata/job.metadata.mjs +30 -0
  191. package/browser/common/metadata/logger.metadata.mjs +10 -0
  192. package/browser/common/metadata/output-policy.mjs +63 -0
  193. package/browser/common/metadata/plugin.metadata.mjs +37 -0
  194. package/browser/common/metadata/prompt.metadata.mjs +29 -0
  195. package/browser/common/metadata/provider.metadata.mjs +12 -0
  196. package/browser/common/metadata/remote-primitive.metadata.mjs +0 -0
  197. package/browser/common/metadata/resource.metadata.mjs +39 -0
  198. package/browser/common/metadata/skill.metadata.mjs +191 -0
  199. package/browser/common/metadata/tool-ui.metadata.mjs +0 -0
  200. package/browser/common/metadata/tool.metadata.mjs +108 -0
  201. package/browser/common/metadata/ui-serving-mode.mjs +21 -0
  202. package/browser/common/metadata/workflow.metadata.mjs +55 -0
  203. package/browser/common/providers/base-config.provider.mjs +118 -0
  204. package/browser/common/records/adapter.record.mjs +11 -0
  205. package/browser/common/records/agent.record.mjs +13 -0
  206. package/browser/common/records/app.record.mjs +9 -0
  207. package/browser/common/records/auth-provider.record.mjs +12 -0
  208. package/browser/common/records/channel.record.mjs +9 -0
  209. package/browser/common/records/flow.record.mjs +8 -0
  210. package/browser/common/records/hook.record.mjs +8 -0
  211. package/browser/common/records/index.mjs +22 -0
  212. package/browser/common/records/job.record.mjs +12 -0
  213. package/browser/common/records/logger.record.mjs +8 -0
  214. package/browser/common/records/plugin.record.mjs +11 -0
  215. package/browser/common/records/prompt.record.mjs +11 -0
  216. package/browser/common/records/provider.record.mjs +7 -0
  217. package/browser/common/records/resource.record.mjs +17 -0
  218. package/browser/common/records/scope.record.mjs +9 -0
  219. package/browser/common/records/skill.record.mjs +12 -0
  220. package/browser/common/records/tool.record.mjs +11 -0
  221. package/browser/common/records/workflow.record.mjs +12 -0
  222. package/browser/common/schemas/annotated-class.schema.mjs +311 -0
  223. package/browser/common/schemas/http-input.schema.mjs +16 -0
  224. package/browser/common/schemas/http-output.schema.mjs +315 -0
  225. package/browser/common/schemas/index.mjs +5 -0
  226. package/browser/common/schemas/session-header.schema.mjs +25 -0
  227. package/browser/common/tokens/adapter.tokens.mjs +11 -0
  228. package/browser/common/tokens/agent.tokens.mjs +35 -0
  229. package/browser/common/tokens/app.tokens.mjs +48 -0
  230. package/browser/common/tokens/auth-provider.tokens.mjs +12 -0
  231. package/browser/common/tokens/base.tokens.mjs +8 -0
  232. package/browser/common/tokens/channel.tokens.mjs +19 -0
  233. package/browser/common/tokens/flow-hook.tokens.mjs +10 -0
  234. package/browser/common/tokens/flow.tokens.mjs +16 -0
  235. package/browser/common/tokens/front-mcp.tokens.mjs +71 -0
  236. package/browser/common/tokens/index.mjs +19 -0
  237. package/browser/common/tokens/job.tokens.mjs +22 -0
  238. package/browser/common/tokens/logger.tokens.mjs +11 -0
  239. package/browser/common/tokens/plugin.tokens.mjs +23 -0
  240. package/browser/common/tokens/prompt.tokens.mjs +18 -0
  241. package/browser/common/tokens/provider.tokens.mjs +12 -0
  242. package/browser/common/tokens/resource.tokens.mjs +38 -0
  243. package/browser/common/tokens/server.tokens.mjs +17 -0
  244. package/browser/common/tokens/skill.tokens.mjs +37 -0
  245. package/browser/common/tokens/tool.tokens.mjs +41 -0
  246. package/browser/common/tokens/workflow.tokens.mjs +25 -0
  247. package/browser/common/types/auth/index.mjs +3 -0
  248. package/browser/common/types/auth/jwt.types.mjs +7 -0
  249. package/browser/common/types/auth/session.types.mjs +24 -0
  250. package/browser/common/types/common.types.mjs +0 -0
  251. package/browser/common/types/index.mjs +4 -0
  252. package/browser/common/types/options/auth/index.mjs +89 -0
  253. package/browser/common/types/options/elicitation/index.mjs +6 -0
  254. package/browser/common/types/options/elicitation/schema.mjs +14 -0
  255. package/browser/common/types/options/ext-apps/index.mjs +2 -0
  256. package/browser/common/types/options/ext-apps/schema.mjs +66 -0
  257. package/browser/common/types/options/health/index.mjs +7 -0
  258. package/browser/common/types/options/health/schema.mjs +24 -0
  259. package/browser/common/types/options/http/index.mjs +6 -0
  260. package/browser/common/types/options/http/schema.mjs +118 -0
  261. package/browser/common/types/options/index.mjs +18 -0
  262. package/browser/common/types/options/logging/index.mjs +8 -0
  263. package/browser/common/types/options/logging/interfaces.mjs +22 -0
  264. package/browser/common/types/options/logging/schema.mjs +20 -0
  265. package/browser/common/types/options/metrics/index.mjs +11 -0
  266. package/browser/common/types/options/metrics/schema.mjs +40 -0
  267. package/browser/common/types/options/observability/index.mjs +5 -0
  268. package/browser/common/types/options/observability/schema.mjs +13 -0
  269. package/browser/common/types/options/outbound-fetch/index.mjs +5 -0
  270. package/browser/common/types/options/outbound-fetch/schema.mjs +12 -0
  271. package/browser/common/types/options/pagination/index.mjs +7 -0
  272. package/browser/common/types/options/pagination/schema.mjs +20 -0
  273. package/browser/common/types/options/redis/index.mjs +25 -0
  274. package/browser/common/types/options/redis/schema.mjs +174 -0
  275. package/browser/common/types/options/registry/index.mjs +10 -0
  276. package/browser/common/types/options/registry/schema.mjs +28 -0
  277. package/browser/common/types/options/registry/utils.mjs +29 -0
  278. package/browser/common/types/options/server-info/index.mjs +5 -0
  279. package/browser/common/types/options/server-info/schema.mjs +13 -0
  280. package/browser/common/types/options/session/index.mjs +7 -0
  281. package/browser/common/types/options/session/schema.mjs +25 -0
  282. package/browser/common/types/options/skills-http/index.mjs +15 -0
  283. package/browser/common/types/options/skills-http/schema.mjs +130 -0
  284. package/browser/common/types/options/sqlite/index.mjs +7 -0
  285. package/browser/common/types/options/sqlite/resolve.mjs +56 -0
  286. package/browser/common/types/options/sqlite/schema.mjs +40 -0
  287. package/browser/common/types/options/transport/index.mjs +19 -0
  288. package/browser/common/types/options/transport/schema.mjs +194 -0
  289. package/browser/common/utils/auth-info.utils.mjs +29 -0
  290. package/browser/common/utils/caller-dir.utils.mjs +50 -0
  291. package/browser/common/utils/decide-request-intent.utils.mjs +362 -0
  292. package/browser/common/utils/enforced-metadata.utils.mjs +25 -0
  293. package/browser/common/utils/external-entry.utils.mjs +56 -0
  294. package/browser/common/utils/global-config.utils.mjs +11 -0
  295. package/browser/common/utils/guard.utils.mjs +107 -0
  296. package/browser/common/utils/index.mjs +10 -0
  297. package/browser/common/utils/list-all-pages.utils.mjs +24 -0
  298. package/browser/common/utils/path.utils.mjs +116 -0
  299. package/browser/common/utils/primitive-filter.mjs +39 -0
  300. package/browser/common/utils/principal.utils.mjs +46 -0
  301. package/browser/common/utils/tool-lookup.utils.mjs +32 -0
  302. package/browser/common/utils/validate-remote-url.mjs +10 -0
  303. package/browser/completion/flows/complete.flow.mjs +316 -0
  304. package/browser/context/call-surface.mjs +13 -0
  305. package/browser/context/context-extension.mjs +40 -0
  306. package/browser/context/frontmcp-context-storage.mjs +169 -0
  307. package/browser/context/frontmcp-context.mjs +575 -0
  308. package/browser/context/frontmcp-context.provider.mjs +21 -0
  309. package/browser/context/index.mjs +31 -0
  310. package/browser/context/metadata.utils.mjs +132 -0
  311. package/browser/context/running-flow.mjs +14 -0
  312. package/browser/context/running-tool.mjs +13 -0
  313. package/browser/context/trace-context.mjs +77 -0
  314. package/browser/direct/connect.mjs +97 -0
  315. package/browser/direct/create.mjs +109 -0
  316. package/browser/direct/direct-client.mjs +596 -0
  317. package/browser/direct/direct-server.mjs +235 -0
  318. package/browser/direct/index.mjs +19 -0
  319. package/browser/direct/llm-platform.mjs +208 -0
  320. package/browser/direct/runtime-tools.mjs +103 -0
  321. package/browser/elicitation/elicitation-fallback.schema.mjs +34 -0
  322. package/browser/elicitation/elicitation-meta.mjs +5 -0
  323. package/browser/elicitation/elicitation.types.mjs +7 -0
  324. package/browser/elicitation/flows/elicitation-request.flow.mjs +188 -0
  325. package/browser/elicitation/flows/elicitation-result.flow.mjs +189 -0
  326. package/browser/elicitation/flows/index.mjs +12 -0
  327. package/browser/elicitation/helpers/elicit.helper.mjs +85 -0
  328. package/browser/elicitation/helpers/extend-output-schema.mjs +31 -0
  329. package/browser/elicitation/helpers/fallback.helper.mjs +128 -0
  330. package/browser/elicitation/helpers/index.mjs +24 -0
  331. package/browser/elicitation/helpers/mrtr-request.helper.mjs +25 -0
  332. package/browser/elicitation/helpers/validate-elicitation-content.mjs +34 -0
  333. package/browser/elicitation/index.mjs +8 -0
  334. package/browser/elicitation/send-elicitation-result.tool.mjs +151 -0
  335. package/browser/elicitation/send-elicitation-result.utils.mjs +7 -0
  336. package/browser/elicitation/store/elicitation-encryption.mjs +101 -0
  337. package/browser/elicitation/store/elicitation-store.factory.mjs +224 -0
  338. package/browser/elicitation/store/encrypted-elicitation.store.mjs +392 -0
  339. package/browser/elicitation/store/index.mjs +39 -0
  340. package/browser/elicitation/store/storage-elicitation.store.mjs +470 -0
  341. package/browser/errors/agent.errors.mjs +139 -0
  342. package/browser/errors/auth-internal.errors.mjs +43 -0
  343. package/browser/errors/authorization-required.error.mjs +219 -0
  344. package/browser/errors/decorator.errors.mjs +16 -0
  345. package/browser/errors/elicitation.error.mjs +122 -0
  346. package/browser/errors/error-handler.mjs +91 -0
  347. package/browser/errors/esm.errors.mjs +88 -0
  348. package/browser/errors/external-entry.errors.mjs +68 -0
  349. package/browser/errors/index.mjs +414 -0
  350. package/browser/errors/job.errors.mjs +23 -0
  351. package/browser/errors/mcp.error.mjs +588 -0
  352. package/browser/errors/misconfiguration.mjs +53 -0
  353. package/browser/errors/mrtr.error.mjs +36 -0
  354. package/browser/errors/normalization.errors.mjs +34 -0
  355. package/browser/errors/plugin.errors.mjs +27 -0
  356. package/browser/errors/provider.errors.mjs +82 -0
  357. package/browser/errors/registry.errors.mjs +79 -0
  358. package/browser/errors/remote.errors.mjs +240 -0
  359. package/browser/errors/sdk.errors.mjs +180 -0
  360. package/browser/errors/session-identity-required.error.mjs +15 -0
  361. package/browser/errors/task.error.mjs +68 -0
  362. package/browser/errors/tool-call.error.mjs +15 -0
  363. package/browser/errors/tool-credentials-required.error.mjs +49 -0
  364. package/browser/errors/transport.errors.mjs +81 -0
  365. package/browser/errors/workflow.errors.mjs +28 -0
  366. package/browser/esm-loader/esm-auth.types.mjs +35 -0
  367. package/browser/esm-loader/esm-cache.mjs +270 -0
  368. package/browser/esm-loader/esm-entries.mjs +119 -0
  369. package/browser/esm-loader/esm-manifest.mjs +166 -0
  370. package/browser/esm-loader/esm-module-loader.mjs +224 -0
  371. package/browser/esm-loader/factories/esm-context-factories.mjs +34 -0
  372. package/browser/esm-loader/factories/esm-instance-factories.mjs +22 -0
  373. package/browser/esm-loader/factories/esm-record-builders.mjs +83 -0
  374. package/browser/esm-loader/factories/index.mjs +23 -0
  375. package/browser/esm-loader/index.mjs +73 -0
  376. package/browser/esm-loader/module-specifiers.mjs +172 -0
  377. package/browser/esm-loader/package-specifier.mjs +63 -0
  378. package/browser/esm-loader/semver.utils.mjs +37 -0
  379. package/browser/esm-loader/version-poller.mjs +150 -0
  380. package/browser/esm-loader/version-resolver.mjs +116 -0
  381. package/browser/ext-apps/ext-apps.handler.mjs +402 -0
  382. package/browser/ext-apps/ext-apps.types.mjs +24 -0
  383. package/browser/ext-apps/index.mjs +21 -0
  384. package/browser/flows/flow.http-path.mjs +43 -0
  385. package/browser/flows/flow.instance.mjs +478 -0
  386. package/browser/flows/flow.registry.mjs +147 -0
  387. package/browser/flows/flow.stages.mjs +88 -0
  388. package/browser/flows/flow.utils.mjs +30 -0
  389. package/browser/flows/resolved-entries.mjs +23 -0
  390. package/browser/front-mcp/authorities-engine.mjs +33 -0
  391. package/browser/front-mcp/authorities-rules.check.mjs +19 -0
  392. package/browser/front-mcp/direct-only.flag.mjs +13 -0
  393. package/browser/front-mcp/front-mcp.mjs +699 -0
  394. package/browser/front-mcp/front-mcp.providers.mjs +44 -0
  395. package/browser/front-mcp/front-mcp.tokens.mjs +5 -0
  396. package/browser/front-mcp/index.mjs +6 -0
  397. package/browser/front-mcp/serverless-handler.mjs +39 -0
  398. package/browser/front-mcp/shutdown-signals.mjs +32 -0
  399. package/browser/front-mcp/static-startup.check.mjs +181 -0
  400. package/browser/ha/ha-config.mjs +30 -0
  401. package/browser/ha/ha-headers.mjs +34 -0
  402. package/browser/ha/ha-manager.mjs +227 -0
  403. package/browser/ha/ha.constants.mjs +7 -0
  404. package/browser/ha/ha.types.mjs +13 -0
  405. package/browser/ha/heartbeat.service.mjs +95 -0
  406. package/browser/ha/index.mjs +25 -0
  407. package/browser/ha/notification-relay.mjs +74 -0
  408. package/browser/ha/relay-messages.mjs +7 -0
  409. package/browser/ha/session-takeover.mjs +42 -0
  410. package/browser/health/health.probes.mjs +72 -0
  411. package/browser/health/health.routes.mjs +38 -0
  412. package/browser/health/health.service.mjs +198 -0
  413. package/browser/health/index.mjs +13 -0
  414. package/browser/hooks/entry-class-hooks.mjs +39 -0
  415. package/browser/hooks/hook-coverage.mjs +33 -0
  416. package/browser/hooks/hook.instance.mjs +28 -0
  417. package/browser/hooks/hook.registry.mjs +178 -0
  418. package/browser/hooks/hooks.utils.mjs +91 -0
  419. package/browser/index.cjs +55575 -54583
  420. package/browser/index.mjs +191 -75307
  421. package/browser/job/enclave/index.mjs +7 -0
  422. package/browser/job/enclave/job-dynamic.executor.mjs +18 -0
  423. package/browser/job/enclave/job-enclave.bridge.mjs +105 -0
  424. package/browser/job/execution/index.mjs +5 -0
  425. package/browser/job/execution/job-execution.manager.mjs +308 -0
  426. package/browser/job/flows/execute-job.flow.mjs +246 -0
  427. package/browser/job/index.mjs +19 -0
  428. package/browser/job/job-attempt.mjs +53 -0
  429. package/browser/job/job-context-providers.mjs +26 -0
  430. package/browser/job/job-permission.guard.mjs +43 -0
  431. package/browser/job/job-scope.helper.mjs +107 -0
  432. package/browser/job/job.events.mjs +14 -0
  433. package/browser/job/job.instance.mjs +149 -0
  434. package/browser/job/job.registry.mjs +190 -0
  435. package/browser/job/job.utils.mjs +56 -0
  436. package/browser/job/store/index.mjs +17 -0
  437. package/browser/job/store/job-definition-store.factory.mjs +59 -0
  438. package/browser/job/store/job-definition.interface.mjs +0 -0
  439. package/browser/job/store/job-state-store.factory.mjs +28 -0
  440. package/browser/job/store/job-state.interface.mjs +0 -0
  441. package/browser/job/store/memory-job-definition.store.mjs +36 -0
  442. package/browser/job/store/memory-job-state.store.mjs +51 -0
  443. package/browser/job/store/redis-job-definition.store.mjs +100 -0
  444. package/browser/job/store/redis-job-state.store.mjs +93 -0
  445. package/browser/job/tools/execute-job.tool.mjs +57 -0
  446. package/browser/job/tools/get-job-status.tool.mjs +83 -0
  447. package/browser/job/tools/index.mjs +13 -0
  448. package/browser/job/tools/list-jobs.tool.mjs +80 -0
  449. package/browser/job/tools/register-job.tool.mjs +74 -0
  450. package/browser/job/tools/remove-job.tool.mjs +62 -0
  451. package/browser/logger/instances/instance.console-logger.mjs +78 -0
  452. package/browser/logger/instances/instance.file-logger.mjs +121 -0
  453. package/browser/logger/instances/instance.logger.mjs +80 -0
  454. package/browser/logger/logger.registry.mjs +136 -0
  455. package/browser/logger/logger.types.mjs +8 -0
  456. package/browser/logger/logger.utils.mjs +34 -0
  457. package/browser/logging/flows/set-level.flow.mjs +101 -0
  458. package/browser/mcp-registry/flows/index.mjs +9 -0
  459. package/browser/mcp-registry/flows/server-card.flow.mjs +136 -0
  460. package/browser/mcp-registry/flows/well-known.ai-catalog.flow.mjs +96 -0
  461. package/browser/mcp-registry/flows/well-known.mcp-registry-auth.flow.mjs +73 -0
  462. package/browser/mcp-registry/mcp-registry-scope.helper.mjs +15 -0
  463. package/browser/mcp-registry/mcp-registry.utils.mjs +34 -0
  464. package/browser/metrics/index.mjs +20 -0
  465. package/browser/metrics/metrics.errors.mjs +26 -0
  466. package/browser/metrics/metrics.routes.mjs +64 -0
  467. package/browser/metrics/metrics.service.mjs +121 -0
  468. package/browser/notification/index.mjs +25 -0
  469. package/browser/notification/notification.service.mjs +867 -0
  470. package/browser/plugin/enforced-metadata.check.mjs +90 -0
  471. package/browser/plugin/plugin.registry.mjs +273 -0
  472. package/browser/plugin/plugin.utils.mjs +107 -0
  473. package/browser/prompt/flows/get-prompt.flow.mjs +351 -0
  474. package/browser/prompt/flows/prompts-list.flow.mjs +269 -0
  475. package/browser/prompt/prompt.events.mjs +20 -0
  476. package/browser/prompt/prompt.instance.mjs +131 -0
  477. package/browser/prompt/prompt.registry.mjs +540 -0
  478. package/browser/prompt/prompt.types.mjs +10 -0
  479. package/browser/prompt/prompt.utils.mjs +94 -0
  480. package/browser/provider/flow-context-providers.mjs +30 -0
  481. package/browser/provider/provider.registry.mjs +994 -0
  482. package/browser/provider/provider.utils.mjs +108 -0
  483. package/browser/regsitry/index.mjs +2 -0
  484. package/browser/regsitry/registry.base.mjs +31 -0
  485. package/browser/remote-mcp/cache/capability-cache.mjs +131 -0
  486. package/browser/remote-mcp/cache/index.mjs +5 -0
  487. package/browser/remote-mcp/factories/context-factories.mjs +31 -0
  488. package/browser/remote-mcp/factories/index.mjs +31 -0
  489. package/browser/remote-mcp/factories/instance-factories.mjs +32 -0
  490. package/browser/remote-mcp/factories/record-builders.mjs +93 -0
  491. package/browser/remote-mcp/index.mjs +51 -0
  492. package/browser/remote-mcp/mcp-client.service.mjs +919 -0
  493. package/browser/remote-mcp/mcp-stateless-client.adapter.mjs +77 -0
  494. package/browser/remote-mcp/remote-entries.mjs +121 -0
  495. package/browser/remote-mcp/remote-request-headers.mjs +21 -0
  496. package/browser/remote-mcp/resilience/circuit-breaker.mjs +193 -0
  497. package/browser/remote-mcp/resilience/health-check.mjs +218 -0
  498. package/browser/remote-mcp/resilience/index.mjs +29 -0
  499. package/browser/remote-mcp/resilience/retry.mjs +80 -0
  500. package/browser/resource/flows/read-resource.flow.mjs +382 -0
  501. package/browser/resource/flows/resource-templates-list.flow.mjs +254 -0
  502. package/browser/resource/flows/resources-list.flow.mjs +272 -0
  503. package/browser/resource/flows/subscribe-resource.flow.mjs +132 -0
  504. package/browser/resource/flows/unsubscribe-resource.flow.mjs +102 -0
  505. package/browser/resource/resource.events.mjs +14 -0
  506. package/browser/resource/resource.instance.mjs +220 -0
  507. package/browser/resource/resource.registry.mjs +665 -0
  508. package/browser/resource/resource.types.mjs +10 -0
  509. package/browser/resource/resource.utils.mjs +157 -0
  510. package/browser/scope/flows/http.ip-filter.flow.mjs +45 -0
  511. package/browser/scope/flows/http.request.flow.mjs +872 -0
  512. package/browser/scope/flows/request-log.redaction.mjs +34 -0
  513. package/browser/scope/http-scope.helper.mjs +14 -0
  514. package/browser/scope/index.mjs +5 -0
  515. package/browser/scope/observability-scope.helper.mjs +131 -0
  516. package/browser/scope/optional-dependency.util.mjs +47 -0
  517. package/browser/scope/scope.instance.mjs +1478 -0
  518. package/browser/scope/scope.registry.mjs +121 -0
  519. package/browser/scope/scope.utils.mjs +61 -0
  520. package/browser/scope/server-entries.helper.mjs +20 -0
  521. package/browser/scope/startup-report.helper.mjs +16 -0
  522. package/browser/scope/tracer-provider.utils.mjs +14 -0
  523. package/browser/server/adapters/base.host.adapter.mjs +7 -0
  524. package/browser/server/custom-routes.helper.mjs +115 -0
  525. package/browser/server/middleware/cors-env.mjs +27 -0
  526. package/browser/server/middleware/csp.middleware.mjs +123 -0
  527. package/browser/server/noop-server.mjs +18 -0
  528. package/browser/server/security/host-validation.mjs +54 -0
  529. package/browser/server/security/resolve-allowed-hosts.mjs +75 -0
  530. package/browser/server/security/security-audit.mjs +148 -0
  531. package/browser/server/server.instance.mjs +173 -0
  532. package/browser/server/server.validation.mjs +169 -0
  533. package/browser/skill/auth/index.mjs +7 -0
  534. package/browser/skill/auth/skill-http-auth.mjs +209 -0
  535. package/browser/skill/cache/index.mjs +18 -0
  536. package/browser/skill/cache/skill-http-cache.factory.mjs +71 -0
  537. package/browser/skill/cache/skill-http-cache.holder.mjs +72 -0
  538. package/browser/skill/cache/skill-http-cache.mjs +150 -0
  539. package/browser/skill/errors/skill-validation.error.mjs +50 -0
  540. package/browser/skill/errors/tool-not-allowed.error.mjs +112 -0
  541. package/browser/skill/flows/filter-skills.flow.mjs +64 -0
  542. package/browser/skill/flows/http/index.mjs +9 -0
  543. package/browser/skill/flows/http/llm-full-txt.flow.mjs +174 -0
  544. package/browser/skill/flows/http/llm-txt.flow.mjs +173 -0
  545. package/browser/skill/flows/http/skills-api.flow.mjs +468 -0
  546. package/browser/skill/flows/index.mjs +13 -0
  547. package/browser/skill/flows/load-skill.flow.mjs +202 -0
  548. package/browser/skill/flows/search-skills.flow.mjs +149 -0
  549. package/browser/skill/guards/tool-authorization.guard.mjs +113 -0
  550. package/browser/skill/hooks/index.mjs +7 -0
  551. package/browser/skill/hooks/skill-tool.hook.mjs +100 -0
  552. package/browser/skill/index.mjs +213 -0
  553. package/browser/skill/providers/external-skill.provider.mjs +311 -0
  554. package/browser/skill/providers/memory-skill.provider.mjs +531 -0
  555. package/browser/skill/semantic/skill-semantic-search.interface.mjs +7 -0
  556. package/browser/skill/sep-2640/index.mjs +53 -0
  557. package/browser/skill/sep-2640/resources/index.mjs +13 -0
  558. package/browser/skill/sep-2640/resources/skill-file.resource.mjs +93 -0
  559. package/browser/skill/sep-2640/resources/skill-index.resource.mjs +78 -0
  560. package/browser/skill/sep-2640/resources/skill-md.resource.mjs +71 -0
  561. package/browser/skill/sep-2640/sep-2640.builders.mjs +97 -0
  562. package/browser/skill/sep-2640/sep-2640.constants.mjs +23 -0
  563. package/browser/skill/sep-2640/sep-2640.last-modified.mjs +18 -0
  564. package/browser/skill/sep-2640/sep-2640.per-skill.mjs +137 -0
  565. package/browser/skill/sep-2640/sep-2640.resource-helpers.mjs +230 -0
  566. package/browser/skill/sep-2640/sep-2640.uri.mjs +128 -0
  567. package/browser/skill/session/index.mjs +4 -0
  568. package/browser/skill/session/skill-session-store.interface.mjs +122 -0
  569. package/browser/skill/session/skill-session.manager.mjs +485 -0
  570. package/browser/skill/session/skill-session.types.mjs +73 -0
  571. package/browser/skill/skill-audit.helper.mjs +106 -0
  572. package/browser/skill/skill-authorities.helper.mjs +58 -0
  573. package/browser/skill/skill-directory-loader.mjs +154 -0
  574. package/browser/skill/skill-entry.resolver.mjs +35 -0
  575. package/browser/skill/skill-filter.helper.mjs +68 -0
  576. package/browser/skill/skill-http.utils.mjs +170 -0
  577. package/browser/skill/skill-instructions.helper.mjs +148 -0
  578. package/browser/skill/skill-md-parser.mjs +176 -0
  579. package/browser/skill/skill-mode.utils.mjs +25 -0
  580. package/browser/skill/skill-scope.helper.mjs +69 -0
  581. package/browser/skill/skill-storage.factory.mjs +86 -0
  582. package/browser/skill/skill-validator.mjs +100 -0
  583. package/browser/skill/skill.events.mjs +43 -0
  584. package/browser/skill/skill.instance.mjs +310 -0
  585. package/browser/skill/skill.registry.mjs +1258 -0
  586. package/browser/skill/skill.utils.mjs +379 -0
  587. package/browser/skill/sync/index.mjs +13 -0
  588. package/browser/skill/sync/memory-sync-state.store.mjs +51 -0
  589. package/browser/skill/sync/skill-hash.mjs +43 -0
  590. package/browser/skill/sync/sync-state.interface.mjs +27 -0
  591. package/browser/task/flows/tasks-cancel.flow.mjs +124 -0
  592. package/browser/task/flows/tasks-get.flow.mjs +89 -0
  593. package/browser/task/flows/tasks-list.flow.mjs +86 -0
  594. package/browser/task/flows/tasks-result.flow.mjs +190 -0
  595. package/browser/task/helpers/cli-task-runner.mjs +126 -0
  596. package/browser/task/helpers/in-process-task-runner.mjs +30 -0
  597. package/browser/task/helpers/process-liveness.mjs +20 -0
  598. package/browser/task/helpers/task-id.mjs +8 -0
  599. package/browser/task/helpers/task-notifier.mjs +30 -0
  600. package/browser/task/helpers/task-runner.mjs +128 -0
  601. package/browser/task/index.mjs +38 -0
  602. package/browser/task/runtime/execute-task-flag.mjs +10 -0
  603. package/browser/task/runtime/execute-task.mjs +142 -0
  604. package/browser/task/store/index.mjs +15 -0
  605. package/browser/task/store/storage-task.store.mjs +358 -0
  606. package/browser/task/store/task-backend.utils.mjs +14 -0
  607. package/browser/task/store/task-store.factory.mjs +122 -0
  608. package/browser/task/task-scope.helper.mjs +14 -0
  609. package/browser/task/task.registry.mjs +76 -0
  610. package/browser/task/task.types.mjs +33 -0
  611. package/browser/tool/flows/call-tool.flow.mjs +1134 -0
  612. package/browser/tool/flows/tool-credentials.gate.mjs +57 -0
  613. package/browser/tool/flows/tools-list.flow.mjs +503 -0
  614. package/browser/tool/tool-external.loader.mjs +13 -0
  615. package/browser/tool/tool.events.mjs +14 -0
  616. package/browser/tool/tool.instance.mjs +157 -0
  617. package/browser/tool/tool.registry.mjs +615 -0
  618. package/browser/tool/tool.types.mjs +10 -0
  619. package/browser/tool/tool.utils.mjs +365 -0
  620. package/browser/tool/ui/serving-mode-default.mjs +14 -0
  621. package/browser/tool/ui/template-detection.mjs +40 -0
  622. package/browser/tool/ui/template-helpers.mjs +44 -0
  623. package/browser/tool/ui/ui-option-warnings.mjs +67 -0
  624. package/browser/tool/ui/ui-render.mjs +60 -0
  625. package/browser/tool/ui/ui-resource-template.mjs +29 -0
  626. package/browser/tool/ui/ui-resource.handler.mjs +86 -0
  627. package/browser/tool/ui/ui-shared.mjs +239 -0
  628. package/browser/transport/adapters/polyfills/browser-sse-transport.mjs +9 -0
  629. package/browser/transport/adapters/sse-transport.mjs +70 -0
  630. package/browser/transport/adapters/streamable-http-transport.mjs +134 -0
  631. package/browser/transport/adapters/transport.local.adapter.mjs +380 -0
  632. package/browser/transport/adapters/transport.sse.adapter.mjs +167 -0
  633. package/browser/transport/adapters/transport.streamable-http.adapter.mjs +228 -0
  634. package/browser/transport/build-scoped-server-options.mjs +61 -0
  635. package/browser/transport/bus/index.mjs +5 -0
  636. package/browser/transport/bus/redis-transport-bus.mjs +164 -0
  637. package/browser/transport/event-stores/event-store.factory.mjs +79 -0
  638. package/browser/transport/event-stores/index.mjs +11 -0
  639. package/browser/transport/event-stores/memory.event-store.mjs +112 -0
  640. package/browser/transport/event-stores/redis.event-store.mjs +153 -0
  641. package/browser/transport/event-stores/session-scoped.event-store.mjs +40 -0
  642. package/browser/transport/flow-error-output.mjs +40 -0
  643. package/browser/transport/flows/handle.mcp-20260728.flow.mjs +395 -0
  644. package/browser/transport/flows/handle.sse.flow.mjs +216 -0
  645. package/browser/transport/flows/handle.stateless-http.flow.mjs +132 -0
  646. package/browser/transport/flows/handle.streamable-http.flow.mjs +613 -0
  647. package/browser/transport/in-memory-server.mjs +96 -0
  648. package/browser/transport/index.mjs +32 -0
  649. package/browser/transport/ipc-server.transport.mjs +48 -0
  650. package/browser/transport/mcp-20260728/client/header-params.mjs +75 -0
  651. package/browser/transport/mcp-20260728/client/index.mjs +3 -0
  652. package/browser/transport/mcp-20260728/client/mcp-stateless.client.mjs +368 -0
  653. package/browser/transport/mcp-20260728/discover.mjs +31 -0
  654. package/browser/transport/mcp-20260728/dispatcher.mjs +257 -0
  655. package/browser/transport/mcp-20260728/header-codec.mjs +48 -0
  656. package/browser/transport/mcp-20260728/index.mjs +13 -0
  657. package/browser/transport/mcp-20260728/mrtr.mjs +129 -0
  658. package/browser/transport/mcp-20260728/protocol-20260728.constants.mjs +47 -0
  659. package/browser/transport/mcp-20260728/request-notifications.mjs +86 -0
  660. package/browser/transport/mcp-20260728/request-state.mjs +111 -0
  661. package/browser/transport/mcp-20260728/request-validation.mjs +212 -0
  662. package/browser/transport/mcp-20260728/result-decorator.mjs +64 -0
  663. package/browser/transport/mcp-20260728/subscriptions.mjs +130 -0
  664. package/browser/transport/mcp-20260728/tasks-extension.mjs +118 -0
  665. package/browser/transport/mcp-handlers/Initialized-notification.hanlder.mjs +13 -0
  666. package/browser/transport/mcp-handlers/call-tool-error.utils.mjs +47 -0
  667. package/browser/transport/mcp-handlers/call-tool-request.handler.mjs +30 -0
  668. package/browser/transport/mcp-handlers/complete-request.handler.mjs +31 -0
  669. package/browser/transport/mcp-handlers/get-prompt-request.handler.mjs +33 -0
  670. package/browser/transport/mcp-handlers/index.mjs +62 -0
  671. package/browser/transport/mcp-handlers/initialize-request.handler.mjs +144 -0
  672. package/browser/transport/mcp-handlers/list-prompts-request.handler.mjs +31 -0
  673. package/browser/transport/mcp-handlers/list-resource-templates-request.handler.mjs +33 -0
  674. package/browser/transport/mcp-handlers/list-resources-request.handler.mjs +31 -0
  675. package/browser/transport/mcp-handlers/list-tools-request.handler.mjs +28 -0
  676. package/browser/transport/mcp-handlers/logging-set-level-request.handler.mjs +19 -0
  677. package/browser/transport/mcp-handlers/mcp-error.utils.mjs +42 -0
  678. package/browser/transport/mcp-handlers/mcp-surface.mjs +16 -0
  679. package/browser/transport/mcp-handlers/read-resource-request.handler.mjs +36 -0
  680. package/browser/transport/mcp-handlers/roots-list-changed-notification.handler.mjs +19 -0
  681. package/browser/transport/mcp-handlers/skills-list-request.handler.mjs +64 -0
  682. package/browser/transport/mcp-handlers/skills-load-request.handler.mjs +27 -0
  683. package/browser/transport/mcp-handlers/skills-mcp.types.mjs +113 -0
  684. package/browser/transport/mcp-handlers/skills-search-request.handler.mjs +27 -0
  685. package/browser/transport/mcp-handlers/subscribe-request.handler.mjs +19 -0
  686. package/browser/transport/mcp-handlers/tasks-cancel-request.handler.mjs +24 -0
  687. package/browser/transport/mcp-handlers/tasks-get-request.handler.mjs +24 -0
  688. package/browser/transport/mcp-handlers/tasks-list-request.handler.mjs +24 -0
  689. package/browser/transport/mcp-handlers/tasks-result-request.handler.mjs +24 -0
  690. package/browser/transport/mcp-handlers/unsubscribe-request.handler.mjs +19 -0
  691. package/browser/transport/persistent-session-owner.mjs +27 -0
  692. package/browser/transport/relay/relay-flow.mjs +28 -0
  693. package/browser/transport/relay/relay-http.mjs +343 -0
  694. package/browser/transport/relay/relay-scope.helper.mjs +89 -0
  695. package/browser/transport/relay/session-relay.mjs +276 -0
  696. package/browser/transport/session-mode.check.mjs +38 -0
  697. package/browser/transport/transport.error.mjs +25 -0
  698. package/browser/transport/transport.local.mjs +80 -0
  699. package/browser/transport/transport.registry.mjs +1038 -0
  700. package/browser/transport/transport.remote.mjs +57 -0
  701. package/browser/transport/transport.types.mjs +5 -0
  702. package/browser/transport/web-fetch-handler.mjs +408 -0
  703. package/browser/transport/web-http-route.mjs +70 -0
  704. package/browser/transport/web-response.renderer.mjs +93 -0
  705. package/browser/transport/web-standard-mcp.mjs +72 -0
  706. package/browser/utils/content.utils.mjs +61 -0
  707. package/browser/utils/dynamic-import.utils.mjs +15 -0
  708. package/browser/utils/index.mjs +24 -0
  709. package/browser/utils/lineage.utils.mjs +75 -0
  710. package/browser/utils/naming.utils.mjs +30 -0
  711. package/browser/workflow/engine/index.mjs +7 -0
  712. package/browser/workflow/engine/workflow-step.executor.mjs +75 -0
  713. package/browser/workflow/engine/workflow.engine.mjs +180 -0
  714. package/browser/workflow/index.mjs +11 -0
  715. package/browser/workflow/tools/execute-workflow.tool.mjs +58 -0
  716. package/browser/workflow/tools/get-workflow-status.tool.mjs +80 -0
  717. package/browser/workflow/tools/index.mjs +13 -0
  718. package/browser/workflow/tools/list-workflows.tool.mjs +75 -0
  719. package/browser/workflow/tools/register-workflow.tool.mjs +81 -0
  720. package/browser/workflow/tools/remove-workflow.tool.mjs +62 -0
  721. package/browser/workflow/workflow.events.mjs +14 -0
  722. package/browser/workflow/workflow.instance.mjs +29 -0
  723. package/browser/workflow/workflow.registry.mjs +171 -0
  724. package/browser/workflow/workflow.utils.mjs +39 -0
  725. package/channel/channel-notification.service.d.ts +0 -5
  726. package/channel/channel-notification.service.d.ts.map +1 -1
  727. package/channel/channel.utils.d.ts +6 -1
  728. package/channel/channel.utils.d.ts.map +1 -1
  729. package/common/decorators/front-mcp.decorator.d.ts.map +1 -1
  730. package/common/interfaces/agent.interface.d.ts +1 -1
  731. package/common/interfaces/agent.interface.d.ts.map +1 -1
  732. package/common/interfaces/tool.interface.d.ts +2 -1
  733. package/common/interfaces/tool.interface.d.ts.map +1 -1
  734. package/common/metadata/agent.metadata.d.ts +2 -2
  735. package/common/metadata/app.metadata.d.ts +2 -2
  736. package/common/metadata/channel.metadata.d.ts +2 -2
  737. package/common/metadata/front-mcp.metadata.d.ts +162 -28
  738. package/common/metadata/front-mcp.metadata.d.ts.map +1 -1
  739. package/common/metadata/plugin.metadata.d.ts +2 -2
  740. package/common/metadata/workflow.metadata.d.ts +1 -1
  741. package/common/tokens/front-mcp.tokens.d.ts.map +1 -1
  742. package/common/types/options/index.d.ts +1 -0
  743. package/common/types/options/index.d.ts.map +1 -1
  744. package/common/types/options/registry/index.d.ts +5 -0
  745. package/common/types/options/registry/index.d.ts.map +1 -0
  746. package/common/types/options/registry/interfaces.d.ts +40 -0
  747. package/common/types/options/registry/interfaces.d.ts.map +1 -0
  748. package/common/types/options/registry/schema.d.ts +30 -0
  749. package/common/types/options/registry/schema.d.ts.map +1 -0
  750. package/common/types/options/registry/typecheck.d.ts +2 -0
  751. package/common/types/options/registry/typecheck.d.ts.map +1 -0
  752. package/common/types/options/registry/utils.d.ts +5 -0
  753. package/common/types/options/registry/utils.d.ts.map +1 -0
  754. package/common/types/options/skills-http/schema.d.ts +2 -2
  755. package/elicitation/send-elicitation-result.tool.d.ts +1 -4
  756. package/elicitation/send-elicitation-result.tool.d.ts.map +1 -1
  757. package/elicitation/send-elicitation-result.utils.d.ts +5 -0
  758. package/elicitation/send-elicitation-result.utils.d.ts.map +1 -0
  759. package/esm/index.mjs +52047 -51061
  760. package/front-mcp/authorities-engine.d.ts +10 -0
  761. package/front-mcp/authorities-engine.d.ts.map +1 -0
  762. package/front-mcp/authorities-rules.check.d.ts +1 -3
  763. package/front-mcp/authorities-rules.check.d.ts.map +1 -1
  764. package/front-mcp/direct-only.flag.d.ts +6 -0
  765. package/front-mcp/direct-only.flag.d.ts.map +1 -0
  766. package/front-mcp/front-mcp.d.ts +1 -1
  767. package/front-mcp/front-mcp.d.ts.map +1 -1
  768. package/front-mcp/static-startup.check.d.ts.map +1 -1
  769. package/health/health.service.d.ts +1 -1
  770. package/health/health.service.d.ts.map +1 -1
  771. package/index.d.ts +55 -52
  772. package/index.d.ts.map +1 -1
  773. package/index.js +50925 -49933
  774. package/job/store/job-definition-store.factory.d.ts.map +1 -1
  775. package/job/store/job-state-store.factory.d.ts.map +1 -1
  776. package/job/store/redis-job-state.store.d.ts +2 -2
  777. package/job/store/redis-job-state.store.d.ts.map +1 -1
  778. package/mcp-registry/flows/index.d.ts +4 -0
  779. package/mcp-registry/flows/index.d.ts.map +1 -0
  780. package/mcp-registry/flows/server-card.flow.d.ts +93 -0
  781. package/mcp-registry/flows/server-card.flow.d.ts.map +1 -0
  782. package/mcp-registry/flows/well-known.ai-catalog.flow.d.ts +69 -0
  783. package/mcp-registry/flows/well-known.ai-catalog.flow.d.ts.map +1 -0
  784. package/mcp-registry/flows/well-known.mcp-registry-auth.flow.d.ts +48 -0
  785. package/mcp-registry/flows/well-known.mcp-registry-auth.flow.d.ts.map +1 -0
  786. package/mcp-registry/mcp-registry-scope.helper.d.ts +11 -0
  787. package/mcp-registry/mcp-registry-scope.helper.d.ts.map +1 -0
  788. package/mcp-registry/mcp-registry.utils.d.ts +7 -0
  789. package/mcp-registry/mcp-registry.utils.d.ts.map +1 -0
  790. package/package.json +10 -10
  791. package/prompt/prompt.registry.d.ts.map +1 -1
  792. package/resource/flows/read-resource.flow.d.ts.map +1 -1
  793. package/resource/resource.registry.d.ts.map +1 -1
  794. package/scope/http-scope.helper.d.ts +7 -0
  795. package/scope/http-scope.helper.d.ts.map +1 -0
  796. package/scope/observability-scope.helper.d.ts +11 -0
  797. package/scope/observability-scope.helper.d.ts.map +1 -0
  798. package/scope/scope.instance.d.ts +15 -10
  799. package/scope/scope.instance.d.ts.map +1 -1
  800. package/server/adapters/express.host.adapter.d.ts +2 -0
  801. package/server/adapters/express.host.adapter.d.ts.map +1 -1
  802. package/server/custom-routes.helper.d.ts +1 -1
  803. package/server/custom-routes.helper.d.ts.map +1 -1
  804. package/server/server.instance.d.ts.map +1 -1
  805. package/skill/flows/http/skills-api.flow.d.ts.map +1 -1
  806. package/skill/skill-scope.helper.d.ts.map +1 -1
  807. package/skill/skill.registry.d.ts +13 -4
  808. package/skill/skill.registry.d.ts.map +1 -1
  809. package/skill/skill.utils.d.ts.map +1 -1
  810. package/task/store/task-backend.utils.d.ts +11 -0
  811. package/task/store/task-backend.utils.d.ts.map +1 -0
  812. package/task/store/task-store.factory.d.ts +1 -6
  813. package/task/store/task-store.factory.d.ts.map +1 -1
  814. package/tool/flows/call-tool.flow.d.ts +1 -1
  815. package/tool/flows/call-tool.flow.d.ts.map +1 -1
  816. package/tool/flows/tools-list.flow.d.ts +3 -1
  817. package/tool/flows/tools-list.flow.d.ts.map +1 -1
  818. package/tool/tool-external.loader.d.ts.map +1 -1
  819. package/tool/ui/index.d.ts +3 -3
  820. package/tool/ui/index.d.ts.map +1 -1
  821. package/tool/ui/template-detection.d.ts +8 -0
  822. package/tool/ui/template-detection.d.ts.map +1 -0
  823. package/tool/ui/ui-render.d.ts +21 -0
  824. package/tool/ui/ui-render.d.ts.map +1 -0
  825. package/tool/ui/ui-resource.handler.d.ts.map +1 -1
  826. package/tool/ui/ui-shared.d.ts +9 -3
  827. package/tool/ui/ui-shared.d.ts.map +1 -1
  828. package/transport/adapters/transport.sse.adapter.d.ts +1 -1
  829. package/transport/adapters/transport.sse.adapter.d.ts.map +1 -1
  830. package/transport/event-stores/event-store.factory.d.ts.map +1 -1
  831. package/transport/mcp-handlers/index.d.ts +557 -557
  832. package/transport/mcp-handlers/index.d.ts.map +1 -1
  833. package/transport/web-fetch-handler.d.ts.map +1 -1
@@ -0,0 +1,1466 @@
1
+ // libs/sdk/src/auth/instances/instance.local-primary-auth.ts
2
+ import { jwtVerify, SignJWT } from "jose";
3
+ import {
4
+ createSecureStore,
5
+ createTokenStorageAdapter,
6
+ DcrClientRegistry,
7
+ deriveAuthorizationId,
8
+ InMemoryAuthorizationStore,
9
+ InMemoryConsentStore,
10
+ InMemoryFederatedAuthSessionStore,
11
+ InMemoryOrchestratedTokenStore,
12
+ isPersistentTokenStorage,
13
+ isRedisTokenStorage,
14
+ isSqliteTokenStorage,
15
+ JwksService,
16
+ SessionCredentialVault,
17
+ StorageAuthorizationStore,
18
+ StorageConsentStore,
19
+ StorageFederatedAuthSessionStore,
20
+ StorageOrchestratedTokenStore,
21
+ TokenNotAvailableError,
22
+ verifyPkce
23
+ } from "@frontmcp/auth";
24
+ import {
25
+ getEnv,
26
+ isProduction,
27
+ MemoryStorageAdapter,
28
+ randomBytes,
29
+ randomUUID,
30
+ StorageNotSupportedError
31
+ } from "@frontmcp/utils";
32
+ import {
33
+ computeIssuer,
34
+ defaultHttpPort,
35
+ FrontMcpAuth,
36
+ getPinnedPublicUrl,
37
+ ProviderScope,
38
+ resourceUriMatches
39
+ } from "../../common/index.mjs";
40
+ import {
41
+ isLocalMode,
42
+ isOrchestratedMode,
43
+ isPublicMode,
44
+ isRemoteMode
45
+ } from "../../common/types/options/auth/index.mjs";
46
+ import { installContextExtensions } from "../../context/context-extension.mjs";
47
+ import { JwtSecretRequiredError, JwtSecretWeakError } from "../../errors/index.mjs";
48
+ import { CimdService } from "../cimd/index.mjs";
49
+ import { createCredentialsProviders } from "../credentials/index.mjs";
50
+ import { credentialsContextExtension } from "../credentials/credentials.context-extension.mjs";
51
+ import OauthAuthUiExtraFlow from "../flows/oauth.auth-ui.flow.mjs";
52
+ import OauthAuthorizeFlow from "../flows/oauth.authorize.flow.mjs";
53
+ import OauthCallbackFlow from "../flows/oauth.callback.flow.mjs";
54
+ import OauthConnectFlow from "../flows/oauth.connect.flow.mjs";
55
+ import OauthProviderCallbackFlow from "../flows/oauth.provider-callback.flow.mjs";
56
+ import OauthRegisterFlow from "../flows/oauth.register.flow.mjs";
57
+ import OauthTokenFlow from "../flows/oauth.token.flow.mjs";
58
+ import OauthUserInfoFlow from "../flows/oauth.userinfo.flow.mjs";
59
+ import SessionVerifyFlow from "../flows/session.verify.flow.mjs";
60
+ import WellKnownJwksFlow from "../flows/well-known.jwks.flow.mjs";
61
+ import WellKnownAsFlow from "../flows/well-known.oauth-authorization-server.flow.mjs";
62
+ import WellKnownPrmFlow from "../flows/well-known.prm.flow.mjs";
63
+ import { createSecureStoreProviders } from "../secure-store/index.mjs";
64
+ import { secureStoreContextExtension } from "../secure-store/secure-store.context-extension.mjs";
65
+ var MIN_HS256_SECRET_BYTES = 32;
66
+ var defaultNoAuthSecret;
67
+ function getDefaultNoAuthSecret() {
68
+ if (!defaultNoAuthSecret) {
69
+ defaultNoAuthSecret = randomBytes(32);
70
+ }
71
+ return defaultNoAuthSecret;
72
+ }
73
+ var RESERVED_JWT_CLAIMS = /* @__PURE__ */ new Set([
74
+ "sub",
75
+ "iss",
76
+ "aud",
77
+ "exp",
78
+ "iat",
79
+ "nbf",
80
+ "jti",
81
+ "scope",
82
+ "email",
83
+ "name",
84
+ "picture",
85
+ "roles",
86
+ "consent",
87
+ "federated",
88
+ "authorized_apps"
89
+ ]);
90
+ function normalizeIssuer(value) {
91
+ return value.replace(/\/+$/, "");
92
+ }
93
+ function validateAuthorizationIssuer(received, expected, additional = []) {
94
+ if (received === void 0) return { ok: true };
95
+ if (!expected) return { ok: true };
96
+ const accepted = [expected, ...additional].map(normalizeIssuer);
97
+ if (!accepted.includes(normalizeIssuer(received))) {
98
+ return {
99
+ ok: false,
100
+ reason: `Authorization response issuer "${received}" does not match the configured issuer "${expected}"`
101
+ };
102
+ }
103
+ return { ok: true };
104
+ }
105
+ function audienceMatchesResource(aud, expected) {
106
+ const audiences = typeof aud === "string" ? [aud] : Array.isArray(aud) ? aud : [];
107
+ const resources = typeof expected === "string" ? [expected] : expected;
108
+ return audiences.some(
109
+ (value) => typeof value === "string" && resources.some((resource) => resourceUriMatches(value, resource))
110
+ );
111
+ }
112
+ function isUnsupportedOperation(error) {
113
+ return error instanceof StorageNotSupportedError;
114
+ }
115
+ function originOf(value) {
116
+ try {
117
+ const origin = new URL(value).origin;
118
+ return origin === "null" ? void 0 : origin;
119
+ } catch {
120
+ return void 0;
121
+ }
122
+ }
123
+ var LocalPrimaryAuth = class extends FrontMcpAuth {
124
+ constructor(scope, providers, options) {
125
+ super(options);
126
+ this.scope = scope;
127
+ this.providers = providers;
128
+ this.logger = this.providers.getActiveScope().logger.child("LocalPrimaryAuth");
129
+ this.port = this.providers.getActiveScope().metadata.http?.port ?? defaultHttpPort();
130
+ this.host = getEnv("FRONTMCP_PUBLIC_HOST")?.trim() || "localhost";
131
+ this.issuer = this.deriveIssuer(options);
132
+ this.publicHostPinned = !!getEnv("FRONTMCP_PUBLIC_HOST")?.trim();
133
+ const jwtSecret = getEnv("JWT_SECRET");
134
+ const hasJwtSecret = !!jwtSecret?.trim();
135
+ if (hasJwtSecret && jwtSecret) {
136
+ const encoded = new TextEncoder().encode(jwtSecret);
137
+ if (encoded.length < MIN_HS256_SECRET_BYTES) {
138
+ if (isProduction()) throw new JwtSecretWeakError(encoded.length);
139
+ this.logger.warn(
140
+ `JWT_SECRET is ${encoded.length} bytes; HS256 wants at least ${MIN_HS256_SECRET_BYTES} (RFC 7518). This is refused in production \u2014 generate one with \`openssl rand -hex 32\`.`
141
+ );
142
+ }
143
+ this.secret = encoded;
144
+ } else if (isProduction() && isOrchestratedMode(options)) {
145
+ throw new JwtSecretRequiredError(options.mode);
146
+ } else {
147
+ if (!isPublicMode(options)) {
148
+ this.logger.warn(
149
+ "JWT_SECRET is not set; signing with a random per-process secret. Tokens will not survive a restart and will not verify across instances. Set JWT_SECRET for any deployment that mints tokens."
150
+ );
151
+ }
152
+ this.secret = getDefaultNoAuthSecret();
153
+ }
154
+ this.tokenStorage = this.readTokenStorage(options);
155
+ this.authorizationStoreImpl = new InMemoryAuthorizationStore();
156
+ this.federatedSessionStoreImpl = new InMemoryFederatedAuthSessionStore();
157
+ this.orchestratedTokenStoreImpl = new InMemoryOrchestratedTokenStore({
158
+ encryptionKey: this.secret,
159
+ // Reuse JWT secret for token encryption
160
+ refreshSkewMs: this.providerRefreshSkewMs()
161
+ });
162
+ this.consentStoreImpl = new InMemoryConsentStore();
163
+ this.scope.onDispose(() => this.releaseResources());
164
+ this.dcrClientRegistryImpl = new DcrClientRegistry(this.getDcrConfig() ?? {});
165
+ if (isOrchestratedMode(options)) {
166
+ const cimdConfig = options.cimd;
167
+ this.cimdService = new CimdService(this.logger, cimdConfig);
168
+ }
169
+ this.ready = this.initialize();
170
+ }
171
+ scope;
172
+ providers;
173
+ host;
174
+ port;
175
+ /** The boot-time issuer: the configured one, else this server's listener address (see {@link issuerFor}). */
176
+ issuer;
177
+ /** Whether `FRONTMCP_PUBLIC_HOST` names the boot-time issuer's host, pinning it for every request. */
178
+ publicHostPinned;
179
+ keys = [];
180
+ secret;
181
+ logger;
182
+ jwks = new JwksService();
183
+ cimdService;
184
+ /**
185
+ * Token storage backend selected from `options.tokenStorage`.
186
+ * - `'memory'` / undefined → in-memory stores (default; lost on restart).
187
+ * - `{ redis }` / `{ sqlite }` → adapter-backed stores that survive restart.
188
+ *
189
+ * The three stores below are constructed in-memory synchronously in the
190
+ * constructor (preserving the exact legacy default behavior). When a
191
+ * persistent backend is configured, {@link initializeStores} swaps in the
192
+ * StorageAdapter-backed implementations during async `initialize()`, before
193
+ * the server signals ready.
194
+ */
195
+ tokenStorage;
196
+ /** OAuth authorization-code / pending / refresh-token store. */
197
+ authorizationStoreImpl;
198
+ /** Federated auth session store for multi-provider flows. */
199
+ federatedSessionStoreImpl;
200
+ /** Token store for upstream provider tokens. */
201
+ orchestratedTokenStoreImpl;
202
+ /** Remembered per-(user, client) consent selections (`rememberConsent`). */
203
+ consentStoreImpl;
204
+ /**
205
+ * Local-AS Dynamic Client Registration registry (#462). Seeded with any
206
+ * `dcr.clients` at construction so the authorize/token flows accept those
207
+ * pre-registered clients without a DCR round-trip, and mutated by
208
+ * `POST /oauth/register`. Always present (empty when no `dcr` is configured).
209
+ */
210
+ dcrClientRegistryImpl;
211
+ /** Storage adapter backing the persistent stores (kept for disposal). */
212
+ storageAdapter;
213
+ /** Closes each storage this instance opened (persistent, vault, replay guard, secure store), on scope dispose. */
214
+ storageClosers = [];
215
+ /**
216
+ * Replay guard for incremental-authorization tickets (GHSA-2c4g-9c8x-6m8g).
217
+ * Shares the persistent adapter when one is configured so the guard holds
218
+ * across a distributed deployment; falls back to a dedicated in-memory
219
+ * adapter, matching how the credential vault selects its backing store.
220
+ *
221
+ * Holds the in-flight PROMISE, not the resolved adapter: two concurrent
222
+ * claims for the same ticket must not each build their own store, or each
223
+ * would write and read back its own nonce and both would win.
224
+ */
225
+ ticketReplayStorage;
226
+ /**
227
+ * Per-session encrypted credential vault (Checkpoint 3b). Backs
228
+ * `this.credentials` in tools and persists `authenticate()` credentials.
229
+ * Constructed in {@link initialize} once the storage backend is known.
230
+ */
231
+ credentialVaultImpl;
232
+ /** Per-session encrypted credential vault (Checkpoint 3b), if enabled. */
233
+ get credentialVault() {
234
+ return this.credentialVaultImpl;
235
+ }
236
+ /**
237
+ * General session-scoped secure-secret store backend (#470). Backs
238
+ * `this.secureStore` in tools. Constructed in {@link initialize} from
239
+ * `auth.secureStore`; defaults to an in-memory, AES-256-GCM-encrypted backing.
240
+ */
241
+ secureStoreBackendImpl;
242
+ /** General secure-store backend (#470), if enabled. */
243
+ get secureStoreBackend() {
244
+ return this.secureStoreBackendImpl;
245
+ }
246
+ /** OAuth authorization-code / pending / refresh-token store. */
247
+ get authorizationStore() {
248
+ return this.authorizationStoreImpl;
249
+ }
250
+ /** Federated auth session store for multi-provider flows. */
251
+ get federatedSessionStore() {
252
+ return this.federatedSessionStoreImpl;
253
+ }
254
+ /** Token store for upstream provider tokens. */
255
+ get orchestratedTokenStore() {
256
+ return this.orchestratedTokenStoreImpl;
257
+ }
258
+ /**
259
+ * Remembered per-(user, client) consent selections, backing
260
+ * `auth.consent.rememberConsent`. Shares the configured token-storage backend
261
+ * (memory by default; Redis/SQLite when persistent storage is configured).
262
+ */
263
+ get consentStore() {
264
+ return this.consentStoreImpl;
265
+ }
266
+ /**
267
+ * Local-AS Dynamic Client Registration registry (#462). Consulted by the
268
+ * register/authorize flows to enforce the declarative `dcr` allowlists and to
269
+ * look up pre-registered + dynamically-registered clients.
270
+ */
271
+ get dcrClientRegistry() {
272
+ return this.dcrClientRegistryImpl;
273
+ }
274
+ /**
275
+ * Resolved local-AS DCR config. Only `local` mode carries `dcr`; every other
276
+ * mode returns `undefined`, preserving the historical behavior exactly.
277
+ */
278
+ getDcrConfig() {
279
+ if (isLocalMode(this.options)) {
280
+ return this.options.dcr;
281
+ }
282
+ return void 0;
283
+ }
284
+ /**
285
+ * Whether `POST /oauth/register` and the `registration_endpoint` advertisement
286
+ * are active. Honors an explicit `dcr.enabled`; when unset, falls back to the
287
+ * historical guard (enabled in development, disabled in production).
288
+ */
289
+ isDcrEnabled() {
290
+ const dcr = this.getDcrConfig();
291
+ if (dcr && typeof dcr.enabled === "boolean") {
292
+ return dcr.enabled;
293
+ }
294
+ return !isProduction();
295
+ }
296
+ /** Provider configurations (indexed by provider ID) */
297
+ providerConfigs = /* @__PURE__ */ new Map();
298
+ /** Provider token renewals in flight, by provider and refresh token (see {@link providerTokenRefresher}). */
299
+ providerRenewals = /* @__PURE__ */ new Map();
300
+ /**
301
+ * Remote-mode single upstream provider id (set by {@link registerRemoteProvider}).
302
+ *
303
+ * In `mode: 'remote'` FrontMCP federates exactly ONE mandatory upstream IdP.
304
+ * The authorize flow auto-starts federation against this id (no in-tree login
305
+ * page, no provider-selection page), and tools read its token via
306
+ * `this.orchestration.getToken(remoteProviderId)`. Undefined in every other mode.
307
+ */
308
+ remoteProviderIdImpl;
309
+ /** Remote-mode single upstream provider id, or undefined outside remote mode. */
310
+ get remoteProviderId() {
311
+ return this.remoteProviderIdImpl;
312
+ }
313
+ /** Default access token TTL (1 hour) */
314
+ accessTokenTtlSeconds = 3600;
315
+ /** Default refresh token TTL (30 days) */
316
+ refreshTokenTtlSeconds = 30 * 24 * 3600;
317
+ /**
318
+ * Derive issuer from options.
319
+ *
320
+ * `FRONTMCP_PUBLIC_HOST` overrides only the HOST portion of the boot-time
321
+ * issuer (see `this.host` in the constructor); the scheme stays `http` and
322
+ * the port stays `this.port`. To override the scheme and/or port (e.g.
323
+ * advertise `https://…` with no explicit port behind a TLS proxy), set an
324
+ * explicit `local.issuer` — that is the supported way to make the boot-time
325
+ * issuer match what discovery advertises. JWT verification accepts an issuer
326
+ * array, so tokens minted under a different scheme/port are still tolerated
327
+ * when running behind a TLS-terminating proxy, but `local.issuer` is the
328
+ * supported knob for aligning the issuer with discovery.
329
+ */
330
+ deriveIssuer(options) {
331
+ return this.configuredIssuer(options) ?? `http://${this.host}:${this.port}${this.scope.fullPath}`;
332
+ }
333
+ /**
334
+ * The issuer the options name: `issuer` in public mode, `local.issuer` in local and remote mode,
335
+ * without a trailing slash, since the callback and metadata URLs are built by appending paths to it.
336
+ */
337
+ configuredIssuer(options) {
338
+ const configured = isPublicMode(options) ? options.issuer : isOrchestratedMode(options) ? options.local?.issuer : void 0;
339
+ return configured === void 0 ? void 0 : normalizeIssuer(configured);
340
+ }
341
+ /**
342
+ * The issuer this server names in answer to `request`: in its discovery
343
+ * documents (`/.well-known/oauth-authorization-server`'s `issuer`, the
344
+ * protected resource metadata's `authorization_servers`), on its
345
+ * authorization responses (the RFC 9207 `iss`, errors included), and as the
346
+ * `iss` of the tokens it issues; the tokens it accepts there must name it
347
+ * (#269, and see {@link acceptedIssuersFor}). Every entry point asks this, so
348
+ * none of them can disagree, on the Node server and under a Web fetch
349
+ * handler alike (#629). In order:
350
+ *
351
+ * 1. a configured issuer (`issuer` / `local.issuer`);
352
+ * 2. with `FRONTMCP_PUBLIC_URL` pinned, that URL plus this scope's path;
353
+ * 3. with `FRONTMCP_PUBLIC_HOST` set, the boot-time issuer it names the host
354
+ * of (`http://<host>:<http.port><path>`);
355
+ * 4. the request's own origin plus this scope's path;
356
+ * 5. without a request, the boot-time issuer.
357
+ */
358
+ issuerFor(request) {
359
+ const configured = this.configuredIssuer(this.options);
360
+ if (configured !== void 0) return configured;
361
+ const pinned = getPinnedPublicUrl();
362
+ if (pinned !== void 0) {
363
+ return request ? computeIssuer(request, this.scope.entryPath, this.scope.routeBase) : `${pinned}${this.scope.fullPath}`;
364
+ }
365
+ if (this.publicHostPinned || !request) return this.issuer;
366
+ return computeIssuer(request, this.scope.entryPath, this.scope.routeBase);
367
+ }
368
+ /**
369
+ * The issuers a token presented with `request` may name: {@link issuerFor}
370
+ * the request. When the issuer follows the request (nothing pins it) and
371
+ * local or remote mode lists `expectedAudience`, a token for any listed
372
+ * address was issued under that address's issuer, so each listed address's
373
+ * issuer is accepted too, and so is the boot-time issuer that 1.8.4 named on
374
+ * those tokens. The token's `aud` must still name a listed resource.
375
+ */
376
+ acceptedIssuersFor(request) {
377
+ const issuer = this.issuerFor(request);
378
+ const options = this.options;
379
+ const followsRequest = !!request && this.configuredIssuer(options) === void 0 && getPinnedPublicUrl() === void 0 && !this.publicHostPinned;
380
+ if (!followsRequest || !isOrchestratedMode(options) || options.expectedAudience === void 0) return issuer;
381
+ const listed = Array.isArray(options.expectedAudience) ? options.expectedAudience : [options.expectedAudience];
382
+ const accepted = /* @__PURE__ */ new Set([issuer, this.issuer]);
383
+ for (const audience of listed) {
384
+ const origin = originOf(audience);
385
+ if (origin) accepted.add(`${origin}${this.scope.fullPath}`);
386
+ }
387
+ return [...accepted];
388
+ }
389
+ /**
390
+ * Read the `tokenStorage` selection off the auth options. Only
391
+ * local/remote/orchestrated modes declare it; public mode does not, in which
392
+ * case we treat it as the in-memory default.
393
+ */
394
+ readTokenStorage(options) {
395
+ if ("tokenStorage" in options) {
396
+ return options.tokenStorage;
397
+ }
398
+ return void 0;
399
+ }
400
+ /**
401
+ * When a persistent token-storage backend (Redis/SQLite) is configured, build
402
+ * a shared `StorageAdapter` and swap the three in-memory stores for their
403
+ * adapter-backed equivalents. For `'memory'` (or unset) this is a no-op, so
404
+ * the default behavior is preserved exactly.
405
+ *
406
+ * The orchestrated-token store keeps using the JWT secret as its encryption
407
+ * key, so upstream provider tokens stay encrypted at rest in every backend.
408
+ */
409
+ async initializeStores() {
410
+ if (!isPersistentTokenStorage(this.tokenStorage)) {
411
+ return;
412
+ }
413
+ try {
414
+ const adapter = await createTokenStorageAdapter(this.tokenStorage);
415
+ this.storageAdapter = adapter;
416
+ this.storageClosers.push(() => adapter.disconnect());
417
+ this.disposeInMemoryStores();
418
+ this.authorizationStoreImpl = new StorageAuthorizationStore(adapter);
419
+ this.federatedSessionStoreImpl = new StorageFederatedAuthSessionStore(adapter);
420
+ this.orchestratedTokenStoreImpl = new StorageOrchestratedTokenStore(adapter, {
421
+ encryptionKey: this.secret,
422
+ refreshSkewMs: this.providerRefreshSkewMs()
423
+ });
424
+ this.consentStoreImpl = new StorageConsentStore(adapter);
425
+ const backend = isSqliteTokenStorage(this.tokenStorage) ? "sqlite" : isRedisTokenStorage(this.tokenStorage) ? "redis" : "unknown";
426
+ this.logger.info(`Token storage initialized with persistent backend: ${backend}`);
427
+ } catch (err) {
428
+ this.logger.error("Failed to initialize persistent token storage", err);
429
+ throw err;
430
+ }
431
+ }
432
+ /**
433
+ * Build the per-session credential vault (Checkpoint 3b) and register the
434
+ * `this.credentials` accessor + the `/oauth/connect` add-credential flow.
435
+ *
436
+ * Skipped in pure public mode (no authenticated subject / no authenticate()
437
+ * verifier there). The vault shares the persistent StorageAdapter when one is
438
+ * configured; otherwise it uses a dedicated in-memory adapter. The HMAC pepper
439
+ * and resume-link signing key both derive from the server JWT secret
440
+ * (`this.secret`), so resume URLs are framework-signed with the same trust
441
+ * root as the access tokens.
442
+ */
443
+ /**
444
+ * The server HMAC signing key, as the string form the `signData`/`verifyData`
445
+ * helpers take. These are the exact bytes the access tokens are signed with,
446
+ * so framework-signed URLs share the access tokens' trust root.
447
+ */
448
+ get signingSecret() {
449
+ return new TextDecoder().decode(this.secret);
450
+ }
451
+ /**
452
+ * Claim an incremental-authorization ticket, exactly once.
453
+ *
454
+ * A signature check proves a ticket was minted by this server for a verified
455
+ * subject; it cannot prove the ticket has not already been used. The `auth_url`
456
+ * carrying the ticket travels through agent transcripts and server logs, so a
457
+ * leaked ticket must not stay usable for the rest of its TTL.
458
+ *
459
+ * The claim is race-free without a transaction: each attempt writes its OWN
460
+ * nonce under `ifNotExists` and reads the key back. Only the attempt whose
461
+ * nonce survives won, so concurrent replays all lose.
462
+ *
463
+ * @returns true when this caller claimed the ticket, false when it was already used.
464
+ */
465
+ async claimIncrementalTicket(jti, ttlMs) {
466
+ const key = `incremental-ticket:${jti}`;
467
+ const nonce = randomUUID();
468
+ const ttlSeconds = Math.max(1, Math.ceil(ttlMs / 1e3));
469
+ let storage = await this.getTicketReplayStorage();
470
+ try {
471
+ await storage.set(key, nonce, { ifNotExists: true, ttlSeconds });
472
+ } catch (error) {
473
+ if (!isUnsupportedOperation(error)) {
474
+ this.logger.warn(`Incremental ticket replay guard unavailable: ${String(error)}`);
475
+ return false;
476
+ }
477
+ this.logger.warn(
478
+ "Incremental ticket replay guard: the configured storage has no conditional write; falling back to an in-memory guard (single use holds within this instance only)."
479
+ );
480
+ storage = await this.useInMemoryTicketReplayStorage();
481
+ try {
482
+ await storage.set(key, nonce, { ifNotExists: true, ttlSeconds });
483
+ } catch (fallbackError) {
484
+ this.logger.warn(`Incremental ticket replay guard unavailable: ${String(fallbackError)}`);
485
+ return false;
486
+ }
487
+ }
488
+ try {
489
+ return await storage.get(key) === nonce;
490
+ } catch (error) {
491
+ this.logger.warn(`Incremental ticket replay guard unavailable: ${String(error)}`);
492
+ return false;
493
+ }
494
+ }
495
+ getTicketReplayStorage() {
496
+ if (!this.ticketReplayStorage) {
497
+ if (this.storageAdapter) {
498
+ this.ticketReplayStorage = Promise.resolve(this.storageAdapter);
499
+ } else {
500
+ this.logger.debug(
501
+ "Incremental ticket replay guard is in-memory (no persistent tokenStorage configured); single use holds within this instance only."
502
+ );
503
+ this.ticketReplayStorage = this.useInMemoryTicketReplayStorage();
504
+ }
505
+ }
506
+ return this.ticketReplayStorage;
507
+ }
508
+ /** Replace the replay guard with a fresh in-memory adapter, memoized. */
509
+ useInMemoryTicketReplayStorage() {
510
+ const pending = (async () => {
511
+ const memory = new MemoryStorageAdapter();
512
+ await memory.connect();
513
+ this.storageClosers.push(() => memory.disconnect());
514
+ return memory;
515
+ })();
516
+ this.ticketReplayStorage = pending;
517
+ return pending;
518
+ }
519
+ async initializeCredentialVault() {
520
+ if (isPublicMode(this.options)) {
521
+ return;
522
+ }
523
+ let storage;
524
+ if (this.storageAdapter) {
525
+ storage = this.storageAdapter;
526
+ } else {
527
+ const memory = new MemoryStorageAdapter();
528
+ await memory.connect();
529
+ this.storageClosers.push(() => memory.disconnect());
530
+ storage = memory;
531
+ }
532
+ const pepper = getEnv("VAULT_SECRET") ?? getEnv("JWT_SECRET") ?? void 0;
533
+ this.credentialVaultImpl = new SessionCredentialVault({
534
+ storage,
535
+ pepper,
536
+ logger: this.logger.child("SessionCredentialVault")
537
+ });
538
+ const signingSecret = this.signingSecret;
539
+ const basePath = this.issuer;
540
+ await this.providers.addDynamicProviders(
541
+ createCredentialsProviders({
542
+ vault: this.credentialVaultImpl,
543
+ signingSecret,
544
+ basePath
545
+ })
546
+ );
547
+ installContextExtensions("credentials", [credentialsContextExtension]);
548
+ this.logger.debug("SessionCredentialVault initialized; this.credentials enabled");
549
+ }
550
+ /**
551
+ * Read the `secureStore` selection off the auth options. Only
552
+ * local/remote/orchestrated modes declare it; public mode does not.
553
+ */
554
+ readSecureStoreConfig() {
555
+ if ("secureStore" in this.options) {
556
+ return this.options.secureStore;
557
+ }
558
+ return void 0;
559
+ }
560
+ /**
561
+ * Build the general session-scoped secure-secret store (#470) and register the
562
+ * `this.secureStore` accessor.
563
+ *
564
+ * Skipped in pure public mode (no authenticated subject / no session-bound
565
+ * secrets there). The backing comes from `auth.secureStore`:
566
+ * - unset / `'memory'` → in-memory, AES-256-GCM-encrypted store (default);
567
+ * - `{ sqlite }` / `{ redis }` → persistent encrypted store. When the chosen
568
+ * persistent backing matches the configured `tokenStorage`, the SAME
569
+ * StorageAdapter is reused (one connection);
570
+ * - `{ backend }` → a custom backing used as-is (e.g. an OS keychain) — the
571
+ * framework bundles NO native dependency for this path.
572
+ *
573
+ * The HKDF pepper for the built-in encrypted backings derives from the server
574
+ * JWT secret (`this.secret`) unless an explicit `encryption.pepper` is set, so
575
+ * secrets share the same trust root as the access tokens.
576
+ */
577
+ async initializeSecureStore() {
578
+ if (isPublicMode(this.options)) {
579
+ return;
580
+ }
581
+ const config = this.readSecureStoreConfig();
582
+ const reuseAdapter = this.storageAdapter && this.secureStoreSharesTokenStorage(config) ? this.storageAdapter : void 0;
583
+ const pepper = getEnv("VAULT_SECRET") ?? getEnv("JWT_SECRET") ?? new TextDecoder().decode(this.secret);
584
+ const resolved = await createSecureStore({
585
+ config,
586
+ pepper,
587
+ storage: reuseAdapter,
588
+ logger: this.logger.child("SecureStore")
589
+ });
590
+ this.secureStoreBackendImpl = resolved.backend;
591
+ if (resolved.close) this.storageClosers.push(resolved.close);
592
+ await this.providers.addDynamicProviders(
593
+ createSecureStoreProviders({
594
+ backend: resolved.backend,
595
+ scope: resolved.scope,
596
+ ttlMs: resolved.ttlMs
597
+ })
598
+ );
599
+ installContextExtensions("secureStore", [secureStoreContextExtension]);
600
+ this.logger.debug(
601
+ `SecureStore initialized (backing: ${resolved.kind}, scope: ${resolved.scope}); this.secureStore enabled`
602
+ );
603
+ }
604
+ /** Stop the in-memory stores' cleanup timers (they are replaced by persistent stores, or the scope is disposed). */
605
+ disposeInMemoryStores() {
606
+ if (this.federatedSessionStoreImpl instanceof InMemoryFederatedAuthSessionStore) {
607
+ this.federatedSessionStoreImpl.dispose();
608
+ }
609
+ if (this.orchestratedTokenStoreImpl instanceof InMemoryOrchestratedTokenStore) {
610
+ this.orchestratedTokenStoreImpl.dispose();
611
+ }
612
+ }
613
+ /** Release what this instance started: the in-memory stores' timers and the storage it opened. */
614
+ async releaseResources() {
615
+ this.disposeInMemoryStores();
616
+ await Promise.allSettled(this.storageClosers.splice(0).map((close) => close()));
617
+ }
618
+ /**
619
+ * Whether the `secureStore` config selects the SAME persistent backing as the
620
+ * configured `tokenStorage`, so they can share one StorageAdapter. Returns
621
+ * false for memory/custom/undefined and for mismatched backings (in which case
622
+ * the secure store gets its own adapter).
623
+ */
624
+ secureStoreSharesTokenStorage(config) {
625
+ if (typeof config !== "object" || config === null) return false;
626
+ if ("sqlite" in config && config.sqlite) return isSqliteTokenStorage(this.tokenStorage);
627
+ if ("redis" in config && config.redis) return isRedisTokenStorage(this.tokenStorage);
628
+ return false;
629
+ }
630
+ /**
631
+ * Sign a token for the anonymous grant (`grant_type=anonymous`).
632
+ *
633
+ * The holder is anonymous (#270): the subject is an `anon:` id, so
634
+ * `this.auth.isAnonymous` is true and authorities treat it as no signed-in
635
+ * user, and its scopes are the configured `anonymousScopes`, never a role.
636
+ *
637
+ * @param options.audience The protected resource the token is for (`aud`, #269).
638
+ * @param options.issuer The issuer to name (`iss`): {@link issuerFor} the request. Default: the boot-time issuer.
639
+ */
640
+ async signAnonymousJwt(options = {}) {
641
+ const jwt = new SignJWT({ sub: `anon:${randomUUID()}`, anonymous: true, scope: this.anonymousScopes().join(" ") }).setProtectedHeader({ alg: "HS256", typ: "JWT" }).setIssuedAt().setIssuer(options.issuer ?? this.issuer).setExpirationTime(`${this.anonymousTokenTtlSeconds()}s`).setJti(randomUUID());
642
+ if (options.audience) jwt.setAudience(options.audience);
643
+ return jwt.sign(this.secret);
644
+ }
645
+ /** How long an anonymous token lives: public mode's `sessionTtl` (default an hour), a day otherwise. */
646
+ anonymousTokenTtlSeconds() {
647
+ return isPublicMode(this.options) ? this.options.sessionTtl ?? 3600 : 86400;
648
+ }
649
+ /** The scopes an anonymous caller holds: `anonymousScopes`, default `['anonymous']`. */
650
+ anonymousScopes() {
651
+ const scopes = this.options.anonymousScopes;
652
+ return Array.isArray(scopes) ? scopes.filter((s) => typeof s === "string") : ["anonymous"];
653
+ }
654
+ /**
655
+ * Cryptographically verify a gateway-issued access token (public/local/remote
656
+ * "gateway" modes). Gateway tokens — both authenticated access tokens
657
+ * ({@link signAccessToken}) and anonymous tokens ({@link signAnonymousJwt}) —
658
+ * are HS256-signed with `this.secret`.
659
+ *
660
+ * The secret alone doesn't make a token this server's: every server started
661
+ * with the same JWT_SECRET holds it. So a token must also (#269):
662
+ * - name THIS instance as its issuer (`iss`): `expectedIssuer` (one issuer or
663
+ * several), which callers take from {@link acceptedIssuersFor} the request,
664
+ * matching what the token endpoint names when it signs ({@link issuerFor});
665
+ * the boot-time issuer when not given. Never the token's own claim; and
666
+ * - when `expectedAudience` is given, be issued for that protected resource,
667
+ * or one of those resources (`aud`, compared as RFC 8707 resource URIs).
668
+ * `session:verify` passes the request's resource URL, or the configured
669
+ * `auth.expectedAudience` when there is one.
670
+ *
671
+ * Lifetime: `exp` is required (#272) and checked with `nbf` by `jose`. The
672
+ * algorithm is pinned to HS256 to block `alg` confusion.
673
+ */
674
+ async verifyGatewayToken(token, requestBaseUrl, expectedAudience, expectedIssuer) {
675
+ try {
676
+ const { payload, protectedHeader } = await jwtVerify(token, this.secret, {
677
+ algorithms: ["HS256"],
678
+ issuer: typeof expectedIssuer === "string" ? expectedIssuer : expectedIssuer ? [...expectedIssuer] : this.issuer,
679
+ requiredClaims: ["exp"]
680
+ });
681
+ if (expectedAudience !== void 0 && !audienceMatchesResource(payload.aud, expectedAudience)) {
682
+ return { ok: false, error: "Token audience does not match this resource" };
683
+ }
684
+ return {
685
+ ok: true,
686
+ issuer: payload.iss ?? requestBaseUrl,
687
+ sub: payload.sub,
688
+ header: protectedHeader,
689
+ payload
690
+ };
691
+ } catch (err) {
692
+ const message = err instanceof Error ? err.message : "verification_failed";
693
+ return { ok: false, error: message };
694
+ }
695
+ }
696
+ /**
697
+ * Sign an access token for an authenticated user
698
+ */
699
+ async signAccessToken(user, scopes, audience, consentMetadata, issuer) {
700
+ const claims = {
701
+ sub: user.sub,
702
+ scope: scopes.join(" ")
703
+ };
704
+ if (user.email) claims["email"] = user.email;
705
+ if (user.name) claims["name"] = user.name;
706
+ if (user.picture) claims["picture"] = user.picture;
707
+ if (user.roles) claims["roles"] = user.roles;
708
+ if (consentMetadata) {
709
+ if (consentMetadata.consentEnabled) {
710
+ claims["consent"] = {
711
+ enabled: true,
712
+ selectedTools: consentMetadata.selectedToolIds ?? []
713
+ };
714
+ }
715
+ if (consentMetadata.federatedLoginUsed) {
716
+ claims["federated"] = {
717
+ enabled: true,
718
+ selectedProviders: consentMetadata.selectedProviderIds ?? [],
719
+ skippedProviders: consentMetadata.skippedProviderIds ?? []
720
+ };
721
+ }
722
+ if (consentMetadata.authorizedAppIds) {
723
+ claims["authorized_apps"] = consentMetadata.authorizedAppIds;
724
+ }
725
+ if (consentMetadata.customClaims) {
726
+ for (const [key, value] of Object.entries(consentMetadata.customClaims)) {
727
+ if (RESERVED_JWT_CLAIMS.has(key)) {
728
+ this.logger.warn(`Dropping reserved claim "${key}" from authenticate() custom claims`);
729
+ continue;
730
+ }
731
+ claims[key] = value;
732
+ }
733
+ }
734
+ }
735
+ const jwt = new SignJWT(claims).setProtectedHeader({ alg: "HS256", typ: "JWT" }).setIssuedAt().setIssuer(issuer ?? this.issuer).setExpirationTime(`${this.accessTokenTtlSeconds}s`).setJti(randomUUID());
736
+ if (audience) {
737
+ jwt.setAudience(audience);
738
+ }
739
+ return jwt.sign(this.secret);
740
+ }
741
+ /**
742
+ * Exchange an authorization code for tokens
743
+ */
744
+ async exchangeCode(code, clientId, redirectUri, codeVerifier, clientSecret, defaultAudience, issuer) {
745
+ if (this.dcrClientRegistryImpl.verifyClientSecret(clientId, clientSecret) === "invalid") {
746
+ this.logger.warn("Client authentication failed at token endpoint (authorization_code)");
747
+ return { error: "invalid_client", error_description: "Client authentication failed" };
748
+ }
749
+ const codeRecord = await this.authorizationStore.getAuthorizationCode(code);
750
+ if (!codeRecord) {
751
+ this.logger.warn(`Authorization code not found or expired: ${code.substring(0, 8)}...`);
752
+ return {
753
+ error: "invalid_grant",
754
+ error_description: "Authorization code is invalid or expired"
755
+ };
756
+ }
757
+ if (codeRecord.used) {
758
+ this.logger.warn(`Authorization code already used: ${code.substring(0, 8)}...`);
759
+ if (codeRecord.issuedRefreshToken) {
760
+ try {
761
+ await this.authorizationStore.revokeRefreshToken(codeRecord.issuedRefreshToken);
762
+ } catch (err) {
763
+ this.logger.warn(`Failed to revoke refresh token on authorization-code replay: ${err}`);
764
+ }
765
+ }
766
+ await this.authorizationStore.deleteAuthorizationCode(code);
767
+ return {
768
+ error: "invalid_grant",
769
+ error_description: "Authorization code has already been used"
770
+ };
771
+ }
772
+ if (codeRecord.clientId !== clientId) {
773
+ this.logger.warn(`Client ID mismatch: expected ${codeRecord.clientId}, got ${clientId}`);
774
+ return {
775
+ error: "invalid_grant",
776
+ error_description: "Client ID does not match"
777
+ };
778
+ }
779
+ if (codeRecord.redirectUri !== redirectUri) {
780
+ this.logger.warn(`Redirect URI mismatch`);
781
+ return {
782
+ error: "invalid_grant",
783
+ error_description: "Redirect URI does not match"
784
+ };
785
+ }
786
+ if (!verifyPkce(codeVerifier, codeRecord.pkce)) {
787
+ this.logger.warn(`PKCE verification failed`);
788
+ return {
789
+ error: "invalid_grant",
790
+ error_description: "PKCE verification failed"
791
+ };
792
+ }
793
+ await this.authorizationStore.markCodeUsed(code);
794
+ const user = {
795
+ sub: codeRecord.userSub,
796
+ email: codeRecord.userEmail,
797
+ name: codeRecord.userName
798
+ };
799
+ const hasCustomClaims = !!codeRecord.customClaims && Object.keys(codeRecord.customClaims).length > 0;
800
+ const hasAuthorizedApps = Array.isArray(codeRecord.authorizedAppIds);
801
+ const consentMetadata = codeRecord.consentEnabled || codeRecord.federatedLoginUsed || hasCustomClaims || hasAuthorizedApps ? {
802
+ selectedToolIds: codeRecord.selectedToolIds,
803
+ selectedProviderIds: codeRecord.selectedProviderIds,
804
+ skippedProviderIds: codeRecord.skippedProviderIds,
805
+ consentEnabled: codeRecord.consentEnabled,
806
+ federatedLoginUsed: codeRecord.federatedLoginUsed,
807
+ authorizedAppIds: codeRecord.authorizedAppIds,
808
+ customClaims: codeRecord.customClaims
809
+ } : void 0;
810
+ const resource = codeRecord.resource ?? defaultAudience;
811
+ const accessToken = await this.signAccessToken(user, codeRecord.scopes, resource, consentMetadata, issuer);
812
+ let providerTokensId;
813
+ if (codeRecord.pendingAuthId && codeRecord.federatedLoginUsed) {
814
+ providerTokensId = await this.moveProviderTokens(`pending:${codeRecord.pendingAuthId}`, accessToken);
815
+ }
816
+ const refreshTokenRecord = this.authorizationStore.createRefreshTokenRecord({
817
+ clientId,
818
+ userSub: user.sub,
819
+ scopes: codeRecord.scopes,
820
+ resource,
821
+ userEmail: user.email,
822
+ userName: user.name,
823
+ consentEnabled: codeRecord.consentEnabled,
824
+ selectedToolIds: codeRecord.selectedToolIds,
825
+ authorizedAppIds: codeRecord.authorizedAppIds,
826
+ customClaims: codeRecord.customClaims,
827
+ federatedLoginUsed: codeRecord.federatedLoginUsed,
828
+ selectedProviderIds: codeRecord.selectedProviderIds,
829
+ skippedProviderIds: codeRecord.skippedProviderIds,
830
+ providerTokensId
831
+ });
832
+ await this.authorizationStore.storeRefreshToken(refreshTokenRecord);
833
+ await this.authorizationStore.markCodeUsed(code, refreshTokenRecord.token);
834
+ this.logger.info(`Tokens issued for user: ${user.sub}`);
835
+ return {
836
+ access_token: accessToken,
837
+ token_type: "Bearer",
838
+ expires_in: this.accessTokenTtlSeconds,
839
+ refresh_token: refreshTokenRecord.token,
840
+ scope: codeRecord.scopes.join(" ")
841
+ };
842
+ }
843
+ /**
844
+ * Move the upstream provider tokens stored under `fromAuthorizationId` to the authorization id of
845
+ * `accessToken`, where `this.orchestration` looks for them. Returns where they are now: that id, or
846
+ * `fromAuthorizationId` when the move failed, so the next refresh tries again (the token is still
847
+ * issued; its tools find no provider token until then).
848
+ */
849
+ async moveProviderTokens(fromAuthorizationId, accessToken) {
850
+ const toAuthorizationId = deriveAuthorizationId(accessToken);
851
+ try {
852
+ await this.orchestratedTokenStore.migrateTokens(fromAuthorizationId, toAuthorizationId);
853
+ this.logger.info(`Migrated tokens from ${fromAuthorizationId} to ${toAuthorizationId}`);
854
+ return toAuthorizationId;
855
+ } catch (err) {
856
+ this.logger.warn(`Failed to migrate tokens: ${err}`);
857
+ return fromAuthorizationId;
858
+ }
859
+ }
860
+ /**
861
+ * Copy the upstream provider tokens stored under `fromAuthorizationId` to the authorization id of
862
+ * `accessToken`. Returns that id, or undefined when the store cannot copy (the refresh then moves them)
863
+ * or the copy failed (the token is issued without them, and the next refresh copies them again).
864
+ */
865
+ async copyProviderTokens(fromAuthorizationId, accessToken) {
866
+ const store = this.orchestratedTokenStore;
867
+ if (!store.copyTokens) return void 0;
868
+ const toAuthorizationId = deriveAuthorizationId(accessToken);
869
+ try {
870
+ await store.copyTokens(fromAuthorizationId, toAuthorizationId);
871
+ return toAuthorizationId;
872
+ } catch (err) {
873
+ this.logger.warn(`Failed to copy provider tokens: ${err}`);
874
+ await this.discardProviderTokens(toAuthorizationId);
875
+ return void 0;
876
+ }
877
+ }
878
+ /** Remove the upstream provider tokens stored under `authorizationId`; a failure leaves them to expire. */
879
+ async discardProviderTokens(authorizationId) {
880
+ const store = this.orchestratedTokenStore;
881
+ try {
882
+ const providerIds = await store.getProviderIds(authorizationId);
883
+ await Promise.all(providerIds.map((providerId) => store.deleteTokens(authorizationId, providerId)));
884
+ } catch (err) {
885
+ this.logger.warn(`Failed to discard provider tokens: ${err}`);
886
+ }
887
+ }
888
+ /**
889
+ * Refresh an access token using a refresh token
890
+ */
891
+ async refreshAccessToken(refreshToken, clientId, clientSecret, defaultAudience, issuer) {
892
+ if (this.dcrClientRegistryImpl.verifyClientSecret(clientId, clientSecret) === "invalid") {
893
+ this.logger.warn("Client authentication failed at token endpoint (refresh_token)");
894
+ return { error: "invalid_client", error_description: "Client authentication failed" };
895
+ }
896
+ const tokenRecord = await this.authorizationStore.getRefreshToken(refreshToken);
897
+ if (!tokenRecord) {
898
+ this.logger.warn("Refresh token not found or expired");
899
+ return {
900
+ error: "invalid_grant",
901
+ error_description: "Refresh token is invalid or expired"
902
+ };
903
+ }
904
+ if (tokenRecord.clientId !== clientId) {
905
+ this.logger.warn("Client ID mismatch on refresh");
906
+ return {
907
+ error: "invalid_grant",
908
+ error_description: "Client ID does not match"
909
+ };
910
+ }
911
+ const user = {
912
+ sub: tokenRecord.userSub,
913
+ email: tokenRecord.userEmail,
914
+ name: tokenRecord.userName
915
+ };
916
+ const hasAuthorizedApps = Array.isArray(tokenRecord.authorizedAppIds);
917
+ const hasCustomClaims = !!tokenRecord.customClaims && Object.keys(tokenRecord.customClaims).length > 0;
918
+ const consentMetadata = tokenRecord.consentEnabled || tokenRecord.federatedLoginUsed || hasCustomClaims || hasAuthorizedApps ? {
919
+ selectedToolIds: tokenRecord.selectedToolIds,
920
+ selectedProviderIds: tokenRecord.selectedProviderIds,
921
+ skippedProviderIds: tokenRecord.skippedProviderIds,
922
+ consentEnabled: tokenRecord.consentEnabled,
923
+ federatedLoginUsed: tokenRecord.federatedLoginUsed,
924
+ authorizedAppIds: tokenRecord.authorizedAppIds,
925
+ customClaims: tokenRecord.customClaims
926
+ } : void 0;
927
+ const resource = tokenRecord.resource ?? defaultAudience;
928
+ const accessToken = await this.signAccessToken(user, tokenRecord.scopes, resource, consentMetadata, issuer);
929
+ const sourceId = tokenRecord.providerTokensId;
930
+ const copiedTo = sourceId ? await this.copyProviderTokens(sourceId, accessToken) : void 0;
931
+ if (sourceId && !await this.authorizationStore.getRefreshToken(refreshToken)) {
932
+ if (copiedTo) await this.discardProviderTokens(copiedTo);
933
+ this.logger.warn("Refresh token was redeemed by a concurrent request");
934
+ return { error: "invalid_grant", error_description: "Refresh token is invalid or expired" };
935
+ }
936
+ const newRefreshRecord = this.authorizationStore.createRefreshTokenRecord({
937
+ clientId,
938
+ userSub: tokenRecord.userSub,
939
+ scopes: tokenRecord.scopes,
940
+ resource,
941
+ userEmail: tokenRecord.userEmail,
942
+ userName: tokenRecord.userName,
943
+ consentEnabled: tokenRecord.consentEnabled,
944
+ selectedToolIds: tokenRecord.selectedToolIds,
945
+ authorizedAppIds: tokenRecord.authorizedAppIds,
946
+ customClaims: tokenRecord.customClaims,
947
+ federatedLoginUsed: tokenRecord.federatedLoginUsed,
948
+ selectedProviderIds: tokenRecord.selectedProviderIds,
949
+ skippedProviderIds: tokenRecord.skippedProviderIds,
950
+ providerTokensId: copiedTo ?? sourceId
951
+ });
952
+ try {
953
+ await this.authorizationStore.rotateRefreshToken(refreshToken, newRefreshRecord);
954
+ } catch (err) {
955
+ if (copiedTo) await this.discardProviderTokens(copiedTo);
956
+ throw err;
957
+ }
958
+ if (sourceId && copiedTo) await this.discardProviderTokens(sourceId);
959
+ if (sourceId && !this.orchestratedTokenStore.copyTokens) {
960
+ const movedTo = await this.moveProviderTokens(sourceId, accessToken);
961
+ if (movedTo !== sourceId) {
962
+ await this.authorizationStore.storeRefreshToken({ ...newRefreshRecord, providerTokensId: movedTo });
963
+ }
964
+ }
965
+ this.logger.info(`Tokens refreshed for user: ${user.sub}`);
966
+ return {
967
+ access_token: accessToken,
968
+ token_type: "Bearer",
969
+ expires_in: this.accessTokenTtlSeconds,
970
+ refresh_token: newRefreshRecord.token,
971
+ scope: tokenRecord.scopes.join(" ")
972
+ };
973
+ }
974
+ /**
975
+ * Create an authorization code for a user (called after login)
976
+ */
977
+ async createAuthorizationCode(params) {
978
+ const codeRecord = this.authorizationStore.createCodeRecord({
979
+ clientId: params.clientId,
980
+ redirectUri: params.redirectUri,
981
+ scopes: params.scopes,
982
+ pkce: { challenge: params.codeChallenge, method: "S256" },
983
+ userSub: params.userSub,
984
+ userEmail: params.userEmail,
985
+ userName: params.userName,
986
+ state: params.state,
987
+ resource: params.resource,
988
+ // Consent and Federated Login Data
989
+ selectedToolIds: params.selectedToolIds,
990
+ selectedProviderIds: params.selectedProviderIds,
991
+ skippedProviderIds: params.skippedProviderIds,
992
+ consentEnabled: params.consentEnabled,
993
+ federatedLoginUsed: params.federatedLoginUsed,
994
+ // Token migration ID (for federated auth)
995
+ pendingAuthId: params.pendingAuthId,
996
+ // Progressive/Incremental authorization: granted app-id set.
997
+ authorizedAppIds: params.authorizedAppIds,
998
+ // Custom claims from a local authenticate() verifier (Checkpoint 3a)
999
+ customClaims: params.customClaims
1000
+ });
1001
+ await this.authorizationStore.storeAuthorizationCode(codeRecord);
1002
+ this.logger.info(`Authorization code created for user: ${params.userSub}`);
1003
+ return codeRecord.code;
1004
+ }
1005
+ async initialize() {
1006
+ await this.initializeStores();
1007
+ this.registerConfiguredProviders();
1008
+ this.registerRemoteProvider();
1009
+ await this.initializeCredentialVault();
1010
+ await this.initializeSecureStore();
1011
+ this.providers.injectProvider({
1012
+ value: this.jwks,
1013
+ metadata: {
1014
+ scope: ProviderScope.GLOBAL,
1015
+ name: "auth:jwk-service"
1016
+ },
1017
+ provide: JwksService
1018
+ });
1019
+ if (this.cimdService) {
1020
+ const cimdService = this.cimdService;
1021
+ if (cimdService.enabled) await cimdService.initialize();
1022
+ this.scope.onDispose(() => cimdService.dispose());
1023
+ this.providers.injectProvider({
1024
+ value: cimdService,
1025
+ metadata: {
1026
+ scope: ProviderScope.GLOBAL,
1027
+ name: "auth:cimd-service"
1028
+ },
1029
+ provide: CimdService
1030
+ });
1031
+ this.logger.debug("CIMD service registered");
1032
+ }
1033
+ await this.registerAuthFlows();
1034
+ return Promise.resolve();
1035
+ }
1036
+ fetch(input, init) {
1037
+ return fetch(input, init);
1038
+ }
1039
+ validate(request) {
1040
+ return Promise.resolve();
1041
+ }
1042
+ async registerAuthFlows() {
1043
+ const scope = this.providers.getActiveScope();
1044
+ await scope.registryFlows(
1045
+ WellKnownPrmFlow,
1046
+ WellKnownAsFlow,
1047
+ WellKnownJwksFlow,
1048
+ SessionVerifyFlow,
1049
+ OauthAuthorizeFlow,
1050
+ OauthTokenFlow,
1051
+ OauthUserInfoFlow,
1052
+ OauthCallbackFlow,
1053
+ OauthConnectFlow,
1054
+ OauthRegisterFlow,
1055
+ OauthProviderCallbackFlow,
1056
+ OauthAuthUiExtraFlow
1057
+ );
1058
+ }
1059
+ // ============================================
1060
+ // Upstream Provider OAuth Methods
1061
+ // ============================================
1062
+ /**
1063
+ * Register an upstream OAuth provider configuration
1064
+ */
1065
+ registerProvider(config) {
1066
+ const previous = this.providerConfigs.get(config.id);
1067
+ const issuerChanged = previous?.issuer !== void 0 && config.issuer !== void 0 && normalizeIssuer(previous.issuer) !== normalizeIssuer(config.issuer);
1068
+ if (issuerChanged) {
1069
+ this.logger.warn(
1070
+ `Upstream provider "${config.id}" changed issuer (${previous.issuer} \u2192 ${config.issuer}); discarding credentials bound to the previous authorization server`
1071
+ );
1072
+ void this.discardProviderCredentials(config.id);
1073
+ }
1074
+ this.providerConfigs.set(config.id, config);
1075
+ this.logger.info(`Registered upstream provider: ${config.id}`);
1076
+ }
1077
+ /**
1078
+ * Drop every stored credential for a provider whose authorization server changed.
1079
+ *
1080
+ * Best-effort: the token store may be memory-backed and already empty. Failing
1081
+ * here must not block re-registration, but the credentials MUST NOT survive,
1082
+ * so a failure is logged loudly rather than swallowed.
1083
+ */
1084
+ async discardProviderCredentials(providerId) {
1085
+ try {
1086
+ const store = this.orchestratedTokenStoreImpl;
1087
+ if (typeof store.deleteTokensForProvider !== "function") {
1088
+ this.logger.warn(
1089
+ `Cannot auto-discard credentials for provider "${providerId}": the configured token store does not support provider-wide deletion. Rotate or clear the store manually so credentials issued by the previous authorization server are not reused.`
1090
+ );
1091
+ return;
1092
+ }
1093
+ await store.deleteTokensForProvider(providerId);
1094
+ } catch (error) {
1095
+ this.logger.error(
1096
+ `Failed to discard credentials for provider "${providerId}" after an issuer change`,
1097
+ error instanceof Error ? { message: error.message } : { error }
1098
+ );
1099
+ }
1100
+ }
1101
+ /**
1102
+ * Bridge declarative `auth.providers` (local-mode multi-provider orchestration)
1103
+ * into the upstream-provider registry. Runs once during `initialize()`.
1104
+ *
1105
+ * For each declared provider we map the ergonomic `authorizeUrl`/`tokenUrl`
1106
+ * aliases onto the canonical `authorizationEndpoint`/`tokenEndpoint`, default
1107
+ * `name`/`scopes`, and compute the per-provider callback URL from the issuer
1108
+ * (`${issuer}/oauth/provider/${id}/callback`). No-op when not local mode or
1109
+ * when no providers are declared, so existing configs are unaffected.
1110
+ *
1111
+ * Security: only non-PII provider metadata is read here; client secrets are
1112
+ * kept in the provider config and never logged or exposed to the LLM.
1113
+ */
1114
+ registerConfiguredProviders() {
1115
+ if (!isLocalMode(this.options)) {
1116
+ return;
1117
+ }
1118
+ const providers = this.options.providers;
1119
+ if (!providers || providers.length === 0) {
1120
+ return;
1121
+ }
1122
+ for (const p of providers) {
1123
+ const authorizationEndpoint = p.authorizationEndpoint ?? p.authorizeUrl;
1124
+ const tokenEndpoint = p.tokenEndpoint ?? p.tokenUrl;
1125
+ if (!authorizationEndpoint || !tokenEndpoint) {
1126
+ const missing = !authorizationEndpoint ? !tokenEndpoint ? "authorization and token endpoints" : "authorization endpoint (authorizationEndpoint/authorizeUrl)" : "token endpoint (tokenEndpoint/tokenUrl)";
1127
+ throw new Error(`Provider "${p.id}" is missing its ${missing}.`);
1128
+ }
1129
+ this.registerProvider({
1130
+ id: p.id,
1131
+ name: p.name ?? p.id,
1132
+ authorizationEndpoint,
1133
+ tokenEndpoint,
1134
+ userInfoEndpoint: p.userInfoEndpoint,
1135
+ jwksUri: p.jwksUri,
1136
+ clientId: p.clientId,
1137
+ clientSecret: p.clientSecret,
1138
+ scopes: p.scopes ?? [],
1139
+ callbackUrl: `${this.issuer}/oauth/provider/${p.id}/callback`,
1140
+ issuer: p.issuer,
1141
+ additionalIssuers: p.additionalIssuers
1142
+ });
1143
+ }
1144
+ }
1145
+ /**
1146
+ * Remote mode (`mode: 'remote'`): register the flat remote config as the
1147
+ * SINGLE mandatory upstream provider. Runs once during `initialize()`.
1148
+ *
1149
+ * The flat fields (`provider` base URL + `clientId`/`clientSecret`/`scopes`)
1150
+ * and the `providerConfig` endpoint overrides (`authEndpoint`/`tokenEndpoint`/
1151
+ * `userInfoEndpoint`/`jwksUri`) are mapped onto an {@link UpstreamProviderConfig}.
1152
+ * Endpoints not explicitly overridden are derived from the `provider` base URL
1153
+ * using the standard OIDC paths (`/authorize`, `/token`, `/userinfo`,
1154
+ * `/.well-known/jwks.json`) — the same convention `transparent` mode uses for
1155
+ * discovery. The provider id comes from `providerConfig.id` when set, else it
1156
+ * is derived from the provider hostname (mirroring `deriveProviderId`).
1157
+ *
1158
+ * No-op outside remote mode, so local/public/transparent are unaffected.
1159
+ *
1160
+ * Security: only non-PII provider metadata is read here; the client secret is
1161
+ * kept in the provider config and never logged or exposed to the LLM.
1162
+ */
1163
+ registerRemoteProvider() {
1164
+ if (!isRemoteMode(this.options)) {
1165
+ return;
1166
+ }
1167
+ const options = this.options;
1168
+ const base = options.provider.replace(/\/+$/, "");
1169
+ const cfg = options.providerConfig;
1170
+ const id = cfg?.id ?? this.deriveRemoteProviderId(options.provider);
1171
+ this.remoteProviderIdImpl = id;
1172
+ if (!options.clientId) {
1173
+ this.logger.warn(
1174
+ `Remote mode: no clientId configured for provider "${id}"; upstream OAuth is not available (DCR is not yet wired)`
1175
+ );
1176
+ return;
1177
+ }
1178
+ this.registerProvider({
1179
+ id,
1180
+ name: cfg?.name ?? id,
1181
+ authorizationEndpoint: cfg?.authEndpoint ?? `${base}/authorize`,
1182
+ tokenEndpoint: cfg?.tokenEndpoint ?? `${base}/token`,
1183
+ userInfoEndpoint: cfg?.userInfoEndpoint ?? `${base}/userinfo`,
1184
+ jwksUri: cfg?.jwksUri ?? `${base}/.well-known/jwks.json`,
1185
+ jwks: cfg?.jwks,
1186
+ clientId: options.clientId,
1187
+ clientSecret: options.clientSecret,
1188
+ scopes: options.scopes ?? ["openid"],
1189
+ callbackUrl: `${this.issuer}/oauth/provider/${id}/callback`,
1190
+ // The provider is the issuer, as in transparent mode (#271): an RFC 9207
1191
+ // `iss` on its callback and its id_token's `iss` must name it.
1192
+ issuer: options.provider,
1193
+ additionalIssuers: cfg?.additionalIssuers,
1194
+ verifyIssuer: cfg?.verifyIssuer
1195
+ });
1196
+ }
1197
+ /**
1198
+ * Derive a stable provider id from the upstream `provider` base URL, mirroring
1199
+ * the detection layer's `deriveProviderId`/`urlToProviderId` (hostname with
1200
+ * dots replaced by underscores) so the id is consistent across surfaces.
1201
+ */
1202
+ deriveRemoteProviderId(provider) {
1203
+ try {
1204
+ return new URL(provider).hostname.replace(/\./g, "_");
1205
+ } catch {
1206
+ return provider.replace(/[^a-zA-Z0-9]/g, "_");
1207
+ }
1208
+ }
1209
+ /**
1210
+ * Get provider configuration
1211
+ */
1212
+ getProviderConfig(providerId) {
1213
+ return this.providerConfigs.get(providerId);
1214
+ }
1215
+ /**
1216
+ * Build OAuth authorize URL for an upstream provider
1217
+ */
1218
+ async buildProviderAuthorizeUrl(providerId, params) {
1219
+ const config = this.providerConfigs.get(providerId);
1220
+ if (!config) {
1221
+ this.logger.error(`Provider not found: ${providerId}`);
1222
+ return null;
1223
+ }
1224
+ const url = new URL(config.authorizationEndpoint);
1225
+ url.searchParams.set("response_type", "code");
1226
+ url.searchParams.set("client_id", config.clientId);
1227
+ url.searchParams.set("redirect_uri", config.callbackUrl);
1228
+ url.searchParams.set("state", params.state);
1229
+ url.searchParams.set("code_challenge", params.codeChallenge);
1230
+ url.searchParams.set("code_challenge_method", params.codeChallengeMethod);
1231
+ const scopes = params.scopes ?? config.scopes;
1232
+ if (scopes.length > 0) {
1233
+ url.searchParams.set("scope", scopes.join(" "));
1234
+ }
1235
+ return url.toString();
1236
+ }
1237
+ /**
1238
+ * Exchange authorization code with upstream provider for tokens
1239
+ */
1240
+ async exchangeProviderCode(providerId, code, codeVerifier) {
1241
+ const config = this.providerConfigs.get(providerId);
1242
+ if (!config) {
1243
+ return {
1244
+ error: "invalid_provider",
1245
+ error_description: `Provider not configured: ${providerId}`
1246
+ };
1247
+ }
1248
+ try {
1249
+ const body = new URLSearchParams({
1250
+ grant_type: "authorization_code",
1251
+ code,
1252
+ redirect_uri: config.callbackUrl,
1253
+ client_id: config.clientId
1254
+ });
1255
+ if (config.clientSecret) {
1256
+ body.set("client_secret", config.clientSecret);
1257
+ }
1258
+ if (codeVerifier) {
1259
+ body.set("code_verifier", codeVerifier);
1260
+ }
1261
+ this.logger.debug(`Exchanging code with provider: ${providerId}`);
1262
+ const response = await fetch(config.tokenEndpoint, {
1263
+ method: "POST",
1264
+ headers: {
1265
+ "Content-Type": "application/x-www-form-urlencoded",
1266
+ Accept: "application/json"
1267
+ },
1268
+ body: body.toString()
1269
+ });
1270
+ if (!response.ok) {
1271
+ const errorData = await response.json().catch(() => ({}));
1272
+ this.logger.error(`Provider token exchange failed: ${response.status}`, errorData);
1273
+ return {
1274
+ error: errorData.error || "provider_error",
1275
+ error_description: errorData.error_description || `Provider returned ${response.status}`
1276
+ };
1277
+ }
1278
+ const tokenData = await response.json();
1279
+ if (typeof tokenData?.access_token !== "string" || tokenData.access_token.length === 0) {
1280
+ this.logger.error(`Provider ${providerId} returned 200 without an access_token`);
1281
+ return {
1282
+ error: "provider_error",
1283
+ error_description: `Provider ${providerId} did not return an access_token`
1284
+ };
1285
+ }
1286
+ this.logger.info(`Successfully exchanged code with provider: ${providerId}`);
1287
+ return tokenData;
1288
+ } catch (err) {
1289
+ this.logger.error(`Provider token exchange error for ${providerId}:`, err);
1290
+ return {
1291
+ error: "provider_error",
1292
+ error_description: `Failed to exchange code with provider: ${err}`
1293
+ };
1294
+ }
1295
+ }
1296
+ /**
1297
+ * Get user info from upstream provider
1298
+ */
1299
+ async getProviderUserInfo(providerId, accessToken, idToken) {
1300
+ const config = this.providerConfigs.get(providerId);
1301
+ if (idToken && config) {
1302
+ const claims = await this.verifyProviderIdToken(config, idToken);
1303
+ const sub = typeof claims?.["sub"] === "string" && claims["sub"].trim() ? claims["sub"] : void 0;
1304
+ if (claims && sub) {
1305
+ return {
1306
+ sub,
1307
+ email: claims["email"],
1308
+ name: claims["name"],
1309
+ picture: claims["picture"],
1310
+ claims
1311
+ };
1312
+ }
1313
+ this.logger.warn(`ID token for ${providerId} was not verified; using the userinfo endpoint for identity`);
1314
+ }
1315
+ if (config?.userInfoEndpoint) {
1316
+ try {
1317
+ const response = await fetch(config.userInfoEndpoint, {
1318
+ headers: {
1319
+ Authorization: `Bearer ${accessToken}`,
1320
+ Accept: "application/json"
1321
+ }
1322
+ });
1323
+ if (response.ok) {
1324
+ const userInfo = await response.json();
1325
+ const sub = typeof userInfo["sub"] === "string" && userInfo["sub"].trim() ? userInfo["sub"] : void 0;
1326
+ if (sub) {
1327
+ return {
1328
+ sub,
1329
+ email: userInfo["email"],
1330
+ name: userInfo["name"],
1331
+ picture: userInfo["picture"],
1332
+ claims: userInfo
1333
+ };
1334
+ }
1335
+ this.logger.warn(`userinfo for ${providerId} returned no usable sub`);
1336
+ }
1337
+ } catch (err) {
1338
+ this.logger.warn(`Failed to get userinfo from ${providerId}: ${err}`);
1339
+ }
1340
+ }
1341
+ throw new Error(
1342
+ `Unable to determine a stable user identity from provider "${providerId}" (no id_token sub and no usable userinfo endpoint)`
1343
+ );
1344
+ }
1345
+ /**
1346
+ * Verify an upstream provider's `id_token` and return its claims, or
1347
+ * `undefined` when it doesn't verify or no keys are configured to verify it.
1348
+ *
1349
+ * Checks the signature against the provider's published keys (inline
1350
+ * `jwks`, else `jwksUri`, else the provider's discovery document), the
1351
+ * issuer (the provider, plus `additionalIssuers`, unless `verifyIssuer` is
1352
+ * false), `exp`, and that `aud` names this client. With no issuer configured
1353
+ * (a local-mode provider without `issuer`) the token is not used: a key set
1354
+ * an IdP shares between tenants would vouch for every tenant's tokens.
1355
+ */
1356
+ async verifyProviderIdToken(config, idToken) {
1357
+ if (!config.jwks?.keys?.length && !config.jwksUri) return void 0;
1358
+ if (!config.issuer && config.verifyIssuer !== false) {
1359
+ this.logger.warn(`ID token for ${config.id} not used: the provider has no configured issuer to check it against`);
1360
+ return void 0;
1361
+ }
1362
+ const result = await this.jwks.verifyTransparentToken(idToken, [
1363
+ {
1364
+ id: `upstream:${config.id}`,
1365
+ issuerUrl: config.issuer ?? "",
1366
+ additionalIssuers: config.additionalIssuers,
1367
+ verifyIssuer: config.verifyIssuer,
1368
+ jwks: config.jwks,
1369
+ jwksUri: config.jwksUri
1370
+ }
1371
+ ]);
1372
+ if (!result.ok || !result.payload) {
1373
+ this.logger.warn(`ID token for ${config.id} failed verification: ${result.error ?? "unknown"}`);
1374
+ return void 0;
1375
+ }
1376
+ const aud = result.payload["aud"];
1377
+ const audiences = typeof aud === "string" ? [aud] : Array.isArray(aud) ? aud : [];
1378
+ if (!audiences.includes(config.clientId)) {
1379
+ this.logger.warn(`ID token for ${config.id} was issued for another client`);
1380
+ return void 0;
1381
+ }
1382
+ return result.payload;
1383
+ }
1384
+ /**
1385
+ * Refresh tokens from upstream provider
1386
+ */
1387
+ async refreshProviderToken(providerId, refreshToken) {
1388
+ const config = this.providerConfigs.get(providerId);
1389
+ if (!config) {
1390
+ return {
1391
+ error: "invalid_provider",
1392
+ error_description: `Provider not configured: ${providerId}`
1393
+ };
1394
+ }
1395
+ try {
1396
+ const body = new URLSearchParams({
1397
+ grant_type: "refresh_token",
1398
+ refresh_token: refreshToken,
1399
+ client_id: config.clientId
1400
+ });
1401
+ if (config.clientSecret) {
1402
+ body.set("client_secret", config.clientSecret);
1403
+ }
1404
+ const response = await fetch(config.tokenEndpoint, {
1405
+ method: "POST",
1406
+ headers: {
1407
+ "Content-Type": "application/x-www-form-urlencoded",
1408
+ Accept: "application/json"
1409
+ },
1410
+ body: body.toString()
1411
+ });
1412
+ if (!response.ok) {
1413
+ const errorData = await response.json().catch(() => ({}));
1414
+ return {
1415
+ error: errorData.error || "provider_error",
1416
+ error_description: errorData.error_description || `Provider returned ${response.status}`
1417
+ };
1418
+ }
1419
+ return await response.json();
1420
+ } catch (err) {
1421
+ return {
1422
+ error: "provider_error",
1423
+ error_description: `Failed to refresh token with provider: ${err}`
1424
+ };
1425
+ }
1426
+ }
1427
+ /**
1428
+ * What renews an upstream provider's access token with its refresh token when `this.orchestration`
1429
+ * finds it expired, or none with `refresh.enabled: false`. Renewals with the same refresh token
1430
+ * share one request: a provider that rotates refresh tokens accepts each only once.
1431
+ */
1432
+ providerTokenRefresher() {
1433
+ if (!isOrchestratedMode(this.options) || this.options.refresh?.enabled === false) return void 0;
1434
+ return (providerId, refreshToken) => {
1435
+ const key = JSON.stringify([providerId, refreshToken]);
1436
+ const inFlight = this.providerRenewals.get(key);
1437
+ if (inFlight) return inFlight;
1438
+ const renewal = this.renewProviderToken(providerId, refreshToken).finally(
1439
+ () => this.providerRenewals.delete(key)
1440
+ );
1441
+ this.providerRenewals.set(key, renewal);
1442
+ return renewal;
1443
+ };
1444
+ }
1445
+ async renewProviderToken(providerId, refreshToken) {
1446
+ const result = await this.refreshProviderToken(providerId, refreshToken);
1447
+ if ("error" in result || typeof result.access_token !== "string" || !result.access_token) {
1448
+ this.logger.warn(
1449
+ `Provider ${providerId} did not refresh its token: ${"error" in result ? result.error : "no access_token"}`
1450
+ );
1451
+ throw new TokenNotAvailableError(
1452
+ `Provider "${providerId}" did not refresh its token; the user has to sign in again`
1453
+ );
1454
+ }
1455
+ return { accessToken: result.access_token, refreshToken: result.refresh_token, expiresIn: result.expires_in };
1456
+ }
1457
+ /** How long before its expiry a provider token is renewed: `refresh.skewSeconds` (default 60), none with `refresh` off. */
1458
+ providerRefreshSkewMs() {
1459
+ if (!isOrchestratedMode(this.options) || this.options.refresh?.enabled === false) return 0;
1460
+ return (this.options.refresh?.skewSeconds ?? 60) * 1e3;
1461
+ }
1462
+ };
1463
+ export {
1464
+ LocalPrimaryAuth,
1465
+ validateAuthorizationIssuer
1466
+ };