@selvajs/selva 4.20.1-beta.5 → 4.21.0-beta.7

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 (195) hide show
  1. package/build/adapter-node.js +1 -1
  2. package/build/client/_app/immutable/chunks/{CzfnuBzq.js → BAhtiTKe.js} +1 -1
  3. package/build/client/_app/immutable/chunks/BAhtiTKe.js.br +0 -0
  4. package/build/client/_app/immutable/chunks/BAhtiTKe.js.gz +0 -0
  5. package/build/client/_app/immutable/chunks/{D-uUm_OB.js → BepzH9eI.js} +4 -4
  6. package/build/client/_app/immutable/chunks/BepzH9eI.js.br +0 -0
  7. package/build/client/_app/immutable/chunks/{D-uUm_OB.js.gz → BepzH9eI.js.gz} +0 -0
  8. package/build/client/_app/immutable/chunks/BmoT9ksD.js +1 -0
  9. package/build/client/_app/immutable/chunks/BmoT9ksD.js.br +1 -0
  10. package/build/client/_app/immutable/chunks/BmoT9ksD.js.gz +0 -0
  11. package/build/client/_app/immutable/chunks/{qi43d-TM.js → CKbHmAlc.js} +1 -1
  12. package/build/client/_app/immutable/chunks/CKbHmAlc.js.br +0 -0
  13. package/build/client/_app/immutable/chunks/CKbHmAlc.js.gz +0 -0
  14. package/build/client/_app/immutable/chunks/{C6Y_BUwr.js → CmlXAF26.js} +1 -1
  15. package/build/client/_app/immutable/chunks/CmlXAF26.js.br +0 -0
  16. package/build/client/_app/immutable/chunks/CmlXAF26.js.gz +0 -0
  17. package/build/client/_app/immutable/chunks/{BDYCH-_Q.js → D5j4-ZO1.js} +1 -1
  18. package/build/client/_app/immutable/chunks/D5j4-ZO1.js.br +0 -0
  19. package/build/client/_app/immutable/chunks/D5j4-ZO1.js.gz +0 -0
  20. package/build/client/_app/immutable/chunks/DW5EJMC7.js +1 -0
  21. package/build/client/_app/immutable/chunks/DW5EJMC7.js.br +0 -0
  22. package/build/client/_app/immutable/chunks/DW5EJMC7.js.gz +0 -0
  23. package/build/client/_app/immutable/chunks/{DzxE3j6C.js → qXnHMKD9.js} +1 -1
  24. package/build/client/_app/immutable/chunks/qXnHMKD9.js.br +0 -0
  25. package/build/client/_app/immutable/chunks/qXnHMKD9.js.gz +0 -0
  26. package/build/client/_app/immutable/entry/{app.BpT6WkO1.js → app.Cmuegtgc.js} +2 -2
  27. package/build/client/_app/immutable/entry/app.Cmuegtgc.js.br +0 -0
  28. package/build/client/_app/immutable/entry/app.Cmuegtgc.js.gz +0 -0
  29. package/build/client/_app/immutable/nodes/{1.D3kiiIk_.js → 1.DWd6YbcT.js} +1 -1
  30. package/build/client/_app/immutable/nodes/1.DWd6YbcT.js.br +0 -0
  31. package/build/client/_app/immutable/nodes/1.DWd6YbcT.js.gz +0 -0
  32. package/build/client/_app/immutable/nodes/{2.CUNbzjI_.js → 2.CS32Eh9m.js} +1 -1
  33. package/build/client/_app/immutable/nodes/2.CS32Eh9m.js.br +0 -0
  34. package/build/client/_app/immutable/nodes/2.CS32Eh9m.js.gz +0 -0
  35. package/build/client/_app/immutable/nodes/{20.9OIre0ah.js → 20.CUK41A3B.js} +1 -1
  36. package/build/client/_app/immutable/nodes/20.CUK41A3B.js.br +0 -0
  37. package/build/client/_app/immutable/nodes/20.CUK41A3B.js.gz +0 -0
  38. package/build/client/_app/immutable/nodes/21.DvC40Ypm.js +1 -0
  39. package/build/client/_app/immutable/nodes/21.DvC40Ypm.js.br +0 -0
  40. package/build/client/_app/immutable/nodes/21.DvC40Ypm.js.gz +0 -0
  41. package/build/client/_app/immutable/nodes/24.DkL5kHzA.js +3 -0
  42. package/build/client/_app/immutable/nodes/24.DkL5kHzA.js.br +0 -0
  43. package/build/client/_app/immutable/nodes/24.DkL5kHzA.js.gz +0 -0
  44. package/build/client/_app/immutable/nodes/{25.DW1_vMxq.js → 25.D6EkgNRa.js} +1 -1
  45. package/build/client/_app/immutable/nodes/25.D6EkgNRa.js.br +0 -0
  46. package/build/client/_app/immutable/nodes/25.D6EkgNRa.js.gz +0 -0
  47. package/build/client/_app/immutable/nodes/{3.3Z4QUsQQ.js → 3.Ctd9OGCk.js} +1 -1
  48. package/build/client/_app/immutable/nodes/3.Ctd9OGCk.js.br +0 -0
  49. package/build/client/_app/immutable/nodes/3.Ctd9OGCk.js.gz +0 -0
  50. package/build/client/_app/immutable/nodes/{5.DmA9lTA-.js → 5.Wh_w3RkZ.js} +1 -1
  51. package/build/client/_app/immutable/nodes/5.Wh_w3RkZ.js.br +2 -0
  52. package/build/client/_app/immutable/nodes/5.Wh_w3RkZ.js.gz +0 -0
  53. package/build/client/_app/immutable/nodes/{6.D6WLqCgl.js → 6.C-DiUI5R.js} +1 -1
  54. package/build/client/_app/immutable/nodes/6.C-DiUI5R.js.br +0 -0
  55. package/build/client/_app/immutable/nodes/6.C-DiUI5R.js.gz +0 -0
  56. package/build/client/_app/immutable/nodes/{7.CNuRjkv2.js → 7.B8yubYrv.js} +1 -1
  57. package/build/client/_app/immutable/nodes/7.B8yubYrv.js.br +0 -0
  58. package/build/client/_app/immutable/nodes/7.B8yubYrv.js.gz +0 -0
  59. package/build/client/_app/version.json +1 -1
  60. package/build/client/_app/version.json.br +0 -0
  61. package/build/client/_app/version.json.gz +0 -0
  62. package/build/server/.vite/manifest.json +10 -12
  63. package/build/server/chunks/api.js +9 -2
  64. package/build/server/chunks/api.js.map +1 -1
  65. package/build/server/chunks/computeRateLimit.server.js +1 -1
  66. package/build/server/chunks/grasshopper.js +13 -2
  67. package/build/server/chunks/grasshopper.js.map +1 -1
  68. package/build/server/chunks/handlers.js +21 -17
  69. package/build/server/chunks/handlers.js.map +1 -1
  70. package/build/server/chunks/instance.js +3 -3
  71. package/build/server/chunks/internal.js +1 -1
  72. package/build/server/chunks/liveSolve.server.js +1 -1
  73. package/build/server/chunks/localeContext.svelte.js +14 -0
  74. package/build/server/chunks/localeContext.svelte.js.map +1 -1
  75. package/build/server/chunks/oauth.js +70 -24
  76. package/build/server/chunks/oauth.js.map +1 -1
  77. package/build/server/chunks/{outcome-DNrffAXp.js → outcome-D28FgvFK.js} +9 -6
  78. package/build/server/chunks/outcome-D28FgvFK.js.map +1 -0
  79. package/build/server/chunks/package.js +1 -1
  80. package/build/server/chunks/package.js.map +1 -1
  81. package/build/server/chunks/providers.server.js +4 -2
  82. package/build/server/chunks/providers.server.js.map +1 -1
  83. package/build/server/chunks/registry.js +1 -1
  84. package/build/server/chunks/schema.js +1 -1
  85. package/build/server/chunks/schema.js.map +1 -1
  86. package/build/server/chunks/server2.js +2 -2
  87. package/build/server/chunks/server2.js.map +1 -1
  88. package/build/server/chunks/serverStats.server.js +1 -1
  89. package/build/server/chunks/solve.server.js +5 -4
  90. package/build/server/chunks/solve.server.js.map +1 -1
  91. package/build/server/chunks/sveltekit.js +1 -1
  92. package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js +6 -3
  93. package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js.map +1 -1
  94. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js +6 -3
  95. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js.map +1 -1
  96. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js +6 -3
  97. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js.map +1 -1
  98. package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js +1 -1
  99. package/build/server/entries/endpoints/api/admin/orgs/_id_/_server.ts.js +1 -1
  100. package/build/server/entries/endpoints/api/admin/orgs/_server.ts.js +1 -1
  101. package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js +1 -1
  102. package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_grantId_/_server.ts.js +1 -1
  103. package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_server.ts.js +1 -1
  104. package/build/server/entries/endpoints/api/admin/projects/_server.ts.js +1 -1
  105. package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js +1 -1
  106. package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js +1 -1
  107. package/build/server/entries/endpoints/api/admin/users/_server.ts.js +1 -1
  108. package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +5 -1
  109. package/build/server/entries/endpoints/api/v1/compute/_server.ts.js.map +1 -1
  110. package/build/server/entries/endpoints/api/v1/compute/schema/_server.ts.js +1 -1
  111. package/build/server/entries/endpoints/api/v1/definitions/_guid_/_server.ts.js +1 -1
  112. package/build/server/entries/endpoints/api/v1/definitions/_guid_/image/_server.ts.js +1 -1
  113. package/build/server/entries/endpoints/api/v1/definitions/_guid_/publish/_server.ts.js +1 -1
  114. package/build/server/entries/endpoints/api/v1/definitions/_guid_/schema/_server.ts.js +1 -1
  115. package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_linkId_/_server.ts.js +1 -1
  116. package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_server.ts.js +1 -1
  117. package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +2 -1
  118. package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js.map +1 -1
  119. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_server.ts.js +1 -1
  120. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/_server.ts.js +1 -1
  121. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/schema/_server.ts.js +1 -1
  122. package/build/server/entries/endpoints/api/v1/projects/_id_/_server.ts.js +1 -1
  123. package/build/server/entries/endpoints/api/v1/projects/_id_/members/_server.ts.js +1 -1
  124. package/build/server/entries/endpoints/api/v1/projects/_id_/members/_userId_/_server.ts.js +1 -1
  125. package/build/server/entries/endpoints/api/v1/projects/_id_/reclaim/_server.ts.js +1 -1
  126. package/build/server/entries/endpoints/api/v1/solve/_solveId_/cancel/_server.ts.js +1 -1
  127. package/build/server/entries/endpoints/api/v1/solve-events/_server.ts.js +1 -1
  128. package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
  129. package/build/server/entries/endpoints/mcp/_server.ts.js +5 -4
  130. package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
  131. package/build/server/entries/endpoints/oauth/register/_server.ts.js +1 -1
  132. package/build/server/entries/endpoints/oauth/token/_server.ts.js +1 -1
  133. package/build/server/entries/pages/library/_guid_/_page.server.ts.js +2 -2
  134. package/build/server/entries/pages/library/_guid_/_page.svelte.js +232 -11
  135. package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
  136. package/build/server/entries/pages/oauth/authorize/_page.server.ts.js +3 -2
  137. package/build/server/entries/pages/oauth/authorize/_page.server.ts.js.map +1 -1
  138. package/build/server/entries/pages/oauth/authorize/_page.svelte.js +8 -1
  139. package/build/server/entries/pages/oauth/authorize/_page.svelte.js.map +1 -1
  140. package/build/server/manifest-full.js +1 -1
  141. package/build/server/manifest.js +1 -1
  142. package/build/server/nodes/1.js +1 -1
  143. package/build/server/nodes/2.js +1 -1
  144. package/build/server/nodes/20.js +1 -1
  145. package/build/server/nodes/21.js +1 -1
  146. package/build/server/nodes/24.js +1 -1
  147. package/build/server/nodes/25.js +1 -1
  148. package/build/server/nodes/3.js +1 -1
  149. package/build/server/nodes/5.js +1 -1
  150. package/build/server/nodes/6.js +1 -1
  151. package/build/server/nodes/7.js +1 -1
  152. package/build/server/server.js +1 -1
  153. package/package.json +10 -10
  154. package/build/client/_app/immutable/chunks/BDYCH-_Q.js.br +0 -0
  155. package/build/client/_app/immutable/chunks/BDYCH-_Q.js.gz +0 -0
  156. package/build/client/_app/immutable/chunks/C6Y_BUwr.js.br +0 -0
  157. package/build/client/_app/immutable/chunks/C6Y_BUwr.js.gz +0 -0
  158. package/build/client/_app/immutable/chunks/CzfnuBzq.js.br +0 -0
  159. package/build/client/_app/immutable/chunks/CzfnuBzq.js.gz +0 -0
  160. package/build/client/_app/immutable/chunks/D-uUm_OB.js.br +0 -0
  161. package/build/client/_app/immutable/chunks/D84F7w9g.js +0 -1
  162. package/build/client/_app/immutable/chunks/D84F7w9g.js.br +0 -1
  163. package/build/client/_app/immutable/chunks/D84F7w9g.js.gz +0 -0
  164. package/build/client/_app/immutable/chunks/DQsP4nZb.js +0 -1
  165. package/build/client/_app/immutable/chunks/DQsP4nZb.js.br +0 -0
  166. package/build/client/_app/immutable/chunks/DQsP4nZb.js.gz +0 -0
  167. package/build/client/_app/immutable/chunks/DzxE3j6C.js.br +0 -0
  168. package/build/client/_app/immutable/chunks/DzxE3j6C.js.gz +0 -0
  169. package/build/client/_app/immutable/chunks/qi43d-TM.js.br +0 -0
  170. package/build/client/_app/immutable/chunks/qi43d-TM.js.gz +0 -0
  171. package/build/client/_app/immutable/entry/app.BpT6WkO1.js.br +0 -0
  172. package/build/client/_app/immutable/entry/app.BpT6WkO1.js.gz +0 -0
  173. package/build/client/_app/immutable/nodes/1.D3kiiIk_.js.br +0 -0
  174. package/build/client/_app/immutable/nodes/1.D3kiiIk_.js.gz +0 -0
  175. package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.br +0 -0
  176. package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.gz +0 -0
  177. package/build/client/_app/immutable/nodes/20.9OIre0ah.js.br +0 -0
  178. package/build/client/_app/immutable/nodes/20.9OIre0ah.js.gz +0 -0
  179. package/build/client/_app/immutable/nodes/21.BkNlRItr.js +0 -1
  180. package/build/client/_app/immutable/nodes/21.BkNlRItr.js.br +0 -0
  181. package/build/client/_app/immutable/nodes/21.BkNlRItr.js.gz +0 -0
  182. package/build/client/_app/immutable/nodes/24.CPSunfJJ.js +0 -3
  183. package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.br +0 -0
  184. package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.gz +0 -0
  185. package/build/client/_app/immutable/nodes/25.DW1_vMxq.js.br +0 -0
  186. package/build/client/_app/immutable/nodes/25.DW1_vMxq.js.gz +0 -0
  187. package/build/client/_app/immutable/nodes/3.3Z4QUsQQ.js.br +0 -0
  188. package/build/client/_app/immutable/nodes/3.3Z4QUsQQ.js.gz +0 -0
  189. package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.br +0 -1
  190. package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.gz +0 -0
  191. package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.br +0 -0
  192. package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.gz +0 -0
  193. package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.br +0 -0
  194. package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.gz +0 -0
  195. package/build/server/chunks/outcome-DNrffAXp.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.js","names":["sign"],"sources":["../../../../server/src/oauth/index.ts"],"sourcesContent":["/**\n * OAuth 2.1 for MCP clients and the Grasshopper plugin, with this instance as\n * its own authorization server.\n *\n * The access token is an ordinary API token. The host mints it while the user is\n * signed in, at consent, through the same path as Team → API tokens; this\n * module seals the raw key into the authorization code and hands it over at the\n * token endpoint. So `/mcp` and `/api/v1` keep one credential type.\n *\n * Nothing here is stored. A registered client's id is its own signed metadata,\n * and a code is its own encrypted grant, bound to the issuing origin. The only\n * state is the set of redeemed codes, in the host's memory, so on several\n * replicas a code could be redeemed once per replica within its minute, and only\n * by whoever holds the PKCE verifier.\n */\n\nimport {\n\tcreateCipheriv,\n\tcreateDecipheriv,\n\tcreateHash,\n\tcreateHmac,\n\thkdfSync,\n\trandomBytes,\n\ttimingSafeEqual\n} from 'node:crypto';\n\n/** The scopes a grant can carry. Each maps to one org-wide API scope. */\nexport const OAUTH_SCOPES = ['read', 'solve', 'upload', 'create_projects'] as const;\nexport type OAuthScope = (typeof OAUTH_SCOPES)[number];\n\n/**\n * All a registered (DCR or CIMD) client can be granted. Its name and redirects\n * are whatever the registrant chose, so `upload`, which puts code on the org's\n * Compute server, and `create_projects` stay with the built-in client and a\n * look-alike can't phish for them.\n */\nexport const REGISTERED_CLIENT_SCOPES = ['read', 'solve'] as const satisfies readonly OAuthScope[];\n\n/** The Grasshopper plugin's client id. Built in, so it needs no registration and works air-gapped. */\nexport const GRASSHOPPER_CLIENT_ID = 'selva-grasshopper';\n\n// Loopback on any port (RFC 8252 §7.3), but only this host and path: the code\n// can only ever reach a program on the user's own machine.\nconst GRASSHOPPER_CLIENT: OAuthClient = {\n\tclientId: GRASSHOPPER_CLIENT_ID,\n\tname: 'Selva for Grasshopper',\n\tredirectUris: ['http://127.0.0.1/callback'],\n\tbuiltIn: true,\n\tscopes: ['read', 'upload', 'create_projects']\n};\n\nexport const MCP_PATH = '/mcp';\n\nexport const CODE_TTL_MS = 60_000;\nconst CLIENT_NAME_MAX = 100;\nconst REDIRECT_URIS_MAX = 10;\nconst CIMD_TTL_MS = 60 * 60_000;\n// A failing metadata URL is not refetched for this long: each fetch is outbound\n// work an anonymous caller could otherwise trigger at will.\nconst CIMD_FAILURE_TTL_MS = 60_000;\nconst CIMD_CACHE_MAX = 500;\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nexport class OAuthError extends Error {\n\tconstructor(\n\t\t/** RFC 6749 / 7591 error code. */\n\t\treadonly error: string,\n\t\tdescription: string,\n\t\treadonly status = 400\n\t) {\n\t\tsuper(description);\n\t\tthis.name = 'OAuthError';\n\t}\n\n\ttoBody(): { error: string; error_description: string } {\n\t\treturn { error: this.error, error_description: this.message };\n\t}\n}\n\nexport interface OAuthClient {\n\tclientId: string;\n\t/** Shown on the consent page. Unverified for a registered client: whatever it claimed. */\n\tname: string;\n\tredirectUris: string[];\n\t/** Shipped with this server, so its name can be trusted. */\n\tbuiltIn: boolean;\n\t/** All this client can be granted, whatever it asks for. */\n\tscopes: readonly OAuthScope[];\n}\n\n/** A validated `/oauth/authorize` request, ready for the consent page. */\nexport interface AuthorizeRequest {\n\tclient: OAuthClient;\n\tredirectUri: string;\n\tstate?: string;\n\tcodeChallenge: string;\n\tscopes: OAuthScope[];\n\tresource: string;\n}\n\n/** What the host minted at consent. `secret` is the raw API key. */\nexport interface Grant {\n\ttokenId: string;\n\tsecret: string;\n\tscopes: OAuthScope[];\n\texpiresAt: string;\n}\n\nexport interface OAuthServerOptions {\n\t/** This instance's origin, e.g. `https://selva.example.com`. */\n\torigin: string;\n\t/** `SELVA_HMAC_KEY`. Signs client ids and seals codes. */\n\tsecret: string;\n\t/** The key before the last rotation: client ids and codes it made still verify. */\n\tpreviousSecret?: string;\n\t/**\n\t * Fetches a Client ID Metadata Document. The URL comes from an unknown client,\n\t * so the host must guard it against SSRF. Without it, URL client ids are refused.\n\t */\n\tfetchClientMetadata?: (url: string) => Promise<unknown>;\n\t/**\n\t * Redeemed code hashes and their expiry. Pass one map for the process so a\n\t * rebuilt server (a new origin, a rotated secret) still refuses a replay.\n\t */\n\tredeemedCodes?: Map<string, number>;\n\t/** Called once a code is exchanged, with the token its grant carries. */\n\tonRedeemed?: (tokenId: string) => void;\n\tnow?: () => number;\n}\n\ninterface HttpResult {\n\tstatus: number;\n\tbody: Record<string, unknown>;\n}\n\n// ============================================================================\n// Discovery documents\n// ============================================================================\n\nexport function mcpResourceUrl(origin: string): string {\n\treturn origin + MCP_PATH;\n}\n\nexport function resourceMetadataUrl(origin: string): string {\n\treturn `${origin}/.well-known/oauth-protected-resource${MCP_PATH}`;\n}\n\n/** RFC 9728. Claude uses only the first authorization server. */\nexport function protectedResourceMetadata(origin: string) {\n\treturn {\n\t\tresource: mcpResourceUrl(origin),\n\t\tauthorization_servers: [origin],\n\t\tscopes_supported: [...REGISTERED_CLIENT_SCOPES],\n\t\tbearer_methods_supported: ['header']\n\t};\n}\n\n/**\n * RFC 8414. Claude picks Client ID Metadata Documents only when both\n * `client_id_metadata_document_supported` and the `none` auth method appear.\n */\nexport function authorizationServerMetadata(origin: string) {\n\treturn {\n\t\tissuer: origin,\n\t\tauthorization_endpoint: `${origin}/oauth/authorize`,\n\t\ttoken_endpoint: `${origin}/oauth/token`,\n\t\tregistration_endpoint: `${origin}/oauth/register`,\n\t\tresponse_types_supported: ['code'],\n\t\tgrant_types_supported: ['authorization_code'],\n\t\tcode_challenge_methods_supported: ['S256'],\n\t\ttoken_endpoint_auth_methods_supported: ['none'],\n\t\tscopes_supported: [...OAUTH_SCOPES],\n\t\tclient_id_metadata_document_supported: true,\n\t\tauthorization_response_iss_parameter_supported: true\n\t};\n}\n\n// ============================================================================\n// Server\n// ============================================================================\n\nexport function createOAuthServer(options: OAuthServerOptions) {\n\tconst { origin } = options;\n\tconst now = options.now ?? Date.now;\n\tconst signKey = derive(options.secret, 'selva-oauth-client');\n\tconst codeKey = derive(options.secret, `selva-oauth-code:${origin}`);\n\tconst previous = options.previousSecret;\n\tconst previousSignKey = previous ? derive(previous, 'selva-oauth-client') : undefined;\n\tconst previousCodeKey = previous ? derive(previous, `selva-oauth-code:${origin}`) : undefined;\n\tconst redeemed = options.redeemedCodes ?? new Map<string, number>();\n\tconst metadataCache = new Map<\n\t\tstring,\n\t\t{ at: number; client: OAuthClient } | { at: number; failure: OAuthError }\n\t>();\n\n\t// ==========================================================================\n\t// Clients\n\t// ==========================================================================\n\n\t/** RFC 7591. The client id carries the metadata, signed, so nothing is stored. */\n\tfunction register(input: unknown): HttpResult {\n\t\ttry {\n\t\t\tconst meta = (input ?? {}) as { client_name?: unknown; redirect_uris?: unknown };\n\t\t\tconst redirectUris = checkRedirectUris(meta.redirect_uris);\n\t\t\tconst name = typeof meta.client_name === 'string' ? meta.client_name.trim() : '';\n\t\t\tconst payload = b64(\n\t\t\t\tJSON.stringify({ n: name.slice(0, CLIENT_NAME_MAX), r: redirectUris, t: now() })\n\t\t\t);\n\t\t\tconst clientId = `dcr_${payload}.${sign(signKey, payload)}`;\n\t\t\treturn {\n\t\t\t\tstatus: 201,\n\t\t\t\tbody: {\n\t\t\t\t\tclient_id: clientId,\n\t\t\t\t\tclient_id_issued_at: Math.floor(now() / 1000),\n\t\t\t\t\tclient_name: name || undefined,\n\t\t\t\t\tredirect_uris: redirectUris,\n\t\t\t\t\tgrant_types: ['authorization_code'],\n\t\t\t\t\tresponse_types: ['code'],\n\t\t\t\t\ttoken_endpoint_auth_method: 'none'\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync function resolveClient(clientId: string): Promise<OAuthClient> {\n\t\tif (clientId === GRASSHOPPER_CLIENT_ID) return GRASSHOPPER_CLIENT;\n\t\tif (clientId.startsWith('dcr_')) return registeredClient(clientId);\n\t\tif (clientId.startsWith('https://')) return metadataClient(clientId);\n\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t}\n\n\tfunction registeredClient(clientId: string): OAuthClient {\n\t\tconst [payload, signature] = clientId.slice('dcr_'.length).split('.');\n\t\tconst signedBy = (key: Buffer | undefined) =>\n\t\t\tkey !== undefined && safeEqual(signature, sign(key, payload));\n\t\tif (!payload || !signature || !(signedBy(signKey) || signedBy(previousSignKey))) {\n\t\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t\t}\n\t\tconst meta = JSON.parse(unb64(payload)) as { n: string; r: string[] };\n\t\treturn {\n\t\t\tclientId,\n\t\t\tname: meta.n || 'An MCP client',\n\t\t\tredirectUris: meta.r,\n\t\t\tbuiltIn: false,\n\t\t\tscopes: REGISTERED_CLIENT_SCOPES\n\t\t};\n\t}\n\n\tasync function metadataClient(url: string): Promise<OAuthClient> {\n\t\tconst cached = metadataCache.get(url);\n\t\tif (cached) {\n\t\t\tif ('client' in cached && now() - cached.at < CIMD_TTL_MS) return cached.client;\n\t\t\tif ('failure' in cached && now() - cached.at < CIMD_FAILURE_TTL_MS) throw cached.failure;\n\t\t}\n\t\tif (!options.fetchClientMetadata) {\n\t\t\tthrow new OAuthError('invalid_client', 'This server does not accept URL client ids.');\n\t\t}\n\t\ttry {\n\t\t\tconst client = await readMetadata(url, options.fetchClientMetadata);\n\t\t\tremember(url, { at: now(), client });\n\t\t\treturn client;\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof OAuthError)) throw err;\n\t\t\tremember(url, { at: now(), failure: err });\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction remember(url: string, entry: Parameters<typeof metadataCache.set>[1]) {\n\t\tif (metadataCache.size >= CIMD_CACHE_MAX) {\n\t\t\tmetadataCache.delete(metadataCache.keys().next().value!);\n\t\t}\n\t\tmetadataCache.set(url, entry);\n\t}\n\n\t// ==========================================================================\n\t// Authorization\n\t// ==========================================================================\n\n\t/**\n\t * Validates the query `/oauth/authorize` arrives with. An `OAuthError` from a\n\t * bad client or redirect URI must be shown, not redirected: the redirect target\n\t * is exactly what can't be trusted.\n\t */\n\tasync function parseAuthorizeRequest(query: URLSearchParams): Promise<AuthorizeRequest> {\n\t\tconst client = await resolveClient(query.get('client_id') ?? '');\n\t\tconst redirectUri = query.get('redirect_uri') ?? '';\n\t\tif (!client.redirectUris.some((r) => redirectMatches(r, redirectUri))) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_request',\n\t\t\t\t'The redirect URI is not registered for this client.'\n\t\t\t);\n\t\t}\n\t\tif (query.get('response_type') !== 'code') {\n\t\t\tthrow new OAuthError('unsupported_response_type', 'Only response_type=code is supported.');\n\t\t}\n\t\tconst codeChallenge = query.get('code_challenge') ?? '';\n\t\tif (!codeChallenge || query.get('code_challenge_method') !== 'S256') {\n\t\t\tthrow new OAuthError('invalid_request', 'PKCE with code_challenge_method=S256 is required.');\n\t\t}\n\t\tconst resource = query.get('resource') ?? mcpResourceUrl(origin);\n\t\tif (!isThisResource(resource)) {\n\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t}\n\t\treturn {\n\t\t\tclient,\n\t\t\tredirectUri,\n\t\t\tstate: query.get('state') ?? undefined,\n\t\t\tcodeChallenge,\n\t\t\tscopes: parseScopes(query.get('scope'), client.scopes),\n\t\t\tresource\n\t\t};\n\t}\n\n\t/** Where to send the browser after consent: the client's redirect URI with a code. */\n\tfunction approve(request: AuthorizeRequest, grant: Grant): string {\n\t\tconst code = seal(codeKey, {\n\t\t\tc: request.client.clientId,\n\t\t\tr: request.redirectUri,\n\t\t\tp: request.codeChallenge,\n\t\t\tx: now() + CODE_TTL_MS,\n\t\t\tg: grant\n\t\t});\n\t\treturn withParams(request.redirectUri, { code, state: request.state, iss: origin });\n\t}\n\n\tfunction deny(request: AuthorizeRequest): string {\n\t\treturn withParams(request.redirectUri, {\n\t\t\terror: 'access_denied',\n\t\t\tstate: request.state,\n\t\t\tiss: origin\n\t\t});\n\t}\n\n\t// ==========================================================================\n\t// Token endpoint\n\t// ==========================================================================\n\n\tfunction exchange(form: URLSearchParams): HttpResult {\n\t\ttry {\n\t\t\tif (form.get('grant_type') !== 'authorization_code') {\n\t\t\t\tthrow new OAuthError('unsupported_grant_type', 'Only authorization_code is supported.');\n\t\t\t}\n\t\t\tconst code = form.get('code') ?? '';\n\t\t\tconst sealed = (open(codeKey, code) ??\n\t\t\t\t(previousCodeKey ? open(previousCodeKey, code) : null)) as {\n\t\t\t\tc: string;\n\t\t\t\tr: string;\n\t\t\t\tp: string;\n\t\t\t\tx: number;\n\t\t\t\tg: Grant;\n\t\t\t} | null;\n\t\t\tif (!sealed || sealed.x < now()) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code is invalid or expired.');\n\t\t\t}\n\t\t\tif (sealed.c !== form.get('client_id') || sealed.r !== form.get('redirect_uri')) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was issued to another client.');\n\t\t\t}\n\t\t\tconst verifier = form.get('code_verifier') ?? '';\n\t\t\tif (!safeEqual(createHash('sha256').update(verifier).digest('base64url'), sealed.p)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code_verifier does not match.');\n\t\t\t}\n\t\t\tconst resource = form.get('resource');\n\t\t\tif (resource !== null && !isThisResource(resource)) {\n\t\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t\t}\n\t\t\tif (!markRedeemed(code, sealed.x)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was already used.');\n\t\t\t}\n\t\t\tconst { g } = sealed;\n\t\t\toptions.onRedeemed?.(g.tokenId);\n\t\t\treturn {\n\t\t\t\tstatus: 200,\n\t\t\t\tbody: {\n\t\t\t\t\taccess_token: g.secret,\n\t\t\t\t\ttoken_type: 'Bearer',\n\t\t\t\t\texpires_in: Math.max(0, Math.floor((Date.parse(g.expiresAt) - now()) / 1000)),\n\t\t\t\t\tscope: g.scopes.join(' ')\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction markRedeemed(code: string, expiresAt: number): boolean {\n\t\tconst t = now();\n\t\tfor (const [k, x] of redeemed) if (x < t) redeemed.delete(k);\n\t\tconst id = createHash('sha256').update(code).digest('base64url');\n\t\tif (redeemed.has(id)) return false;\n\t\tredeemed.set(id, expiresAt);\n\t\treturn true;\n\t}\n\n\tfunction isThisResource(resource: string): boolean {\n\t\tconst r = resource.replace(/\\/$/, '');\n\t\treturn r === origin || r === mcpResourceUrl(origin);\n\t}\n\n\treturn {\n\t\tregister,\n\t\tresolveClient,\n\t\tparseAuthorizeRequest,\n\t\tapprove,\n\t\tdeny,\n\t\texchange,\n\t\tprotectedResourceMetadata: () => protectedResourceMetadata(origin),\n\t\tauthorizationServerMetadata: () => authorizationServerMetadata(origin)\n\t};\n}\n\nexport type OAuthServer = ReturnType<typeof createOAuthServer>;\n\n/** OAuth scopes to the API scopes a minted token gets. */\nexport function apiScopesFor(scopes: readonly OAuthScope[]): string[] {\n\treturn scopes.map((s) => `${s}:all`);\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nasync function readMetadata(\n\turl: string,\n\tfetchClientMetadata: (url: string) => Promise<unknown>\n): Promise<OAuthClient> {\n\tlet doc: { client_id?: unknown; client_name?: unknown; redirect_uris?: unknown };\n\ttry {\n\t\tdoc = (await fetchClientMetadata(url)) as typeof doc;\n\t} catch {\n\t\tthrow new OAuthError('invalid_client', 'The client metadata document could not be read.');\n\t}\n\tif (doc?.client_id !== url) {\n\t\tthrow new OAuthError('invalid_client', 'The metadata document names a different client_id.');\n\t}\n\treturn {\n\t\tclientId: url,\n\t\tname:\n\t\t\ttypeof doc.client_name === 'string' && doc.client_name.trim()\n\t\t\t\t? doc.client_name.trim().slice(0, CLIENT_NAME_MAX)\n\t\t\t\t: new URL(url).host,\n\t\tredirectUris: checkRedirectUris(doc.redirect_uris),\n\t\tbuiltIn: false,\n\t\tscopes: REGISTERED_CLIENT_SCOPES\n\t};\n}\n\n/**\n * What the request asks for, within what its client may have. A scope outside\n * that is dropped, not refused, so a client that asks for every advertised\n * scope still signs in with what it may have. No `scope` at all means all of\n * them. Asking only for scopes it may not have gets `read`, never more than it\n * asked for. `read` rides along with `solve`, which the consent page offers as\n * \"read and run solves\".\n */\nfunction parseScopes(raw: string | null, allowed: readonly OAuthScope[]): OAuthScope[] {\n\tconst requested = (raw ?? '').split(' ').filter(Boolean);\n\tif (!requested.length) return [...allowed];\n\tconst asked = requested.filter((s): s is OAuthScope =>\n\t\t(allowed as readonly string[]).includes(s)\n\t);\n\tif (!asked.length) return allowed.includes('read') ? ['read'] : [];\n\treturn allowed.filter((s) => asked.includes(s) || (s === 'read' && asked.includes('solve')));\n}\n\n/** One access level a consent page offers, and the scopes approving it grants. */\nexport interface ConsentChoice {\n\taccess: 'read' | 'solve' | 'upload';\n\tscopes: OAuthScope[];\n}\n\n/**\n * The access levels a consent page offers for a request, narrowest first. The\n * user may narrow what the client asked for, never widen it. An upload request\n * is offered as asked: narrowing it to read would leave the client unable to\n * do the one thing it signed in for.\n */\nexport function consentChoices(scopes: readonly OAuthScope[]): ConsentChoice[] {\n\tif (scopes.includes('upload')) return [{ access: 'upload', scopes: [...scopes] }];\n\tconst choices: ConsentChoice[] = [{ access: 'read', scopes: ['read'] }];\n\tif (scopes.includes('solve')) choices.push({ access: 'solve', scopes: [...scopes] });\n\treturn choices;\n}\n\nfunction checkRedirectUris(value: unknown): string[] {\n\tif (!Array.isArray(value) || !value.length || value.length > REDIRECT_URIS_MAX) {\n\t\tthrow new OAuthError('invalid_redirect_uri', 'Give between 1 and 10 redirect_uris.');\n\t}\n\tfor (const uri of value) {\n\t\tif (typeof uri !== 'string' || !isAllowedRedirect(uri)) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_redirect_uri',\n\t\t\t\t'Redirect URIs must be https, or http on a loopback address.'\n\t\t\t);\n\t\t}\n\t}\n\treturn value as string[];\n}\n\nfunction isAllowedRedirect(uri: string): boolean {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(uri);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (url.hash) return false;\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\n/** A redirect to a program on the user's own machine, which any local process can claim. */\nexport function isLoopbackRedirect(uri: string): boolean {\n\ttry {\n\t\treturn LOOPBACK_HOSTS.has(new URL(uri).hostname);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Exact, except a loopback redirect matches on any port (RFC 8252 §7.3). */\nexport function redirectMatches(registered: string, requested: string): boolean {\n\tif (registered === requested) return true;\n\tlet a: URL, b: URL;\n\ttry {\n\t\ta = new URL(registered);\n\t\tb = new URL(requested);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn (\n\t\ta.protocol === 'http:' &&\n\t\tb.protocol === 'http:' &&\n\t\tLOOPBACK_HOSTS.has(a.hostname) &&\n\t\ta.hostname === b.hostname &&\n\t\ta.pathname === b.pathname &&\n\t\ta.search === b.search &&\n\t\t!b.hash &&\n\t\t!b.username &&\n\t\t!b.password\n\t);\n}\n\nfunction withParams(uri: string, params: Record<string, string | undefined>): string {\n\tconst url = new URL(uri);\n\tfor (const [k, v] of Object.entries(params)) if (v !== undefined) url.searchParams.set(k, v);\n\treturn url.toString();\n}\n\nfunction derive(secret: string, info: string): Buffer {\n\treturn Buffer.from(hkdfSync('sha256', secret, '', info, 32));\n}\n\nfunction sign(key: Buffer, data: string): string {\n\treturn createHmac('sha256', key).update(data).digest('base64url');\n}\n\nfunction seal(key: Buffer, value: unknown): string {\n\tconst iv = randomBytes(12);\n\tconst cipher = createCipheriv('aes-256-gcm', key, iv);\n\tconst body = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]);\n\treturn Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url');\n}\n\nfunction open(key: Buffer, sealed: string): unknown {\n\ttry {\n\t\tconst raw = Buffer.from(sealed, 'base64url');\n\t\t// Without the length, a short code is checked against however many tag bytes it has.\n\t\tconst decipher = createDecipheriv('aes-256-gcm', key, raw.subarray(0, 12), {\n\t\t\tauthTagLength: 16\n\t\t});\n\t\tdecipher.setAuthTag(raw.subarray(12, 28));\n\t\tconst body = Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]);\n\t\treturn JSON.parse(body.toString('utf8'));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction b64(text: string): string {\n\treturn Buffer.from(text).toString('base64url');\n}\n\nfunction unb64(text: string): string {\n\treturn Buffer.from(text, 'base64url').toString('utf8');\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n\tconst x = Buffer.from(a);\n\tconst y = Buffer.from(b);\n\treturn x.length === y.length && timingSafeEqual(x, y);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,IAAa,eAAe;CAAC;CAAQ;CAAS;CAAU;AAAiB;;;;;;;AASzE,IAAa,2BAA2B,CAAC,QAAQ,OAAO;AAOxD,IAAM,qBAAkC;CACvC,UAAU;CACV,MAAM;CACN,cAAc,CAAC,2BAA2B;CAC1C,SAAS;CACT,QAAQ;EAAC;EAAQ;EAAU;CAAiB;AAC7C;AAEA,IAAa,WAAW;AAExB,IAAa,cAAc;AAC3B,IAAM,kBAAkB;AACxB,IAAM,oBAAoB;AAC1B,IAAM,cAAc;AAGpB,IAAM,sBAAsB;AAC5B,IAAM,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AACtD;AAEA,SAAS,UAAU,GAAW,GAAoB;CACjD,MAAM,IAAI,OAAO,KAAK,CAAC;CACvB,MAAM,IAAI,OAAO,KAAK,CAAC;CACvB,OAAO,EAAE,WAAW,EAAE,UAAU,gBAAgB,GAAG,CAAC;AACrD"}
1
+ {"version":3,"file":"oauth.js","names":["sign"],"sources":["../../../../server/src/oauth/index.ts"],"sourcesContent":["/**\n * OAuth 2.1 for MCP clients and the Grasshopper plugin, with this instance as\n * its own authorization server.\n *\n * The access token is an ordinary API token. The host mints it while the user is\n * signed in, at consent, through the same path as Team → API tokens; this\n * module seals the raw key into the authorization code and hands it over at the\n * token endpoint. So `/mcp` and `/api/v1` keep one credential type.\n *\n * Nothing here is stored. A registered client's id is its own signed metadata,\n * and a code is its own encrypted grant, bound to the issuing origin. The only\n * state is the set of redeemed codes, in the host's memory, so on several\n * replicas a code could be redeemed once per replica within its minute, and only\n * by whoever holds the PKCE verifier.\n */\n\nimport {\n\tcreateCipheriv,\n\tcreateDecipheriv,\n\tcreateHash,\n\tcreateHmac,\n\thkdfSync,\n\trandomBytes,\n\ttimingSafeEqual\n} from 'node:crypto';\n\n/** The scopes a grant can carry. Each maps to one org-wide API scope. */\nexport const OAUTH_SCOPES = ['read', 'solve', 'write', 'upload', 'create_projects'] as const;\nexport type OAuthScope = (typeof OAUTH_SCOPES)[number];\n\n/**\n * All a host may hand registered (DCR or CIMD) clients. Their name and redirects\n * are whatever the registrant chose, so `upload`, which puts code on the org's\n * Compute server, and `create_projects` aren't here. `write` is, but `write:all`\n * covers both at `/api/v1` and can delete projects and definitions, so it is\n * off by default. An allowlist: a new scope reaches registered clients only\n * once it is added here.\n */\nexport const REGISTERABLE_SCOPES = [\n\t'read',\n\t'solve',\n\t'write'\n] as const satisfies readonly OAuthScope[];\nexport type RegisteredClientScope = (typeof REGISTERABLE_SCOPES)[number];\n\n/** The default `registeredClientScopes`. */\nexport const REGISTERED_CLIENT_SCOPES = [\n\t'read',\n\t'solve'\n] as const satisfies readonly RegisteredClientScope[];\n\n/** The Grasshopper plugin's client id. Built in, so it needs no registration and works air-gapped. */\nexport const GRASSHOPPER_CLIENT_ID = 'selva-grasshopper';\n\n// Loopback on any port (RFC 8252 §7.3), but only this host and path: the code\n// can only ever reach a program on the user's own machine.\nconst GRASSHOPPER_CLIENT: OAuthClient = {\n\tclientId: GRASSHOPPER_CLIENT_ID,\n\tname: 'Selva for Grasshopper',\n\tredirectUris: ['http://127.0.0.1/callback'],\n\tbuiltIn: true,\n\tscopes: ['read', 'upload', 'create_projects']\n};\n\nexport const MCP_PATH = '/mcp';\n\nexport const CODE_TTL_MS = 60_000;\nconst CLIENT_NAME_MAX = 100;\nconst REDIRECT_URIS_MAX = 10;\nconst CIMD_TTL_MS = 60 * 60_000;\n// A failing metadata URL is not refetched for this long: each fetch is outbound\n// work an anonymous caller could otherwise trigger at will.\nconst CIMD_FAILURE_TTL_MS = 60_000;\nconst CIMD_CACHE_MAX = 500;\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nexport class OAuthError extends Error {\n\tconstructor(\n\t\t/** RFC 6749 / 7591 error code. */\n\t\treadonly error: string,\n\t\tdescription: string,\n\t\treadonly status = 400\n\t) {\n\t\tsuper(description);\n\t\tthis.name = 'OAuthError';\n\t}\n\n\ttoBody(): { error: string; error_description: string } {\n\t\treturn { error: this.error, error_description: this.message };\n\t}\n}\n\nexport interface OAuthClient {\n\tclientId: string;\n\t/** Shown on the consent page. Unverified for a registered client: whatever it claimed. */\n\tname: string;\n\tredirectUris: string[];\n\t/** Shipped with this server, so its name can be trusted. */\n\tbuiltIn: boolean;\n\t/** All this client can be granted, whatever it asks for. */\n\tscopes: readonly OAuthScope[];\n}\n\n/** A validated `/oauth/authorize` request, ready for the consent page. */\nexport interface AuthorizeRequest {\n\tclient: OAuthClient;\n\tredirectUri: string;\n\tstate?: string;\n\tcodeChallenge: string;\n\tscopes: OAuthScope[];\n\tresource: string;\n}\n\n/** What the host minted at consent. `secret` is the raw API key. */\nexport interface Grant {\n\ttokenId: string;\n\tsecret: string;\n\tscopes: OAuthScope[];\n\texpiresAt: string;\n}\n\nexport interface OAuthServerOptions {\n\t/** This instance's origin, e.g. `https://selva.example.com`. */\n\torigin: string;\n\t/** `SELVA_HMAC_KEY`. Signs client ids and seals codes. */\n\tsecret: string;\n\t/** The key before the last rotation: client ids and codes it made still verify. */\n\tpreviousSecret?: string;\n\t/**\n\t * All a DCR or CIMD client can be granted, from {@link REGISTERABLE_SCOPES}\n\t * and including `read`. Default {@link REGISTERED_CLIENT_SCOPES}. Serve the\n\t * server's discovery documents and pass its `registeredScopes` as the MCP\n\t * 401 challenge's scopes, so clients ask for this same list.\n\t */\n\tregisteredClientScopes?: readonly RegisteredClientScope[];\n\t/**\n\t * Fetches a Client ID Metadata Document. The URL comes from an unknown client,\n\t * so the host must guard it against SSRF. Without it, URL client ids are refused.\n\t */\n\tfetchClientMetadata?: (url: string) => Promise<unknown>;\n\t/**\n\t * Redeemed code hashes and their expiry. Pass one map for the process so a\n\t * rebuilt server (a new origin, a rotated secret) still refuses a replay.\n\t */\n\tredeemedCodes?: Map<string, number>;\n\t/** Called once a code is exchanged, with the token its grant carries. */\n\tonRedeemed?: (tokenId: string) => void;\n\tnow?: () => number;\n}\n\ninterface HttpResult {\n\tstatus: number;\n\tbody: Record<string, unknown>;\n}\n\n// ============================================================================\n// Discovery documents\n// ============================================================================\n\nexport function mcpResourceUrl(origin: string): string {\n\treturn origin + MCP_PATH;\n}\n\nexport function resourceMetadataUrl(origin: string): string {\n\treturn `${origin}/.well-known/oauth-protected-resource${MCP_PATH}`;\n}\n\n/**\n * RFC 9728. Claude uses only the first authorization server. `scopes` is what a\n * registered client may be granted; prefer the server's own method, which\n * passes its `registeredClientScopes`.\n */\nexport function protectedResourceMetadata(\n\torigin: string,\n\tscopes: readonly RegisteredClientScope[] = REGISTERED_CLIENT_SCOPES\n) {\n\treturn {\n\t\tresource: mcpResourceUrl(origin),\n\t\tauthorization_servers: [origin],\n\t\tscopes_supported: [...scopes],\n\t\tbearer_methods_supported: ['header']\n\t};\n}\n\n/**\n * RFC 8414. Claude picks Client ID Metadata Documents only when both\n * `client_id_metadata_document_supported` and the `none` auth method appear.\n * Advertises only scopes some client can be granted: a client that asks for one\n * it can never get re-authorizes in a loop. Prefer the server's own method.\n */\nexport function authorizationServerMetadata(\n\torigin: string,\n\tregisteredScopes: readonly RegisteredClientScope[] = REGISTERED_CLIENT_SCOPES\n) {\n\treturn {\n\t\tissuer: origin,\n\t\tauthorization_endpoint: `${origin}/oauth/authorize`,\n\t\ttoken_endpoint: `${origin}/oauth/token`,\n\t\tregistration_endpoint: `${origin}/oauth/register`,\n\t\tresponse_types_supported: ['code'],\n\t\tgrant_types_supported: ['authorization_code'],\n\t\tcode_challenge_methods_supported: ['S256'],\n\t\ttoken_endpoint_auth_methods_supported: ['none'],\n\t\tscopes_supported: OAUTH_SCOPES.filter(\n\t\t\t(s) =>\n\t\t\t\tGRASSHOPPER_CLIENT.scopes.includes(s) ||\n\t\t\t\t(registeredScopes as readonly OAuthScope[]).includes(s)\n\t\t),\n\t\tclient_id_metadata_document_supported: true,\n\t\tauthorization_response_iss_parameter_supported: true\n\t};\n}\n\n/**\n * The host's list, checked: a JS host or a cast gets past the type, and a list\n * without `read` would leave every consent page empty with a message blaming\n * the user's account.\n */\nfunction checkRegisteredScopes(scopes: readonly string[]): RegisteredClientScope[] {\n\tfor (const s of scopes) {\n\t\tif (!(REGISTERABLE_SCOPES as readonly string[]).includes(s)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`registeredClientScopes: \"${s}\" can't be granted to a registered client.`\n\t\t\t);\n\t\t}\n\t}\n\tif (!scopes.includes('read')) throw new TypeError('registeredClientScopes must include \"read\".');\n\treturn REGISTERABLE_SCOPES.filter((s) => scopes.includes(s));\n}\n\n// ============================================================================\n// Server\n// ============================================================================\n\nexport function createOAuthServer(options: OAuthServerOptions) {\n\tconst { origin } = options;\n\tconst now = options.now ?? Date.now;\n\tconst signKey = derive(options.secret, 'selva-oauth-client');\n\tconst codeKey = derive(options.secret, `selva-oauth-code:${origin}`);\n\tconst previous = options.previousSecret;\n\tconst previousSignKey = previous ? derive(previous, 'selva-oauth-client') : undefined;\n\tconst previousCodeKey = previous ? derive(previous, `selva-oauth-code:${origin}`) : undefined;\n\tconst redeemed = options.redeemedCodes ?? new Map<string, number>();\n\tconst registeredScopes = checkRegisteredScopes(\n\t\toptions.registeredClientScopes ?? REGISTERED_CLIENT_SCOPES\n\t);\n\tconst metadataCache = new Map<\n\t\tstring,\n\t\t{ at: number; client: OAuthClient } | { at: number; failure: OAuthError }\n\t>();\n\n\t// ==========================================================================\n\t// Clients\n\t// ==========================================================================\n\n\t/** RFC 7591. The client id carries the metadata, signed, so nothing is stored. */\n\tfunction register(input: unknown): HttpResult {\n\t\ttry {\n\t\t\tconst meta = (input ?? {}) as { client_name?: unknown; redirect_uris?: unknown };\n\t\t\tconst redirectUris = checkRedirectUris(meta.redirect_uris);\n\t\t\tconst name = typeof meta.client_name === 'string' ? meta.client_name.trim() : '';\n\t\t\tconst payload = b64(\n\t\t\t\tJSON.stringify({ n: name.slice(0, CLIENT_NAME_MAX), r: redirectUris, t: now() })\n\t\t\t);\n\t\t\tconst clientId = `dcr_${payload}.${sign(signKey, payload)}`;\n\t\t\treturn {\n\t\t\t\tstatus: 201,\n\t\t\t\tbody: {\n\t\t\t\t\tclient_id: clientId,\n\t\t\t\t\tclient_id_issued_at: Math.floor(now() / 1000),\n\t\t\t\t\tclient_name: name || undefined,\n\t\t\t\t\tredirect_uris: redirectUris,\n\t\t\t\t\tgrant_types: ['authorization_code'],\n\t\t\t\t\tresponse_types: ['code'],\n\t\t\t\t\ttoken_endpoint_auth_method: 'none'\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync function resolveClient(clientId: string): Promise<OAuthClient> {\n\t\tif (clientId === GRASSHOPPER_CLIENT_ID) return GRASSHOPPER_CLIENT;\n\t\tif (clientId.startsWith('dcr_')) return registeredClient(clientId);\n\t\tif (clientId.startsWith('https://')) return metadataClient(clientId);\n\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t}\n\n\tfunction registeredClient(clientId: string): OAuthClient {\n\t\tconst [payload, signature] = clientId.slice('dcr_'.length).split('.');\n\t\tconst signedBy = (key: Buffer | undefined) =>\n\t\t\tkey !== undefined && safeEqual(signature, sign(key, payload));\n\t\tif (!payload || !signature || !(signedBy(signKey) || signedBy(previousSignKey))) {\n\t\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t\t}\n\t\tconst meta = JSON.parse(unb64(payload)) as { n: string; r: string[] };\n\t\treturn {\n\t\t\tclientId,\n\t\t\tname: meta.n || 'An MCP client',\n\t\t\tredirectUris: meta.r,\n\t\t\tbuiltIn: false,\n\t\t\tscopes: registeredScopes\n\t\t};\n\t}\n\n\tasync function metadataClient(url: string): Promise<OAuthClient> {\n\t\tconst cached = metadataCache.get(url);\n\t\tif (cached) {\n\t\t\tif ('client' in cached && now() - cached.at < CIMD_TTL_MS) return cached.client;\n\t\t\tif ('failure' in cached && now() - cached.at < CIMD_FAILURE_TTL_MS) throw cached.failure;\n\t\t}\n\t\tif (!options.fetchClientMetadata) {\n\t\t\tthrow new OAuthError('invalid_client', 'This server does not accept URL client ids.');\n\t\t}\n\t\ttry {\n\t\t\tconst client = await readMetadata(url, options.fetchClientMetadata, registeredScopes);\n\t\t\tremember(url, { at: now(), client });\n\t\t\treturn client;\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof OAuthError)) throw err;\n\t\t\tremember(url, { at: now(), failure: err });\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction remember(url: string, entry: Parameters<typeof metadataCache.set>[1]) {\n\t\tif (metadataCache.size >= CIMD_CACHE_MAX) {\n\t\t\tmetadataCache.delete(metadataCache.keys().next().value!);\n\t\t}\n\t\tmetadataCache.set(url, entry);\n\t}\n\n\t// ==========================================================================\n\t// Authorization\n\t// ==========================================================================\n\n\t/**\n\t * Validates the query `/oauth/authorize` arrives with. An `OAuthError` from a\n\t * bad client or redirect URI must be shown, not redirected: the redirect target\n\t * is exactly what can't be trusted.\n\t */\n\tasync function parseAuthorizeRequest(query: URLSearchParams): Promise<AuthorizeRequest> {\n\t\tconst client = await resolveClient(query.get('client_id') ?? '');\n\t\tconst redirectUri = query.get('redirect_uri') ?? '';\n\t\tif (!client.redirectUris.some((r) => redirectMatches(r, redirectUri))) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_request',\n\t\t\t\t'The redirect URI is not registered for this client.'\n\t\t\t);\n\t\t}\n\t\tif (query.get('response_type') !== 'code') {\n\t\t\tthrow new OAuthError('unsupported_response_type', 'Only response_type=code is supported.');\n\t\t}\n\t\tconst codeChallenge = query.get('code_challenge') ?? '';\n\t\tif (!codeChallenge || query.get('code_challenge_method') !== 'S256') {\n\t\t\tthrow new OAuthError('invalid_request', 'PKCE with code_challenge_method=S256 is required.');\n\t\t}\n\t\tconst resource = query.get('resource') ?? mcpResourceUrl(origin);\n\t\tif (!isThisResource(resource)) {\n\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t}\n\t\treturn {\n\t\t\tclient,\n\t\t\tredirectUri,\n\t\t\tstate: query.get('state') ?? undefined,\n\t\t\tcodeChallenge,\n\t\t\tscopes: parseScopes(query.get('scope'), client.scopes),\n\t\t\tresource\n\t\t};\n\t}\n\n\t/** Where to send the browser after consent: the client's redirect URI with a code. */\n\tfunction approve(request: AuthorizeRequest, grant: Grant): string {\n\t\tconst code = seal(codeKey, {\n\t\t\tc: request.client.clientId,\n\t\t\tr: request.redirectUri,\n\t\t\tp: request.codeChallenge,\n\t\t\tx: now() + CODE_TTL_MS,\n\t\t\tg: grant\n\t\t});\n\t\treturn withParams(request.redirectUri, { code, state: request.state, iss: origin });\n\t}\n\n\tfunction deny(request: AuthorizeRequest): string {\n\t\treturn withParams(request.redirectUri, {\n\t\t\terror: 'access_denied',\n\t\t\tstate: request.state,\n\t\t\tiss: origin\n\t\t});\n\t}\n\n\t// ==========================================================================\n\t// Token endpoint\n\t// ==========================================================================\n\n\tfunction exchange(form: URLSearchParams): HttpResult {\n\t\ttry {\n\t\t\tif (form.get('grant_type') !== 'authorization_code') {\n\t\t\t\tthrow new OAuthError('unsupported_grant_type', 'Only authorization_code is supported.');\n\t\t\t}\n\t\t\tconst code = form.get('code') ?? '';\n\t\t\tconst sealed = (open(codeKey, code) ??\n\t\t\t\t(previousCodeKey ? open(previousCodeKey, code) : null)) as {\n\t\t\t\tc: string;\n\t\t\t\tr: string;\n\t\t\t\tp: string;\n\t\t\t\tx: number;\n\t\t\t\tg: Grant;\n\t\t\t} | null;\n\t\t\tif (!sealed || sealed.x < now()) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code is invalid or expired.');\n\t\t\t}\n\t\t\tif (sealed.c !== form.get('client_id') || sealed.r !== form.get('redirect_uri')) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was issued to another client.');\n\t\t\t}\n\t\t\tconst verifier = form.get('code_verifier') ?? '';\n\t\t\tif (!safeEqual(createHash('sha256').update(verifier).digest('base64url'), sealed.p)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code_verifier does not match.');\n\t\t\t}\n\t\t\tconst resource = form.get('resource');\n\t\t\tif (resource !== null && !isThisResource(resource)) {\n\t\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t\t}\n\t\t\tif (!markRedeemed(code, sealed.x)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was already used.');\n\t\t\t}\n\t\t\tconst { g } = sealed;\n\t\t\toptions.onRedeemed?.(g.tokenId);\n\t\t\treturn {\n\t\t\t\tstatus: 200,\n\t\t\t\tbody: {\n\t\t\t\t\taccess_token: g.secret,\n\t\t\t\t\ttoken_type: 'Bearer',\n\t\t\t\t\texpires_in: Math.max(0, Math.floor((Date.parse(g.expiresAt) - now()) / 1000)),\n\t\t\t\t\tscope: g.scopes.join(' ')\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction markRedeemed(code: string, expiresAt: number): boolean {\n\t\tconst t = now();\n\t\tfor (const [k, x] of redeemed) if (x < t) redeemed.delete(k);\n\t\tconst id = createHash('sha256').update(code).digest('base64url');\n\t\tif (redeemed.has(id)) return false;\n\t\tredeemed.set(id, expiresAt);\n\t\treturn true;\n\t}\n\n\tfunction isThisResource(resource: string): boolean {\n\t\tconst r = resource.replace(/\\/$/, '');\n\t\treturn r === origin || r === mcpResourceUrl(origin);\n\t}\n\n\treturn {\n\t\tregister,\n\t\tresolveClient,\n\t\tparseAuthorizeRequest,\n\t\tapprove,\n\t\tdeny,\n\t\texchange,\n\t\t/** All a registered client can be granted: the MCP 401 challenge's scopes. */\n\t\tregisteredScopes: registeredScopes as readonly RegisteredClientScope[],\n\t\tprotectedResourceMetadata: () => protectedResourceMetadata(origin, registeredScopes),\n\t\tauthorizationServerMetadata: () => authorizationServerMetadata(origin, registeredScopes)\n\t};\n}\n\nexport type OAuthServer = ReturnType<typeof createOAuthServer>;\n\n/** OAuth scopes to the API scopes a minted token gets. */\nexport function apiScopesFor(scopes: readonly OAuthScope[]): string[] {\n\treturn scopes.map((s) => `${s}:all`);\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nasync function readMetadata(\n\turl: string,\n\tfetchClientMetadata: (url: string) => Promise<unknown>,\n\tscopes: readonly OAuthScope[]\n): Promise<OAuthClient> {\n\tlet doc: { client_id?: unknown; client_name?: unknown; redirect_uris?: unknown };\n\ttry {\n\t\tdoc = (await fetchClientMetadata(url)) as typeof doc;\n\t} catch {\n\t\tthrow new OAuthError('invalid_client', 'The client metadata document could not be read.');\n\t}\n\tif (doc?.client_id !== url) {\n\t\tthrow new OAuthError('invalid_client', 'The metadata document names a different client_id.');\n\t}\n\treturn {\n\t\tclientId: url,\n\t\tname:\n\t\t\ttypeof doc.client_name === 'string' && doc.client_name.trim()\n\t\t\t\t? doc.client_name.trim().slice(0, CLIENT_NAME_MAX)\n\t\t\t\t: new URL(url).host,\n\t\tredirectUris: checkRedirectUris(doc.redirect_uris),\n\t\tbuiltIn: false,\n\t\tscopes\n\t};\n}\n\n/**\n * What the request asks for, within what its client may have. A scope outside\n * that is dropped, not refused, so a client that asks for every advertised\n * scope still signs in with what it may have. No `scope` at all means all of\n * them. Asking only for scopes it may not have gets `read`, never more than it\n * asked for. `read` rides along with `solve` and `write`, which the consent\n * page offers as \"read and run solves\" and \"read and change\".\n */\nfunction parseScopes(raw: string | null, allowed: readonly OAuthScope[]): OAuthScope[] {\n\tconst requested = (raw ?? '').split(' ').filter(Boolean);\n\tif (!requested.length) return [...allowed];\n\tconst asked = requested.filter((s): s is OAuthScope =>\n\t\t(allowed as readonly string[]).includes(s)\n\t);\n\tif (!asked.length) return allowed.includes('read') ? ['read'] : [];\n\tconst impliesRead = asked.includes('solve') || asked.includes('write');\n\treturn allowed.filter((s) => asked.includes(s) || (s === 'read' && impliesRead));\n}\n\n/** One access level a consent page offers, and the scopes approving it grants. */\nexport interface ConsentChoice {\n\taccess: 'read' | 'solve' | 'write' | 'write_and_solve' | 'upload';\n\tscopes: OAuthScope[];\n}\n\n/**\n * The access levels a consent page offers for a request: `read` first, all it\n * asked for last. The user may narrow what the client asked for, never widen\n * it. `write` is offered with and without `solve`, so change access needn't\n * spend compute budget, and a host policy that allows one can still grant it.\n * An upload request is offered as asked: narrowing it to read would leave the\n * client unable to do the one thing it signed in for.\n */\nexport function consentChoices(scopes: readonly OAuthScope[]): ConsentChoice[] {\n\tif (!scopes.length) return [];\n\tif (scopes.includes('upload')) return [{ access: 'upload', scopes: [...scopes] }];\n\tconst solve = scopes.includes('solve');\n\tconst write = scopes.includes('write');\n\tconst choices: ConsentChoice[] = [{ access: 'read', scopes: ['read'] }];\n\tif (solve) choices.push({ access: 'solve', scopes: ['read', 'solve'] });\n\tif (write) choices.push({ access: 'write', scopes: ['read', 'write'] });\n\tif (solve && write) {\n\t\tchoices.push({ access: 'write_and_solve', scopes: ['read', 'solve', 'write'] });\n\t}\n\treturn choices;\n}\n\nfunction checkRedirectUris(value: unknown): string[] {\n\tif (!Array.isArray(value) || !value.length || value.length > REDIRECT_URIS_MAX) {\n\t\tthrow new OAuthError('invalid_redirect_uri', 'Give between 1 and 10 redirect_uris.');\n\t}\n\tfor (const uri of value) {\n\t\tif (typeof uri !== 'string' || !isAllowedRedirect(uri)) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_redirect_uri',\n\t\t\t\t'Redirect URIs must be https, or http on a loopback address.'\n\t\t\t);\n\t\t}\n\t}\n\treturn value as string[];\n}\n\nfunction isAllowedRedirect(uri: string): boolean {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(uri);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (url.hash) return false;\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\n/** A redirect to a program on the user's own machine, which any local process can claim. */\nexport function isLoopbackRedirect(uri: string): boolean {\n\ttry {\n\t\treturn LOOPBACK_HOSTS.has(new URL(uri).hostname);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Exact, except a loopback redirect matches on any port (RFC 8252 §7.3). */\nexport function redirectMatches(registered: string, requested: string): boolean {\n\tif (registered === requested) return true;\n\tlet a: URL, b: URL;\n\ttry {\n\t\ta = new URL(registered);\n\t\tb = new URL(requested);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn (\n\t\ta.protocol === 'http:' &&\n\t\tb.protocol === 'http:' &&\n\t\tLOOPBACK_HOSTS.has(a.hostname) &&\n\t\ta.hostname === b.hostname &&\n\t\ta.pathname === b.pathname &&\n\t\ta.search === b.search &&\n\t\t!b.hash &&\n\t\t!b.username &&\n\t\t!b.password\n\t);\n}\n\nfunction withParams(uri: string, params: Record<string, string | undefined>): string {\n\tconst url = new URL(uri);\n\tfor (const [k, v] of Object.entries(params)) if (v !== undefined) url.searchParams.set(k, v);\n\treturn url.toString();\n}\n\nfunction derive(secret: string, info: string): Buffer {\n\treturn Buffer.from(hkdfSync('sha256', secret, '', info, 32));\n}\n\nfunction sign(key: Buffer, data: string): string {\n\treturn createHmac('sha256', key).update(data).digest('base64url');\n}\n\nfunction seal(key: Buffer, value: unknown): string {\n\tconst iv = randomBytes(12);\n\tconst cipher = createCipheriv('aes-256-gcm', key, iv);\n\tconst body = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]);\n\treturn Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url');\n}\n\nfunction open(key: Buffer, sealed: string): unknown {\n\ttry {\n\t\tconst raw = Buffer.from(sealed, 'base64url');\n\t\t// Without the length, a short code is checked against however many tag bytes it has.\n\t\tconst decipher = createDecipheriv('aes-256-gcm', key, raw.subarray(0, 12), {\n\t\t\tauthTagLength: 16\n\t\t});\n\t\tdecipher.setAuthTag(raw.subarray(12, 28));\n\t\tconst body = Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]);\n\t\treturn JSON.parse(body.toString('utf8'));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction b64(text: string): string {\n\treturn Buffer.from(text).toString('base64url');\n}\n\nfunction unb64(text: string): string {\n\treturn Buffer.from(text, 'base64url').toString('utf8');\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n\tconst x = Buffer.from(a);\n\tconst y = Buffer.from(b);\n\treturn x.length === y.length && timingSafeEqual(x, y);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,IAAa,eAAe;CAAC;CAAQ;CAAS;CAAS;CAAU;AAAiB;;;;;;;;;AAWlF,IAAa,sBAAsB;CAClC;CACA;CACA;AACD;;AAIA,IAAa,2BAA2B,CACvC,QACA,OACD;AA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
- // ../solve/dist/outcome-DNrffAXp.js
1
+ // ../solve/dist/outcome-D28FgvFK.js
2
2
  /**
3
3
  * The solve contract — what a solve returns and what a caller supplies to run one.
4
4
  *
@@ -105,7 +105,7 @@ function decodeDiagnostic(entry) {
105
105
  ...d.isGate === true ? { isGate: true } : {}
106
106
  };
107
107
  }
108
- function normalizeOutcome(entries, blocked, aborted) {
108
+ function normalizeOutcome(entries, blocked, aborted, deferred) {
109
109
  const seen = /* @__PURE__ */ new Set();
110
110
  const diagnostics = [];
111
111
  for (const entry of entries) {
@@ -119,7 +119,8 @@ function normalizeOutcome(entries, blocked, aborted) {
119
119
  return {
120
120
  diagnostics,
121
121
  blocked: blocked || aborted,
122
- aborted
122
+ aborted,
123
+ ...deferred && deferred.length > 0 ? { deferred } : {}
123
124
  };
124
125
  }
125
126
  /**
@@ -130,11 +131,12 @@ function normalizeOutcome(entries, blocked, aborted) {
130
131
  */
131
132
  function decodeOutcome(wire) {
132
133
  if (!wire || typeof wire !== "object") return null;
133
- const { diagnostics, blocked, aborted } = wire;
134
+ const { diagnostics, blocked, aborted, deferred } = wire;
134
135
  const hasList = Array.isArray(diagnostics);
135
136
  if (!hasList && blocked === void 0 && aborted === void 0) return null;
136
137
  const isTrue = (flag) => flag === true || flag === "true";
137
- return normalizeOutcome(hasList ? diagnostics : [], isTrue(blocked), isTrue(aborted));
138
+ const deferredIds = Array.isArray(deferred) ? deferred.filter((id) => typeof id === "string" && id !== "") : void 0;
139
+ return normalizeOutcome(hasList ? diagnostics : [], isTrue(blocked), isTrue(aborted), deferredIds);
138
140
  }
139
141
  /** The legacy verdict, read from Compute's flattened `errors`/`warnings` and their markers. */
140
142
  function outcomeFromComputeMessages(errors, warnings) {
@@ -159,9 +161,10 @@ function finalizeResult(partial, outcome) {
159
161
  diagnostics: outcome.diagnostics,
160
162
  blocked: outcome.blocked,
161
163
  aborted: outcome.aborted,
164
+ ...outcome.deferred && !rejected ? { deferred: outcome.deferred } : {},
162
165
  ...partial.source !== void 0 && !rejected ? { source: partial.source } : {}
163
166
  };
164
167
  }
165
168
  export { outcomeFromComputeMessages as i, decodeOutcome as n, finalizeResult as r, decodeDiagnostic as t };
166
169
 
167
- //# sourceMappingURL=outcome-DNrffAXp.js.map
170
+ //# sourceMappingURL=outcome-D28FgvFK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outcome-D28FgvFK.js","names":[],"sources":["../../../../solve/dist/outcome-D28FgvFK.js"],"sourcesContent":["// src/shared/solve-fn.ts\n/**\n* The solve contract — what a solve returns and what a caller supplies to run one.\n*\n* Lives in `shared/` because both halves of the package speak it: `client/` calls a `SolveFn` and\n* stores its `SolveResult`; `server/` produces the payload one is built from.\n*/\n/**\n* Marker the Grasshopper Message component prepends to a blocking error.\n*\n* Rhino.Compute flattens runtime messages to plain strings with no component attribution, so\n* this is the only way that path can tell a deliberate block from any other solve error. The\n* local WebSocket path carries `isGate` structurally and does not need it — but the component\n* writes the marker unconditionally, because the same definition runs on both.\n*\n* Changing this string breaks blocking on deployed Selva for every already-published\n* definition, since the text is baked into the .gh file's solve output, not the plugin.\n*/\nconst SOLVE_BLOCKED_MARKER = \"[Selva:blocked]\";\n/**\n* Marker the Message component prepends to a remark or warning — the non-blocking levels.\n*\n* Same reason as `SOLVE_BLOCKED_MARKER`: on Rhino.Compute nothing structural survives, and the\n* UI has to tell a message the author chose to write from an incidental Grasshopper warning.\n* Definitions saved before this existed lack it, so the reader falls back to the component name.\n*/\nconst SOLVE_AUTHORED_MARKER = \"[Selva:msg]\";\n/**\n* Marker for an authored message whose author chose Notify = Log.\n*\n* Still theirs — it keeps its attribution and its place in the message list — but it does not\n* interrupt. Errors never carry it: their result is withheld, so they always interrupt.\n*/\nconst SOLVE_LOG_ONLY_MARKER = \"[Selva:log]\";\n// src/shared/compute-diagnostics.ts\n/**\n* Compute's per-message attribution suffix. Anchored to the end and requiring the parenthesised\n* GUID, so an author who writes `component \"x\"` mid-sentence keeps their text intact.\n*/\nconst ATTRIBUTION = /:\\s*component\\s+\"([^\"]*)\"\\s*\\(([0-9a-fA-F-]{36}|\\.\\.\\.)\\)\\s*$/;\n/** The Selva Message component's own name, as `LogRuntimeMessages` reports it. */\nconst MESSAGE_COMPONENT_NAME = \"Message\";\n/**\n* Splits one Compute message string into the author's text and its attribution.\n*\n* Leaves the text alone when the suffix is absent — an exception thrown by a script component\n* has no attribution and must not be truncated on a guess.\n*/\nfunction parseComputeMessage(raw) {\n\tconst blocked = raw.includes(SOLVE_BLOCKED_MARKER);\n\tconst logOnly = !blocked && raw.includes(\"[Selva:log]\");\n\tconst authored = blocked || logOnly || raw.includes(\"[Selva:msg]\");\n\tlet message = raw;\n\tlet source;\n\tconst attribution = ATTRIBUTION.exec(message);\n\tif (attribution) {\n\t\tsource = attribution[1] || void 0;\n\t\tmessage = message.slice(0, attribution.index);\n\t}\n\tif (authored) message = message.replace(SOLVE_BLOCKED_MARKER, \"\").replace(SOLVE_AUTHORED_MARKER, \"\").replace(SOLVE_LOG_ONLY_MARKER, \"\").replace(/^\\s*\\d+\\.\\s*Solution exception:\\s*/, \"\");\n\treturn {\n\t\tmessage: message.replace(/\\s{2,}/g, \" \").trim(),\n\t\tsource,\n\t\tblocked,\n\t\tauthored,\n\t\tlogOnly\n\t};\n}\n/**\n* Rebuilds structured diagnostics from Compute's `errors`/`warnings` arrays.\n*\n* `isGate` comes from the marker the component writes. The component-name fallback is for\n* definitions saved before the non-blocking marker existed; `obj.Name` is the component's type\n* name, not its nickname, so renaming one on the canvas cannot change how it behaves.\n*/\nfunction parseComputeDiagnostics(errors, warnings) {\n\tconst build = (raw, level) => {\n\t\tconst { message, source, authored, logOnly } = parseComputeMessage(raw);\n\t\tconst isGate = (authored || source === MESSAGE_COMPONENT_NAME) && !logOnly;\n\t\treturn {\n\t\t\tlevel,\n\t\t\tmessage,\n\t\t\t...source ? { source } : {},\n\t\t\t...isGate ? { isGate } : {}\n\t\t};\n\t};\n\treturn [...errors.map((raw) => build(raw, \"error\")), ...warnings.map((raw) => build(raw, \"warning\"))];\n}\n// src/shared/outcome.ts\nfunction isLevel(value) {\n\treturn value === \"error\" || value === \"warning\" || value === \"remark\";\n}\n/**\n* One wire diagnostic, normalized: an unknown level reads as a remark, text is trimmed, and\n* `source`/`isGate` are omitted rather than null or false. Null when it carries no message.\n*/\nfunction decodeDiagnostic(entry) {\n\tif (!entry || typeof entry !== \"object\") return null;\n\tconst d = entry;\n\tconst message = typeof d.message === \"string\" ? d.message.trim() : \"\";\n\tif (!message) return null;\n\tconst source = typeof d.source === \"string\" && d.source ? d.source : void 0;\n\treturn {\n\t\tlevel: isLevel(d.level) ? d.level : \"remark\",\n\t\tmessage,\n\t\t...source ? { source } : {},\n\t\t...d.isGate === true ? { isGate: true } : {}\n\t};\n}\nfunction normalizeOutcome(entries, blocked, aborted, deferred) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst diagnostics = [];\n\tfor (const entry of entries) {\n\t\tconst d = decodeDiagnostic(entry);\n\t\tif (!d) continue;\n\t\tconst key = `${d.level}\\u0000${d.message}\\u0000${d.source ?? \"\"}\\u0000${d.isGate === true}`;\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tdiagnostics.push(d);\n\t}\n\treturn {\n\t\tdiagnostics,\n\t\tblocked: blocked || aborted,\n\t\taborted,\n\t\t...deferred && deferred.length > 0 ? { deferred } : {}\n\t};\n}\n/**\n* Normalizes a wire outcome with `decodeDiagnostic`, dropping exact repeats, so the same verdict\n* decodes to the same object from either transport. Null when `wire` is not an outcome at all;\n* the caller then falls back. A verdict without a diagnostic list still counts: reading a refusal\n* as \"no outcome\" would let the solve through.\n*/\nfunction decodeOutcome(wire) {\n\tif (!wire || typeof wire !== \"object\") return null;\n\tconst { diagnostics, blocked, aborted, deferred } = wire;\n\tconst hasList = Array.isArray(diagnostics);\n\tif (!hasList && blocked === void 0 && aborted === void 0) return null;\n\tconst isTrue = (flag) => flag === true || flag === \"true\";\n\tconst deferredIds = Array.isArray(deferred) ? deferred.filter((id) => typeof id === \"string\" && id !== \"\") : void 0;\n\treturn normalizeOutcome(hasList ? diagnostics : [], isTrue(blocked), isTrue(aborted), deferredIds);\n}\n/** The legacy verdict, read from Compute's flattened `errors`/`warnings` and their markers. */\nfunction outcomeFromComputeMessages(errors, warnings) {\n\tconst strings = (list) => list.filter((m) => typeof m === \"string\");\n\tconst errorText = strings(errors);\n\treturn normalizeOutcome(parseComputeDiagnostics(errorText, strings(warnings)), errorText.some((e) => e.includes(SOLVE_BLOCKED_MARKER)), false);\n}\n/**\n* Builds the result a driver reports. A blocked or aborted outcome is \"no result\" whatever the\n* transport sent along: no outputs, no `source` (it holds the withheld outputs), and an empty mesh\n* list so the viewer clears. `errors` and `warnings` are derived from the diagnostics for hosts\n* that only want text.\n*/\nfunction finalizeResult(partial, outcome) {\n\tconst rejected = outcome.blocked || outcome.aborted;\n\tconst meshes = rejected ? [] : partial.meshes;\n\treturn {\n\t\toutputs: rejected ? {} : partial.outputs,\n\t\t...meshes !== void 0 ? { meshes } : {},\n\t\terrors: outcome.diagnostics.filter((d) => d.level === \"error\").map((d) => d.message),\n\t\twarnings: outcome.diagnostics.filter((d) => d.level === \"warning\").map((d) => d.message),\n\t\tdiagnostics: outcome.diagnostics,\n\t\tblocked: outcome.blocked,\n\t\taborted: outcome.aborted,\n\t\t...outcome.deferred && !rejected ? { deferred: outcome.deferred } : {},\n\t\t...partial.source !== void 0 && !rejected ? { source: partial.source } : {}\n\t};\n}\nexport { outcomeFromComputeMessages as i, decodeOutcome as n, finalizeResult as r, decodeDiagnostic as t };\n\n//# sourceMappingURL=outcome-D28FgvFK.js.map"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAM,uBAAuB;;;;;;;;AAQ7B,IAAM,wBAAwB;;;;;;;AAO9B,IAAM,wBAAwB;;;;;AAM9B,IAAM,cAAc;;AAEpB,IAAM,yBAAyB;;;;;;;AAO/B,SAAS,oBAAoB,KAAK;CACjC,MAAM,UAAU,IAAI,SAAS,oBAA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D,MAAM,WAAW,SAAS,KAAK,QAAQ,MAAM,OAAO,MAAM,QAAQ;CAClE,MAAM,YAAY,QAAQ,MAAM;CAChC,OAAO,iBAAiB,wBAAwB,WAAW,QAAQ,QAAQ,CAAC,GAAG,UAAU,MAAM,MAAM,EAAE,SAAS,oBAAoB,CAAC,GAAG,KAAK;AAC9I;;;;;;;AAOA,SAAS,eAAe,SAAS,SAAS;CACzC,MAAM,WAAW,QAAQ,WAAW,QAAQ;CAC5C,MAAM,SAAS,WAAW,CAAC,IAAI,QAAQ;CACvC,OAAO;EACN,SAAS,WAAW,CAAC,IAAI,QAAQ;EACjC,GAAG,WAAW,KAAK,IAAI,EAAE,OAAO,IAAI,CAAC;EACrC,QAAQ,QAAQ,YAAY,QAAQ,MAAM,EAAE,UAAU,OAAO,CAAC,CAAC,KAAK,MAAM,EAAE,OAAO;EACnF,UAAU,QAAQ,YAAY,QAAQ,MAAM,EAAE,UAAU,SAAS,CAAC,CAAC,KAAK,MAAM,EAAE,OAAO;EACvF,aAAa,QAAQ;EACrB,SAAS,QAAQ;EACjB,SAAS,QAAQ;EACjB,GAAG,QAAQ,YAAY,CAAC,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;EACrE,GAAG,QAAQ,WAAW,KAAK,KAAK,CAAC,WAAW,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;CAC3E;AACD"}
@@ -1,6 +1,6 @@
1
1
  var package_default = {
2
2
  name: "@selvajs/selva",
3
- version: "4.20.1-beta.5",
3
+ version: "4.21.0-beta.7",
4
4
  description: "Selva — self-contained Grasshopper-driven web app. Install, configure via .env, deploy.",
5
5
  license: "MIT",
6
6
  author: "VektorNode",
@@ -1 +1 @@
1
- {"version":3,"file":"package.js","names":[],"sources":["../../../package.json"],"sourcesContent":["{\n\t\"name\": \"@selvajs/selva\",\n\t\"version\": \"4.20.1-beta.5\",\n\t\"description\": \"Selva — self-contained Grasshopper-driven web app. Install, configure via .env, deploy.\",\n\t\"license\": \"MIT\",\n\t\"author\": \"VektorNode\",\n\t\"homepage\": \"https://selva.dev\",\n\t\"bugs\": \"https://github.com/VektorNode/selva/issues\",\n\t\"keywords\": [\n\t\t\"grasshopper\",\n\t\t\"rhino\",\n\t\t\"rhino-compute\",\n\t\t\"parametric-design\",\n\t\t\"web-app\",\n\t\t\"sveltekit\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/VektorNode/selva.git\",\n\t\t\"directory\": \"packages/selva\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./build/index.js\",\n\t\"files\": [\n\t\t\"build\",\n\t\t\"templates\"\n\t],\n\t\"engines\": {\n\t\t\"node\": \">=24.0.0\"\n\t},\n\t\"scripts\": {\n\t\t\"dev\": \"vite dev\",\n\t\t\"dev:lan\": \"vite dev --host\",\n\t\t\"build\": \"rimraf build && vite build && node ./scripts/generate-templates.js && node ./scripts/write-runtime-meta.js\",\n\t\t\"preview\": \"vite preview\",\n\t\t\"start\": \"node build/index.js\",\n\t\t\"clean\": \"rimraf build templates\",\n\t\t\"prepare\": \"svelte-kit sync || echo ''\",\n\t\t\"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n\t\t\"test\": \"vitest run\",\n\t\t\"test:watch\": \"vitest\",\n\t\t\"openapi:generate\": \"node scripts/generate-openapi.js\",\n\t\t\"test:e2e\": \"playwright test\",\n\t\t\"lint\": \"eslint .\",\n\t\t\"lint:types\": \"eslint . --config eslint.typed.config.js\",\n\t\t\"generate:cli-config\": \"node scripts/generate-cli-config.js\"\n\t},\n\t\"dependencies\": {\n\t\t\"@lucide/svelte\": \"catalog:\",\n\t\t\"@supabase/supabase-js\": \"catalog:\",\n\t\t\"@sveltejs/kit\": \"catalog:\",\n\t\t\"bits-ui\": \"catalog:\",\n\t\t\"clsx\": \"catalog:\",\n\t\t\"mode-watcher\": \"catalog:\",\n\t\t\"nodemailer\": \"catalog:\",\n\t\t\"pino\": \"^10.4.0\",\n\t\t\"rhino3dm\": \"catalog:\",\n\t\t\"sharp\": \"catalog:\",\n\t\t\"tailwind-merge\": \"catalog:\",\n\t\t\"tailwind-variants\": \"catalog:\",\n\t\t\"three\": \"catalog:\",\n\t\t\"zod\": \"catalog:\"\n\t},\n\t\"optionalDependencies\": {\n\t\t\"@sentry/node\": \"^11.10.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@playwright/test\": \"catalog:\",\n\t\t\"@selvajs/compute\": \"workspace:*\",\n\t\t\"@selvajs/config\": \"workspace:*\",\n\t\t\"@selvajs/header-auth-provider\": \"workspace:*\",\n\t\t\"@selvajs/local-provider\": \"workspace:*\",\n\t\t\"@selvajs/mcp\": \"workspace:*\",\n\t\t\"@selvajs/notifications\": \"workspace:*\",\n\t\t\"@selvajs/platform\": \"workspace:*\",\n\t\t\"@selvajs/schemas\": \"workspace:*\",\n\t\t\"@selvajs/server\": \"workspace:*\",\n\t\t\"@selvajs/solve\": \"workspace:*\",\n\t\t\"@selvajs/supabase-provider\": \"workspace:*\",\n\t\t\"@selvajs/ui\": \"workspace:*\",\n\t\t\"@selvajs/visualization\": \"workspace:*\",\n\t\t\"@sveltejs/adapter-node\": \"catalog:\",\n\t\t\"@types/nodemailer\": \"catalog:\",\n\t\t\"@types/three\": \"catalog:\",\n\t\t\"rimraf\": \"catalog:\",\n\t\t\"tw-animate-css\": \"catalog:\",\n\t\t\"vitest\": \"catalog:\"\n\t},\n\t\"imports\": {\n\t\t\"#lib/*\": \"./src/lib/*\"\n\t}\n}\n"],"mappings":""}
1
+ {"version":3,"file":"package.js","names":[],"sources":["../../../package.json"],"sourcesContent":["{\n\t\"name\": \"@selvajs/selva\",\n\t\"version\": \"4.21.0-beta.7\",\n\t\"description\": \"Selva — self-contained Grasshopper-driven web app. Install, configure via .env, deploy.\",\n\t\"license\": \"MIT\",\n\t\"author\": \"VektorNode\",\n\t\"homepage\": \"https://selva.dev\",\n\t\"bugs\": \"https://github.com/VektorNode/selva/issues\",\n\t\"keywords\": [\n\t\t\"grasshopper\",\n\t\t\"rhino\",\n\t\t\"rhino-compute\",\n\t\t\"parametric-design\",\n\t\t\"web-app\",\n\t\t\"sveltekit\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/VektorNode/selva.git\",\n\t\t\"directory\": \"packages/selva\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./build/index.js\",\n\t\"files\": [\n\t\t\"build\",\n\t\t\"templates\"\n\t],\n\t\"engines\": {\n\t\t\"node\": \">=24.0.0\"\n\t},\n\t\"scripts\": {\n\t\t\"dev\": \"vite dev\",\n\t\t\"dev:lan\": \"vite dev --host\",\n\t\t\"build\": \"rimraf build && vite build && node ./scripts/generate-templates.js && node ./scripts/write-runtime-meta.js\",\n\t\t\"preview\": \"vite preview\",\n\t\t\"start\": \"node build/index.js\",\n\t\t\"clean\": \"rimraf build templates\",\n\t\t\"prepare\": \"svelte-kit sync || echo ''\",\n\t\t\"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n\t\t\"test\": \"vitest run\",\n\t\t\"test:watch\": \"vitest\",\n\t\t\"openapi:generate\": \"node scripts/generate-openapi.js\",\n\t\t\"test:e2e\": \"playwright test\",\n\t\t\"lint\": \"eslint .\",\n\t\t\"lint:types\": \"eslint . --config eslint.typed.config.js\",\n\t\t\"generate:cli-config\": \"node scripts/generate-cli-config.js\"\n\t},\n\t\"dependencies\": {\n\t\t\"@lucide/svelte\": \"catalog:\",\n\t\t\"@supabase/supabase-js\": \"catalog:\",\n\t\t\"@sveltejs/kit\": \"catalog:\",\n\t\t\"bits-ui\": \"catalog:\",\n\t\t\"clsx\": \"catalog:\",\n\t\t\"mode-watcher\": \"catalog:\",\n\t\t\"nodemailer\": \"catalog:\",\n\t\t\"pino\": \"^10.4.0\",\n\t\t\"rhino3dm\": \"catalog:\",\n\t\t\"sharp\": \"catalog:\",\n\t\t\"tailwind-merge\": \"catalog:\",\n\t\t\"tailwind-variants\": \"catalog:\",\n\t\t\"three\": \"catalog:\",\n\t\t\"zod\": \"catalog:\"\n\t},\n\t\"optionalDependencies\": {\n\t\t\"@sentry/node\": \"^11.10.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@playwright/test\": \"catalog:\",\n\t\t\"@selvajs/compute\": \"workspace:*\",\n\t\t\"@selvajs/config\": \"workspace:*\",\n\t\t\"@selvajs/header-auth-provider\": \"workspace:*\",\n\t\t\"@selvajs/local-provider\": \"workspace:*\",\n\t\t\"@selvajs/mcp\": \"workspace:*\",\n\t\t\"@selvajs/notifications\": \"workspace:*\",\n\t\t\"@selvajs/platform\": \"workspace:*\",\n\t\t\"@selvajs/schemas\": \"workspace:*\",\n\t\t\"@selvajs/server\": \"workspace:*\",\n\t\t\"@selvajs/solve\": \"workspace:*\",\n\t\t\"@selvajs/supabase-provider\": \"workspace:*\",\n\t\t\"@selvajs/ui\": \"workspace:*\",\n\t\t\"@selvajs/visualization\": \"workspace:*\",\n\t\t\"@sveltejs/adapter-node\": \"catalog:\",\n\t\t\"@types/nodemailer\": \"catalog:\",\n\t\t\"@types/three\": \"catalog:\",\n\t\t\"rimraf\": \"catalog:\",\n\t\t\"tw-animate-css\": \"catalog:\",\n\t\t\"vitest\": \"catalog:\"\n\t},\n\t\"imports\": {\n\t\t\"#lib/*\": \"./src/lib/*\"\n\t}\n}\n"],"mappings":""}
@@ -8,7 +8,7 @@ import { t as ALL_PLATFORM_PERMISSIONS } from "./types3.js";
8
8
  import { d as encodeOffsetCursor, l as clampPageLimit, u as decodeOffsetCursor } from "./visibility.js";
9
9
  import { n as readBool } from "./limits.js";
10
10
  import { a as createLogger, i as ConsoleLogger, n as renderThrown } from "./definitions.js";
11
- import { c as ComputeError, i as TreeBuilder, l as ErrorCodes, m as isDefinitionRef, n as GrasshopperClient, p as enableDebugLogging, s as stableStringify } from "./grasshopper.js";
11
+ import { c as withSolveMode, h as isDefinitionRef, i as TreeBuilder, l as ComputeError, m as enableDebugLogging, n as GrasshopperClient, s as stableStringify, u as ErrorCodes } from "./grasshopper.js";
12
12
  import { i as getInputItems, n as serverSourcedInputIds, t as raceAbort } from "./abort-Bfrdupaj.js";
13
13
  import { createRequire } from "node:module";
14
14
  import * as crypto from "node:crypto";
@@ -34619,6 +34619,7 @@ async function runSolvePipeline(args) {
34619
34619
  signal: args.signal,
34620
34620
  selvaevents: args.selvaEvents,
34621
34621
  sessionId: args.sessionId,
34622
+ solveMode: args.solveMode,
34622
34623
  headers: args.headers,
34623
34624
  onServerTiming: (t) => {
34624
34625
  rhino = t;
@@ -34759,13 +34760,14 @@ var SolveEngine = class {
34759
34760
  }
34760
34761
  const treeBuildMs = performance.now() - treeBuildStart;
34761
34762
  const live = args.selvaEvents ? `:live:${args.selvaEvents.solveId}` : "";
34762
- const flight = await this.singleFlight.run(`${identity}:${args.server.id}:${this.clientGeneration(client)}:${stableStringify(inputTree)}${live}`, (signal) => runSolvePipeline({
34763
+ const flight = await this.singleFlight.run(`${identity}:${args.server.id}:${this.clientGeneration(client)}:${withSolveMode(stableStringify(inputTree), args.solveMode)}${live}`, (signal) => runSolvePipeline({
34763
34764
  definitionSource,
34764
34765
  inputTree,
34765
34766
  client,
34766
34767
  responseMaxBytes: this.limits.computeResponseMaxBytes,
34767
34768
  selvaEvents: args.selvaEvents,
34768
34769
  sessionId: args.sessionId,
34770
+ solveMode: args.solveMode,
34769
34771
  ...args.definitionGuid && { headers: { "X-Selva-Definition": args.definitionGuid } },
34770
34772
  signal
34771
34773
  }), args.signal);