@selvajs/selva 4.20.1-beta.0 → 4.20.1-beta.2

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 (243) hide show
  1. package/build/adapter-node.js +1 -1
  2. package/build/client/_app/immutable/assets/{0.CqMxMIbm.css → 0.2jDm0bqh.css} +1 -1
  3. package/build/client/_app/immutable/assets/0.2jDm0bqh.css.br +0 -0
  4. package/build/client/_app/immutable/assets/0.2jDm0bqh.css.gz +0 -0
  5. package/build/client/_app/immutable/chunks/{CDkfHL-P.js → BDYCH-_Q.js} +1 -1
  6. package/build/client/_app/immutable/chunks/BDYCH-_Q.js.br +0 -0
  7. package/build/client/_app/immutable/chunks/BDYCH-_Q.js.gz +0 -0
  8. package/build/client/_app/immutable/chunks/{DkB5TkAO.js → D-SwRD80.js} +4 -4
  9. package/build/client/_app/immutable/chunks/D-SwRD80.js.br +0 -0
  10. package/build/client/_app/immutable/chunks/D-SwRD80.js.gz +0 -0
  11. package/build/client/_app/immutable/chunks/Dvq2vJj6.js +1 -0
  12. package/build/client/_app/immutable/chunks/Dvq2vJj6.js.br +1 -0
  13. package/build/client/_app/immutable/chunks/Dvq2vJj6.js.gz +0 -0
  14. package/build/client/_app/immutable/chunks/{CEJB5MhK.js → DzxE3j6C.js} +1 -1
  15. package/build/client/_app/immutable/chunks/DzxE3j6C.js.br +0 -0
  16. package/build/client/_app/immutable/chunks/DzxE3j6C.js.gz +0 -0
  17. package/build/client/_app/immutable/chunks/{B9o4N7Mf.js → qi43d-TM.js} +1 -1
  18. package/build/client/_app/immutable/chunks/qi43d-TM.js.br +0 -0
  19. package/build/client/_app/immutable/chunks/qi43d-TM.js.gz +0 -0
  20. package/build/client/_app/immutable/chunks/zJ-SFdYZ.js +1 -0
  21. package/build/client/_app/immutable/chunks/zJ-SFdYZ.js.br +0 -0
  22. package/build/client/_app/immutable/chunks/zJ-SFdYZ.js.gz +0 -0
  23. package/build/client/_app/immutable/entry/{app.BOj9G5jx.js → app.hg2qyLJU.js} +2 -2
  24. package/build/client/_app/immutable/entry/app.hg2qyLJU.js.br +0 -0
  25. package/build/client/_app/immutable/entry/app.hg2qyLJU.js.gz +0 -0
  26. package/build/client/_app/immutable/nodes/{2.CERUnqD5.js → 2.CUNbzjI_.js} +1 -1
  27. package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.br +0 -0
  28. package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.gz +0 -0
  29. package/build/client/_app/immutable/nodes/{20.BqTJQD3B.js → 20.9OIre0ah.js} +1 -1
  30. package/build/client/_app/immutable/nodes/20.9OIre0ah.js.br +0 -0
  31. package/build/client/_app/immutable/nodes/20.9OIre0ah.js.gz +0 -0
  32. package/build/client/_app/immutable/nodes/21.gGT7QEb1.js +1 -0
  33. package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.br +1 -0
  34. package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.gz +0 -0
  35. package/build/client/_app/immutable/nodes/{30.Bz0cB9UL.js → 30.BBuL_XNB.js} +2 -2
  36. package/build/client/_app/immutable/nodes/30.BBuL_XNB.js.br +0 -0
  37. package/build/client/_app/immutable/nodes/30.BBuL_XNB.js.gz +0 -0
  38. package/build/client/_app/immutable/nodes/35.De6sleaH.js +5 -0
  39. package/build/client/_app/immutable/nodes/35.De6sleaH.js.br +0 -0
  40. package/build/client/_app/immutable/nodes/35.De6sleaH.js.gz +0 -0
  41. package/build/client/_app/immutable/nodes/{5.Cw-wybBi.js → 5.DmA9lTA-.js} +1 -1
  42. package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.br +1 -0
  43. package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.gz +0 -0
  44. package/build/client/_app/immutable/nodes/{6.BiVPgDTL.js → 6.D6WLqCgl.js} +1 -1
  45. package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.br +0 -0
  46. package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.gz +0 -0
  47. package/build/client/_app/immutable/nodes/{7.BUhgSp_A.js → 7.CNuRjkv2.js} +1 -1
  48. package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.br +0 -0
  49. package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.gz +0 -0
  50. package/build/client/_app/version.json +1 -1
  51. package/build/client/_app/version.json.br +0 -0
  52. package/build/client/_app/version.json.gz +0 -0
  53. package/build/runtime-meta.json +1 -1
  54. package/build/server/.vite/manifest.json +107 -88
  55. package/build/server/_app/immutable/assets/{_layout.CqMxMIbm.css → _layout.2jDm0bqh.css} +1 -1
  56. package/build/server/chunks/SettingsMenu.js +1 -1
  57. package/build/server/chunks/{abort-CNJ8Sn4g.js → abort-Bfrdupaj.js} +10 -3
  58. package/build/server/chunks/{abort-CNJ8Sn4g.js.map → abort-Bfrdupaj.js.map} +1 -1
  59. package/build/server/chunks/access.js +608 -150
  60. package/build/server/chunks/access.js.map +1 -1
  61. package/build/server/chunks/access2.server.js +2 -2
  62. package/build/server/chunks/api-errors.js +1 -1
  63. package/build/server/chunks/api.js +66 -18
  64. package/build/server/chunks/api.js.map +1 -1
  65. package/build/server/chunks/auth-bootstrap.server.js +1 -1
  66. package/build/server/chunks/boot.server.js +12 -702
  67. package/build/server/chunks/boot.server.js.map +1 -1
  68. package/build/server/chunks/bootHealth.server.js.map +1 -1
  69. package/build/server/chunks/compute.js +1 -1
  70. package/build/server/chunks/computeLimits.js +1 -1
  71. package/build/server/chunks/computeRateLimit.server.js +1 -1
  72. package/build/server/chunks/context.js +9 -43
  73. package/build/server/chunks/context.js.map +1 -1
  74. package/build/server/chunks/create-project.js +2 -2
  75. package/build/server/chunks/delete-with-blobs.js +1 -1
  76. package/build/server/chunks/engine.server.js +2 -16
  77. package/build/server/chunks/engine.server.js.map +1 -1
  78. package/build/server/chunks/handlers.js +13 -29
  79. package/build/server/chunks/handlers.js.map +1 -1
  80. package/build/server/chunks/http.js +93 -6
  81. package/build/server/chunks/http.js.map +1 -1
  82. package/build/server/chunks/instance.js +3 -3
  83. package/build/server/chunks/instanceAdmins.server.js +1 -1
  84. package/build/server/chunks/internal.js +1 -1
  85. package/build/server/chunks/limits.js +71 -0
  86. package/build/server/chunks/limits.js.map +1 -0
  87. package/build/server/chunks/ops.js +1 -1
  88. package/build/server/chunks/package.js +1 -1
  89. package/build/server/chunks/package.js.map +1 -1
  90. package/build/server/chunks/permissions.server.js +1 -1
  91. package/build/server/chunks/presets.server.js +1 -1
  92. package/build/server/chunks/previous-key.js +18 -2
  93. package/build/server/chunks/previous-key.js.map +1 -1
  94. package/build/server/chunks/providers.server.js +775 -422
  95. package/build/server/chunks/providers.server.js.map +1 -1
  96. package/build/server/chunks/registry.js +4 -1
  97. package/build/server/chunks/registry.js.map +1 -1
  98. package/build/server/chunks/remote-definition.js +1 -1
  99. package/build/server/chunks/safe-url.js +1 -1
  100. package/build/server/chunks/schema.js.map +1 -1
  101. package/build/server/chunks/schemas.js +12 -61
  102. package/build/server/chunks/schemas.js.map +1 -1
  103. package/build/server/chunks/schemas2.js +80 -0
  104. package/build/server/chunks/schemas2.js.map +1 -0
  105. package/build/server/chunks/server-config-write.js +3 -8
  106. package/build/server/chunks/server-config-write.js.map +1 -1
  107. package/build/server/chunks/signInMaxAge.server.js +1 -1
  108. package/build/server/chunks/solve.server.js +10 -3
  109. package/build/server/chunks/solve.server.js.map +1 -1
  110. package/build/server/chunks/sveltekit.js +4 -4
  111. package/build/server/chunks/token2.server.js +1 -1
  112. package/build/server/chunks/tokens.js +2 -2
  113. package/build/server/chunks/types.js +9 -4
  114. package/build/server/chunks/types.js.map +1 -1
  115. package/build/server/chunks/types2.js +1 -2
  116. package/build/server/chunks/types2.js.map +1 -1
  117. package/build/server/chunks/visibility.js +1 -1
  118. package/build/server/chunks/visibility.js.map +1 -1
  119. package/build/server/entries/endpoints/api/admin/orgs/_id_/_server.ts.js +3 -3
  120. package/build/server/entries/endpoints/api/admin/orgs/_server.ts.js +6 -5
  121. package/build/server/entries/endpoints/api/admin/orgs/_server.ts.js.map +1 -1
  122. package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js +2 -2
  123. package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_grantId_/_server.ts.js +1 -1
  124. package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_server.ts.js +1 -1
  125. package/build/server/entries/endpoints/api/admin/projects/_server.ts.js +1 -1
  126. package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js +1 -1
  127. package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js +1 -1
  128. package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js +2 -2
  129. package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js +2 -2
  130. package/build/server/entries/endpoints/api/admin/users/_server.ts.js +2 -2
  131. package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js +2 -1
  132. package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js.map +1 -1
  133. package/build/server/entries/endpoints/api/v1/compute/schema/_server.ts.js +1 -1
  134. package/build/server/entries/endpoints/api/v1/definitions/_guid_/_server.ts.js +2 -2
  135. package/build/server/entries/endpoints/api/v1/definitions/_guid_/image/_server.ts.js +2 -2
  136. package/build/server/entries/endpoints/api/v1/definitions/_guid_/publish/_server.ts.js +2 -2
  137. package/build/server/entries/endpoints/api/v1/definitions/_guid_/schema/_server.ts.js +2 -2
  138. package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_linkId_/_server.ts.js +2 -2
  139. package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_server.ts.js +2 -2
  140. package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +2 -2
  141. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_server.ts.js +2 -2
  142. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/_server.ts.js +2 -2
  143. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/schema/_server.ts.js +2 -2
  144. package/build/server/entries/endpoints/api/v1/definitions/_server.ts.js +1 -1
  145. package/build/server/entries/endpoints/api/v1/me/_server.ts.js +1 -1
  146. package/build/server/entries/endpoints/api/v1/me/starred/_guid_/_server.ts.js +1 -1
  147. package/build/server/entries/endpoints/api/v1/me/token/_server.ts.js +1 -1
  148. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/_server.ts.js +1 -1
  149. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/assets/_kind_/_server.ts.js +1 -1
  150. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/compute/_server.ts.js +1 -1
  151. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/invites/_id_/_server.ts.js +1 -1
  152. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/invites/_id_/resend/_server.ts.js +1 -1
  153. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/invites/_server.ts.js +1 -1
  154. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/members/_server.ts.js +1 -1
  155. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/members/_userId_/_server.ts.js +1 -1
  156. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_server.ts.js +1 -1
  157. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_tokenId_/_server.ts.js +1 -1
  158. package/build/server/entries/endpoints/api/v1/projects/_id_/_server.ts.js +2 -2
  159. package/build/server/entries/endpoints/api/v1/projects/_id_/members/_server.ts.js +2 -2
  160. package/build/server/entries/endpoints/api/v1/projects/_id_/members/_userId_/_server.ts.js +2 -2
  161. package/build/server/entries/endpoints/api/v1/projects/_id_/reclaim/_server.ts.js +2 -2
  162. package/build/server/entries/endpoints/api/v1/projects/_server.ts.js +1 -1
  163. package/build/server/entries/endpoints/api/v1/solve/_solveId_/cancel/_server.ts.js +1 -1
  164. package/build/server/entries/endpoints/api/v1/solve-events/_server.ts.js +1 -1
  165. package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
  166. package/build/server/entries/endpoints/mcp/_server.ts.js +5 -4
  167. package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
  168. package/build/server/entries/hooks.server.js +3 -92
  169. package/build/server/entries/hooks.server.js.map +1 -1
  170. package/build/server/entries/pages/accept-invite/_page.server.ts.js +27 -6
  171. package/build/server/entries/pages/accept-invite/_page.server.ts.js.map +1 -1
  172. package/build/server/entries/pages/admin/_page.server.ts.js +1 -1
  173. package/build/server/entries/pages/admin/organizations/_page.server.ts.js +1 -1
  174. package/build/server/entries/pages/admin/projects/_id_/_page.server.ts.js +1 -1
  175. package/build/server/entries/pages/admin/projects/_page.server.ts.js +1 -1
  176. package/build/server/entries/pages/admin/system/_page.server.ts.js +2 -2
  177. package/build/server/entries/pages/admin/users/_page.server.ts.js +1 -1
  178. package/build/server/entries/pages/library/_guid_/_page.server.ts.js +1 -1
  179. package/build/server/entries/pages/library/_guid_/_page.svelte.js +10 -8
  180. package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
  181. package/build/server/entries/pages/oauth/authorize/_page.server.ts.js +1 -1
  182. package/build/server/entries/pages/projects/_layout.server.ts.js +1 -1
  183. package/build/server/entries/pages/projects/_page.server.ts.js +2 -2
  184. package/build/server/entries/pages/setup/_page.server.ts.js +1 -1
  185. package/build/server/entries/pages/team/compute/_page.server.ts.js +1 -1
  186. package/build/server/entries/pages/team/members/_page.server.ts.js +1 -1
  187. package/build/server/entries/pages/team/members/_page.svelte.js +2 -2
  188. package/build/server/entries/pages/team/members/_page.svelte.js.map +1 -1
  189. package/build/server/entries/pages/team/projects/_page.server.ts.js +1 -1
  190. package/build/server/entries/pages/team/settings/_page.server.ts.js +1 -1
  191. package/build/server/entries/pages/team/shares/_page.server.ts.js +1 -1
  192. package/build/server/manifest-full.js +1 -1
  193. package/build/server/manifest.js +1 -1
  194. package/build/server/nodes/0.js +2 -2
  195. package/build/server/nodes/2.js +1 -1
  196. package/build/server/nodes/20.js +1 -1
  197. package/build/server/nodes/21.js +1 -1
  198. package/build/server/nodes/30.js +1 -1
  199. package/build/server/nodes/35.js +1 -1
  200. package/build/server/nodes/5.js +1 -1
  201. package/build/server/nodes/6.js +1 -1
  202. package/build/server/nodes/7.js +1 -1
  203. package/build/server/server.js +1 -1
  204. package/package.json +10 -10
  205. package/build/client/_app/immutable/assets/0.CqMxMIbm.css.br +0 -0
  206. package/build/client/_app/immutable/assets/0.CqMxMIbm.css.gz +0 -0
  207. package/build/client/_app/immutable/chunks/B9o4N7Mf.js.br +0 -0
  208. package/build/client/_app/immutable/chunks/B9o4N7Mf.js.gz +0 -0
  209. package/build/client/_app/immutable/chunks/CDkfHL-P.js.br +0 -0
  210. package/build/client/_app/immutable/chunks/CDkfHL-P.js.gz +0 -0
  211. package/build/client/_app/immutable/chunks/CEJB5MhK.js.br +0 -0
  212. package/build/client/_app/immutable/chunks/CEJB5MhK.js.gz +0 -0
  213. package/build/client/_app/immutable/chunks/CmSGJYdN.js +0 -1
  214. package/build/client/_app/immutable/chunks/CmSGJYdN.js.br +0 -1
  215. package/build/client/_app/immutable/chunks/CmSGJYdN.js.gz +0 -0
  216. package/build/client/_app/immutable/chunks/DkB5TkAO.js.br +0 -0
  217. package/build/client/_app/immutable/chunks/DkB5TkAO.js.gz +0 -0
  218. package/build/client/_app/immutable/chunks/I4bYfY0F.js +0 -1
  219. package/build/client/_app/immutable/chunks/I4bYfY0F.js.br +0 -0
  220. package/build/client/_app/immutable/chunks/I4bYfY0F.js.gz +0 -0
  221. package/build/client/_app/immutable/entry/app.BOj9G5jx.js.br +0 -0
  222. package/build/client/_app/immutable/entry/app.BOj9G5jx.js.gz +0 -0
  223. package/build/client/_app/immutable/nodes/2.CERUnqD5.js.br +0 -0
  224. package/build/client/_app/immutable/nodes/2.CERUnqD5.js.gz +0 -0
  225. package/build/client/_app/immutable/nodes/20.BqTJQD3B.js.br +0 -0
  226. package/build/client/_app/immutable/nodes/20.BqTJQD3B.js.gz +0 -0
  227. package/build/client/_app/immutable/nodes/21.DeRwDjP4.js +0 -1
  228. package/build/client/_app/immutable/nodes/21.DeRwDjP4.js.br +0 -0
  229. package/build/client/_app/immutable/nodes/21.DeRwDjP4.js.gz +0 -0
  230. package/build/client/_app/immutable/nodes/30.Bz0cB9UL.js.br +0 -0
  231. package/build/client/_app/immutable/nodes/30.Bz0cB9UL.js.gz +0 -0
  232. package/build/client/_app/immutable/nodes/35.DFkalFgm.js +0 -5
  233. package/build/client/_app/immutable/nodes/35.DFkalFgm.js.br +0 -0
  234. package/build/client/_app/immutable/nodes/35.DFkalFgm.js.gz +0 -0
  235. package/build/client/_app/immutable/nodes/5.Cw-wybBi.js.br +0 -0
  236. package/build/client/_app/immutable/nodes/5.Cw-wybBi.js.gz +0 -0
  237. package/build/client/_app/immutable/nodes/6.BiVPgDTL.js.br +0 -0
  238. package/build/client/_app/immutable/nodes/6.BiVPgDTL.js.gz +0 -0
  239. package/build/client/_app/immutable/nodes/7.BUhgSp_A.js.br +0 -0
  240. package/build/client/_app/immutable/nodes/7.BUhgSp_A.js.gz +0 -0
  241. /package/build/client/_app/immutable/nodes/{0.146jEGn4.js → 0.CYdyv5To.js} +0 -0
  242. /package/build/client/_app/immutable/nodes/{0.146jEGn4.js.br → 0.CYdyv5To.js.br} +0 -0
  243. /package/build/client/_app/immutable/nodes/{0.146jEGn4.js.gz → 0.CYdyv5To.js.gz} +0 -0
@@ -1,17 +1,18 @@
1
1
  import { n as env, t as previousKey } from "./previous-key.js";
2
- import { F as readBool, R as isFlagEnabled, z as NoopLogger } from "./access.js";
3
- import { a as assertCanReadPermissionsBatch, i as assertCanReadPermissions, n as assertCanAccessProfile, r as assertCanManagePermissions, s as ProviderError, t as SYSTEM_CONTEXT } from "./context.js";
2
+ import { B as NoopLogger, I as ENGINE_SETTINGS, at as composeManifest, et as readSetting, it as trimTrailing, nt as rawValue, ot as defineSetting, rt as parseKey32, tt as resolveConfig, z as isFlagEnabled } from "./access.js";
3
+ import { i as ProviderError, n as assertNotShareContext, r as hasPermission, t as SYSTEM_CONTEXT } from "./context.js";
4
4
  import { c as isOrgServer, l as isPlatformServer, o as scopeConfigToOrg } from "./utils.js";
5
- import { i as DEFAULT_ORG_PERMISSIONS, t as ALL_ORG_ASSET_KINDS } from "./schemas.js";
5
+ import { a as toSourceDocumentId, i as UUID_REGEX } from "./schemas.js";
6
+ import { i as DEFAULT_ORG_PERMISSIONS, t as ALL_ORG_ASSET_KINDS } from "./schemas2.js";
6
7
  import { t as ALL_PLATFORM_PERMISSIONS } from "./types3.js";
7
8
  import { d as encodeOffsetCursor, l as clampPageLimit, u as decodeOffsetCursor } from "./visibility.js";
9
+ import { n as readBool } from "./limits.js";
8
10
  import { n as renderThrown } from "./definitions.js";
9
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";
10
- import { r as getInputItems, t as raceAbort } from "./abort-CNJ8Sn4g.js";
12
+ import { i as getInputItems, n as serverSourcedInputIds, t as raceAbort } from "./abort-Bfrdupaj.js";
11
13
  import { createRequire } from "node:module";
12
14
  import * as crypto from "node:crypto";
13
15
  import { createCipheriv, createDecipheriv, createHash, createHmac, createPrivateKey, randomBytes, randomUUID, sign, timingSafeEqual } from "node:crypto";
14
- import { z } from "zod";
15
16
  import { gzip } from "node:zlib";
16
17
  import { pathToFileURL } from "node:url";
17
18
  import * as path$1 from "node:path";
@@ -23,234 +24,121 @@ import { promisify } from "node:util";
23
24
  // \0rolldown/runtime.js
24
25
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
25
26
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
26
- // ../platform/src/config/manifest.ts
27
- function defineSetting(spec) {
28
- return spec;
29
- }
30
- /** Flattens slices and rejects a key declared twice: two readers, two defaults. */
31
- function composeManifest(parts) {
32
- const out = [];
33
- const seen = /* @__PURE__ */ new Set();
34
- for (const part of parts) for (const spec of Array.isArray(part) ? part : [part]) {
35
- for (const name of [spec.key, ...spec.aliases ?? []]) {
36
- if (seen.has(name)) throw new Error(`Config key ${name} is declared twice`);
37
- seen.add(name);
38
- }
39
- out.push(spec);
40
- }
41
- return out;
42
- }
43
- // ../platform/src/utils/trim.ts
44
- function trimTrailing$1(s, ch) {
45
- let end = s.length;
46
- while (end > 0 && s[end - 1] === ch) end--;
47
- return s.slice(0, end);
48
- }
49
- // ../platform/src/config/resolve.ts
50
- var TRUE = /* @__PURE__ */ new Set([
51
- "true",
52
- "1",
53
- "yes",
54
- "on"
55
- ]);
56
- var FALSE = /* @__PURE__ */ new Set([
57
- "false",
58
- "0",
59
- "no",
60
- "off"
61
- ]);
62
- function parse(spec, raw) {
63
- const v = raw.trim();
64
- switch (spec.type) {
65
- case "string":
66
- if (spec.minLength !== void 0 && v.length < spec.minLength) return {
67
- ok: false,
68
- problem: `must be at least ${spec.minLength} characters`
69
- };
70
- return {
71
- ok: true,
72
- value: v
73
- };
74
- case "key": return isKey32(v) ? {
75
- ok: true,
76
- value: v
77
- } : {
78
- ok: false,
79
- problem: "must be 32 bytes as 64 hex characters or base64"
80
- };
81
- case "url": try {
82
- new URL(v);
83
- return {
84
- ok: true,
85
- value: trimTrailing$1(v, "/")
86
- };
87
- } catch {
88
- return {
89
- ok: false,
90
- problem: "must be an absolute URL"
91
- };
92
- }
93
- case "int": {
94
- const n = Number(v);
95
- if (!Number.isInteger(n)) return {
96
- ok: false,
97
- problem: "must be a whole number"
98
- };
99
- if (spec.min !== void 0 && n < spec.min) return {
100
- ok: false,
101
- problem: `must be ≥ ${spec.min}`
102
- };
103
- if (spec.max !== void 0 && n > spec.max) return {
104
- ok: false,
105
- problem: `must be ≤ ${spec.max}`
106
- };
107
- return {
108
- ok: true,
109
- value: n
110
- };
111
- }
112
- case "bool": {
113
- const lower = v.toLowerCase();
114
- if (TRUE.has(lower)) return {
115
- ok: true,
116
- value: true
117
- };
118
- if (FALSE.has(lower)) return {
119
- ok: true,
120
- value: false
121
- };
122
- return {
123
- ok: false,
124
- problem: "must be true or false"
125
- };
126
- }
127
- case "enum": {
128
- const lower = v.toLowerCase();
129
- const match = spec.values.find((m) => m.toLowerCase() === lower);
130
- return match !== void 0 ? {
131
- ok: true,
132
- value: match
133
- } : {
134
- ok: false,
135
- problem: `must be one of ${spec.values.join(" | ")}`
136
- };
137
- }
138
- case "list": return {
139
- ok: true,
140
- value: v.split(",").map((s) => s.trim()).filter(Boolean)
141
- };
142
- }
143
- }
144
- function isKey32(v) {
145
- if (/^[0-9a-fA-F]{64}$/.test(v)) return true;
146
- const buf = Buffer.from(v, "base64");
147
- return buf.length === 32 && trimTrailing$1(buf.toString("base64"), "=") === trimTrailing$1(v, "=");
148
- }
149
- function resolveKey(spec, env) {
150
- let raw = env[spec.key];
151
- let source = "env";
152
- let alias;
153
- if (raw === void 0 || raw === "") {
154
- alias = spec.aliases?.find((a) => env[a] !== void 0 && env[a] !== "");
155
- raw = alias ? env[alias] : void 0;
156
- source = alias ? "alias" : spec.default !== void 0 ? "default" : "unset";
157
- }
158
- const base = {
159
- key: spec.key,
160
- spec,
161
- ...alias ? { alias } : {}
162
- };
163
- if (raw === void 0) {
164
- if (spec.required) return {
165
- ...base,
166
- source,
167
- status: "error",
168
- value: void 0,
169
- problem: "is required"
170
- };
27
+ // ../platform/src/config/report.ts
28
+ /**
29
+ * What `selva config show` and the admin page render. Pure, and free of
30
+ * secret values, so the result can go to a browser or a terminal as is.
31
+ */
32
+ function buildConfigReport(manifest, env, options = {}) {
33
+ const resolved = resolveConfig(manifest, env, options);
34
+ const rows = manifest.map((spec) => {
35
+ const k = resolved.keys[spec.key];
171
36
  return {
172
- ...base,
173
- source,
174
- status: "ok",
175
- value: spec.default
37
+ key: spec.key,
38
+ ...spec.label ? { label: spec.label } : {},
39
+ type: spec.type,
40
+ required: spec.required === true,
41
+ ...spec.type === "int" && spec.zero ? { zero: spec.zero } : {},
42
+ ...spec.type === "int" && spec.unit ? { unit: spec.unit } : {},
43
+ class: spec.class,
44
+ summary: spec.summary === true,
45
+ description: spec.description,
46
+ ...spec.impact ? { impact: spec.impact } : {},
47
+ source: k.source,
48
+ status: k.status,
49
+ display: display(spec, k, rawValue(spec, env)?.raw),
50
+ ...k.problem ? { problem: k.problem } : {},
51
+ ...k.alias ? { alias: k.alias } : {}
176
52
  };
177
- }
178
- const parsed = parse(spec, raw);
179
- if (parsed.ok) return {
180
- ...base,
181
- source,
182
- status: "ok",
183
- value: parsed.value
184
- };
185
- if (spec.onInvalid === "fail") return {
186
- ...base,
187
- source,
188
- status: "error",
189
- value: void 0,
190
- problem: parsed.problem
191
- };
53
+ });
192
54
  return {
193
- ...base,
194
- source,
195
- status: "invalid",
196
- value: spec.default,
197
- problem: parsed.problem
55
+ rows: [...rows.filter((r) => r.summary), ...rows.filter((r) => !r.summary)],
56
+ problems: rows.filter((r) => r.status !== "ok"),
57
+ unknown: resolved.unknown
198
58
  };
199
59
  }
200
- /** Resolve every declared key from an env map. Pure: reads nothing ambient. */
201
- function resolveConfig(manifest, env, options = {}) {
60
+ /** `raw` is the env text the value came from, undefined when it is the default. */
61
+ function display(spec, k, raw) {
62
+ if (k.source === "unset") return "";
63
+ if (spec.sensitive) return raw !== void 0 && spec.generated ? fingerprint(raw) : "set";
64
+ return raw === void 0 ? formatValue(k.value) : raw.trim();
65
+ }
66
+ function formatValue(value) {
67
+ if (Array.isArray(value)) return value.join(",");
68
+ return value === void 0 ? "" : String(value);
69
+ }
70
+ /** Short, stable id for a generated key, so two machines can be compared. */
71
+ function fingerprint(value) {
72
+ return `sha256:${createHash("sha256").update(value.trim()).digest("hex").slice(0, 8)}`;
73
+ }
74
+ // ../platform/src/config/snapshot.ts
75
+ var SENSITIVE_MARKER = "set";
76
+ function takeSnapshot(manifest, env, salt) {
77
+ const key = typeof salt === "string" && salt !== "" ? salt : randomBytes(16).toString("hex");
202
78
  const values = {};
203
- const keys = {};
204
- const errors = [];
205
- const known = new Set(options.external ?? []);
79
+ const sensitive = [];
206
80
  for (const spec of manifest) {
207
- known.add(spec.key);
208
- for (const a of spec.aliases ?? []) known.add(a);
209
- const report = resolveKey(spec, env);
210
- keys[spec.key] = report;
211
- values[spec.key] = report.value;
212
- if (report.status === "error") errors.push(report);
213
- }
214
- const declared = manifest.map((s) => s.key);
215
- const prefixes = options.prefixes ?? [];
216
- const unknown = [];
217
- for (const key of Object.keys(env)) {
218
- if (known.has(key) || !prefixes.some((p) => key.startsWith(p))) continue;
219
- const suggestion = nearest(key, declared);
220
- unknown.push(suggestion ? {
221
- key,
222
- suggestion
223
- } : { key });
81
+ const found = rawValue(spec, env);
82
+ if (!found) continue;
83
+ const raw = found.raw.trim();
84
+ if (spec.sensitive) {
85
+ values[spec.key] = spec.generated ? createHmac("sha256", key).update(raw).digest("hex").slice(0, 16) : SENSITIVE_MARKER;
86
+ sensitive.push(spec.key);
87
+ } else values[spec.key] = raw;
224
88
  }
225
89
  return {
90
+ version: 1,
91
+ salt: key,
226
92
  values,
227
- keys,
228
- errors,
229
- unknown
93
+ sensitive
230
94
  };
231
95
  }
232
- /** A declared name within a typo's reach: a prefix of it, or a few edits away. */
233
- function nearest(key, declared) {
234
- let best;
235
- let bestDistance = Infinity;
236
- for (const candidate of declared) {
237
- const d = candidate.startsWith(key) || key.startsWith(candidate) ? 0 : editDistance(key, candidate);
238
- if (d < bestDistance) {
239
- best = candidate;
240
- bestDistance = d;
241
- }
242
- }
243
- return bestDistance <= 3 ? best : void 0;
96
+ /**
97
+ * What changed since `before`, the previous snapshot as read from disk; anything
98
+ * that is not a snapshot counts as none. Take `after` with `before.salt`, or every
99
+ * generated key reads as changed.
100
+ */
101
+ function diffSnapshots(before, after) {
102
+ if (!isSnapshot(before)) return [];
103
+ const secret = /* @__PURE__ */ new Set([...before.sensitive, ...after.sensitive]);
104
+ const changes = [];
105
+ const plain = (key, from, to) => secret.has(key) ? {} : {
106
+ ...from !== void 0 ? { from } : {},
107
+ ...to !== void 0 ? { to } : {}
108
+ };
109
+ for (const [key, to] of Object.entries(after.values)) {
110
+ const from = before.values[key];
111
+ if (from === void 0) changes.push({
112
+ key,
113
+ change: "added",
114
+ ...plain(key, void 0, to)
115
+ });
116
+ else if (from !== to) changes.push({
117
+ key,
118
+ change: "changed",
119
+ ...plain(key, from, to)
120
+ });
121
+ }
122
+ for (const [key, from] of Object.entries(before.values)) if (!(key in after.values)) changes.push({
123
+ key,
124
+ change: "removed",
125
+ ...plain(key, from)
126
+ });
127
+ return changes;
244
128
  }
245
- function editDistance(a, b) {
246
- let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
247
- for (let i = 1; i <= a.length; i++) {
248
- const row = [i];
249
- for (let j = 1; j <= b.length; j++) row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
250
- prev = row;
251
- }
252
- return prev[b.length];
129
+ function isSnapshot(value) {
130
+ if (typeof value !== "object" || value === null) return false;
131
+ const { version, salt, values, sensitive } = value;
132
+ return version === 1 && typeof salt === "string" && salt !== "" && typeof values === "object" && values !== null && !Array.isArray(values) && Object.values(values).every((v) => typeof v === "string") && Array.isArray(sensitive) && sensitive.every((k) => typeof k === "string");
253
133
  }
134
+ // ../platform/src/errors/interface.ts
135
+ /**
136
+ * Default `IErrorReporter` — discards every report, so call sites can report
137
+ * unconditionally when no error-tracking backend is configured.
138
+ */
139
+ var NoopErrorReporter = class {
140
+ capture(_error, _context) {}
141
+ };
254
142
  // ../platform/src/data/interface.ts
255
143
  /**
256
144
  * Written to `solve_metrics.actor_id` when a user is erased, so capacity/billing
@@ -270,63 +158,19 @@ function assertSafeKey(value, label) {
270
158
  if (!value || !SAFE_SEGMENT_ONLY.test(value) || value === "." || value === "..") throw new Error(`Unsafe ${label}: ${JSON.stringify(value)}`);
271
159
  }
272
160
  // ../platform/src/definitions/paths.ts
161
+ function prefix$1(guid) {
162
+ assertSafeKey(guid, "guid");
163
+ return `definitions/${guid}/`;
164
+ }
273
165
  var definitionPaths = {
274
166
  version: (guid, versionNumber, ext) => {
275
- assertSafeKey(guid, "guid");
167
+ const dir = prefix$1(guid);
276
168
  if (!Number.isInteger(versionNumber) || versionNumber < 1) throw new Error(`Unsafe versionNumber: ${versionNumber}`);
277
- return `definitions/${guid}/versions/v${versionNumber}.${ext}`;
278
- },
279
- image: (guid) => {
280
- assertSafeKey(guid, "guid");
281
- return `definitions/${guid}/cover.webp`;
169
+ return `${dir}versions/v${versionNumber}.${ext}`;
282
170
  },
283
- prefix: (guid) => {
284
- assertSafeKey(guid, "guid");
285
- return `definitions/${guid}/`;
286
- }
171
+ image: (guid) => `${prefix$1(guid)}cover.webp`,
172
+ prefix: prefix$1
287
173
  };
288
- // ../platform/src/definitions/schemas.ts
289
- var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
290
- var GuidSchema = z.string().toLowerCase().regex(UUID_REGEX, "Invalid GUID format");
291
- /** A Grasshopper document GUID as stores keep and compare it (lowercase), or null for anything else. */
292
- function toSourceDocumentId(value) {
293
- return typeof value === "string" && UUID_REGEX.test(value) ? value.toLowerCase() : null;
294
- }
295
- var DefinitionStatusSchema = z.enum([
296
- "draft",
297
- "published",
298
- "archived"
299
- ]);
300
- var DefinitionChannelSchema = z.enum(["live", "draft"]);
301
- /** HTTP-body validator for new-definition input. */
302
- var CreateDefinitionInputSchema = z.object({
303
- displayName: z.string().trim().min(1, "Display name is required").max(256),
304
- description: z.string().max(2e3).optional(),
305
- coverImage: z.string().max(2048).optional(),
306
- category: z.string().max(128).optional(),
307
- tags: z.array(z.string().max(64)).max(20).optional(),
308
- projectId: GuidSchema,
309
- computeServerId: GuidSchema.optional()
310
- });
311
- /**
312
- * PATCH validator. Field semantics match `DefinitionRecordPatch`:
313
- * - missing / `undefined` — leave unchanged
314
- * - `null` — clear (only on nullable fields)
315
- * - value — set
316
- */
317
- var UpdateMetadataInputSchema = z.object({
318
- displayName: z.string().trim().min(1, "Display name is required").max(256).optional(),
319
- description: z.string().max(2e3).nullable().optional(),
320
- coverImage: z.string().max(2048).nullable().optional(),
321
- category: z.string().max(128).nullable().optional(),
322
- tags: z.array(z.string().max(64)).max(20).nullable().optional(),
323
- projectId: GuidSchema.optional(),
324
- computeServerId: GuidSchema.nullable().optional(),
325
- solveCacheLimit: z.number().int().min(0).max(1e5).nullable().optional(),
326
- status: DefinitionStatusSchema.optional()
327
- });
328
- /** Body for `POST /api/definitions/[guid]/publish`. */
329
- var PublishVersionInputSchema = z.object({ versionId: GuidSchema.optional() }).default({});
330
174
  // ../platform/src/events/interface.ts
331
175
  /**
332
176
  * `ctx.userId === ''` is the `SYSTEM_CONTEXT` convention for a server-internal
@@ -348,6 +192,10 @@ var NoopEventSink = class {
348
192
  async emit(_event) {}
349
193
  };
350
194
  // ../platform/src/organizations/paths.ts
195
+ function prefix(id) {
196
+ assertSafeKey(id, "orgId");
197
+ return `orgs/${id}/`;
198
+ }
351
199
  /**
352
200
  * Every branding asset is stored as `.webp` (uploads go through the shared
353
201
  * transcoder), so the path per kind is fixed and a re-upload overwrites in
@@ -359,15 +207,30 @@ var NoopEventSink = class {
359
207
  */
360
208
  var orgPaths = {
361
209
  asset: (id, kind) => {
362
- assertSafeKey(id, "orgId");
363
210
  assertSafeKey(kind, "assetKind");
364
- return `orgs/${id}/branding/${kind}.webp`;
211
+ return `${prefix(id)}branding/${kind}.webp`;
365
212
  },
366
- prefix: (id) => {
367
- assertSafeKey(id, "orgId");
368
- return `orgs/${id}/`;
369
- }
213
+ prefix
370
214
  };
215
+ // ../platform/src/permissions/guards.ts
216
+ /** May `ctx` read `userId`'s platform permissions? Throws `ProviderError(403)` if not. */
217
+ function assertCanReadPermissions(ctx, userId) {
218
+ assertNotShareContext(ctx, "read permissions");
219
+ if (ctx.userId === userId || hasPermission(ctx, "manage_instance_users")) return;
220
+ throw new ProviderError("Forbidden: cannot read another user’s permissions", 403);
221
+ }
222
+ /** May `ctx` read several users' platform permissions? Throws `ProviderError(403)` if not. */
223
+ function assertCanReadPermissionsBatch(ctx) {
224
+ assertNotShareContext(ctx, "read permissions");
225
+ if (hasPermission(ctx, "manage_instance_users")) return;
226
+ throw new ProviderError("Forbidden: instance admin or manage_instance_users required", 403);
227
+ }
228
+ /** May `ctx` change platform permissions? Throws `ProviderError(403)` if not. */
229
+ function assertCanManagePermissions(ctx) {
230
+ assertNotShareContext(ctx, "manage permissions");
231
+ if (hasPermission(ctx, "instance_admin")) return;
232
+ throw new ProviderError("Forbidden: instance admin required", 403);
233
+ }
371
234
  // ../platform/src/storage/image.ts
372
235
  /**
373
236
  * Shared image-transcoding helper for `IStorageProvider` implementations.
@@ -379,19 +242,21 @@ var orgPaths = {
379
242
  */
380
243
  var IMAGE_MAX_WIDTH = 1200;
381
244
  var MAX_INPUT_PIXELS = 6e7;
245
+ var MAX_INPUT_SIDE = 16384;
382
246
  var TRANSCODE_TIMEOUT_SECONDS = 10;
383
- var ALLOWED_FORMATS = /* @__PURE__ */ new Set([
384
- "jpeg",
385
- "png",
386
- "webp",
387
- "gif",
388
- "tiff",
389
- "svg"
247
+ var TRANSCODE_WAIT_MS = 2e4;
248
+ var SVG_MAX_BYTES = 1048576;
249
+ var SVG_MAX_ELEMENTS = 1e4;
250
+ var SVG_ENCODINGS = /* @__PURE__ */ new Set([
251
+ "utf-8",
252
+ "us-ascii",
253
+ "iso-8859-1"
390
254
  ]);
391
255
  /** True if the input is an image to process. The content type decides, unless it says nothing. */
392
256
  function isImageUpload(contentType, storagePath) {
393
- if (contentType && contentType !== "application/octet-stream") return contentType.startsWith("image/");
394
- return /\.(webp|png|jpe?g|gif|bmp|tif?f|svg)$/i.test(storagePath);
257
+ const type = mediaType(contentType);
258
+ if (type && type !== "application/octet-stream") return type.startsWith("image/");
259
+ return /\.(webp|png|jpe?g|gif|tif?f|svg)$/i.test(storagePath);
395
260
  }
396
261
  /**
397
262
  * Rewrites a path's extension to `.webp`; unchanged for non-image extensions.
@@ -399,14 +264,15 @@ function isImageUpload(contentType, storagePath) {
399
264
  * persisted — served bytes stay XSS-free without a sanitizer.
400
265
  */
401
266
  function toWebpPath(storagePath) {
402
- return storagePath.replace(/\.(png|jpe?g|gif|bmp|tif?f|svg)$/i, ".webp");
267
+ return storagePath.replace(/\.(png|jpe?g|gif|tif?f|svg)$/i, ".webp");
403
268
  }
404
269
  /**
405
270
  * Transcodes images to WebP; passes non-images through unchanged, so
406
271
  * providers can call this unconditionally before `put`.
407
272
  *
408
- * Throws `ProviderError(422)` for bytes it won't process, and a plain error if
409
- * `sharp` isn't installed, which is a config problem rather than a bad upload.
273
+ * Throws `ProviderError(422)` for bytes it won't process, `ProviderError(503)`
274
+ * when too many transcodes are queued, and a plain error if `sharp` isn't
275
+ * installed, which is a config problem rather than a bad upload.
410
276
  */
411
277
  async function transcodeImageIfNeeded(data, contentType, storagePath) {
412
278
  if (!isImageUpload(contentType, storagePath)) return {
@@ -414,19 +280,97 @@ async function transcodeImageIfNeeded(data, contentType, storagePath) {
414
280
  contentType: contentType ?? "application/octet-stream",
415
281
  path: storagePath
416
282
  };
283
+ const input = Buffer.from(data);
284
+ const format = checkFormat(input, contentType, storagePath);
417
285
  const sharp = await loadSharp();
418
- const compressed = await withTranscodeSlot(() => rasterize(sharp, Buffer.from(data), contentType, storagePath));
286
+ const compressed = await withTranscodeSlot(() => rasterize(sharp, input, format));
419
287
  return {
420
288
  data: new Uint8Array(compressed),
421
289
  contentType: "image/webp",
422
290
  path: toWebpPath(storagePath)
423
291
  };
424
292
  }
425
- async function rasterize(sharp, input, contentType, storagePath) {
293
+ function mediaType(contentType) {
294
+ return (contentType ?? "").split(";")[0].trim().toLowerCase();
295
+ }
296
+ /** Refuses what sharp should never parse, from the bytes alone. */
297
+ function checkFormat(input, contentType, storagePath) {
298
+ const format = sniffFormat(input);
299
+ if (!format) throw new ProviderError("Unsupported image format", 422);
300
+ if (format === "svg") {
301
+ if (!(mediaType(contentType) === "image/svg+xml" || /\.svg$/i.test(storagePath))) throw new ProviderError("SVG content needs the image/svg+xml type", 422);
302
+ checkSvg(input);
303
+ }
304
+ return format;
305
+ }
306
+ function sniffFormat(input) {
307
+ const head = input.subarray(0, 12).toString("latin1");
308
+ if (head.startsWith("ÿØÿ")) return "jpeg";
309
+ if (head.startsWith("‰PNG\r\n\n")) return "png";
310
+ if (head.startsWith("GIF87a") || head.startsWith("GIF89a")) return "gif";
311
+ if (head.startsWith("RIFF") && head.slice(8, 12) === "WEBP") return "webp";
312
+ if (head.startsWith("II*\0") || head.startsWith("MM\0*")) return "tiff";
313
+ if (/^(?:\xEF\xBB\xBF)?[\t\n\r ]*</.test(input.subarray(0, 1024).toString("latin1"))) return "svg";
314
+ return null;
315
+ }
316
+ /**
317
+ * Refuses an SVG that could draw slowly, or pull in one that does: a `data:` URL
318
+ * (librsvg follows it to another SVG or stylesheet) or an entity (which can spell
319
+ * anything). librsvg decodes character references and CSS escapes, and joins
320
+ * `<style>` text across comments and child elements, so the checks read the text
321
+ * the same way.
322
+ */
323
+ function checkSvg(input) {
324
+ const refuse = (why) => new ProviderError(`SVG ${why}`, 422);
325
+ if (input.length > SVG_MAX_BYTES) throw refuse(`is larger than ${SVG_MAX_BYTES / 1024} KB`);
326
+ const text = input.toString("latin1");
327
+ if (input.includes(0) || !SVG_ENCODINGS.has(declaredEncoding(text))) throw refuse("must be UTF-8");
328
+ if (/<!ENTITY/i.test(text)) throw refuse("may not declare entities");
329
+ let elements = 0;
330
+ for (const _ of text.matchAll(/<[A-Za-z_:]/g)) if (++elements > SVG_MAX_ELEMENTS) throw refuse(`has more than ${SVG_MAX_ELEMENTS} elements`);
331
+ for (const seen of [unescapeSvg(text), unescapeSvg(textContent(text))]) {
332
+ if (/filter/i.test(seen) || /<(?:[\w.-]+:)?fe[A-Z]/.test(seen)) throw refuse("filters are not accepted");
333
+ if (/<(?:[\w.-]+:)?use\b/.test(seen) || /mask|marker|dasharray/i.test(seen)) throw refuse("<use>, masks, markers and dash patterns are not accepted");
334
+ if (/d[\t\n\r]*a[\t\n\r]*t[\t\n\r]*a[\t\n\r]*:/i.test(seen)) throw refuse("may not embed data: URLs");
335
+ }
336
+ }
337
+ function declaredEncoding(text) {
338
+ const decl = /^(?:\xEF\xBB\xBF)?<\?xml[^>]*\bencoding\s*=\s*["']([^"']*)["']/.exec(text);
339
+ return decl ? decl[1].toLowerCase() : "utf-8";
340
+ }
341
+ function unescapeSvg(text) {
342
+ return text.replace(/&#(?:x([0-9a-f]+)|(\d+));/gi, (_, hex, dec) => codePoint(hex ? parseInt(hex, 16) : Number(dec))).replace(/\\(?:([0-9a-f]{1,6})[\t\n\r ]?|([^\n]))/gi, (_, hex, ch) => hex ? codePoint(parseInt(hex, 16)) : ch);
343
+ }
344
+ function codePoint(n) {
345
+ return n > 0 && n <= 1114111 ? String.fromCodePoint(n) : "";
346
+ }
347
+ /** Character data only: comments, tags and processing instructions dropped, CDATA kept. */
348
+ function textContent(text) {
349
+ let out = "";
350
+ let i = 0;
351
+ while (i < text.length) if (text.startsWith("<!--", i)) {
352
+ const end = text.indexOf("-->", i + 4);
353
+ i = end < 0 ? text.length : end + 3;
354
+ } else if (text.startsWith("<![CDATA[", i)) {
355
+ const end = text.indexOf("]]>", i + 9);
356
+ out += text.slice(i + 9, end < 0 ? text.length : end);
357
+ i = end < 0 ? text.length : end + 3;
358
+ } else if (text[i] === "<") {
359
+ const end = text.indexOf(">", i + 1);
360
+ i = end < 0 ? text.length : end + 1;
361
+ } else {
362
+ const end = text.indexOf("<", i);
363
+ out += text.slice(i, end < 0 ? text.length : end);
364
+ i = end < 0 ? text.length : end;
365
+ }
366
+ return out;
367
+ }
368
+ async function rasterize(sharp, input, format) {
426
369
  try {
427
- const { format, width = 0, height = 0 } = await sharp(input, { limitInputPixels: false }).metadata();
428
- const declaredSvg = contentType === "image/svg+xml" || /\.svg$/i.test(storagePath);
429
- if (!ALLOWED_FORMATS.has(format) || format === "svg" && !declaredSvg) throw new ProviderError(`Unsupported image format: ${format}`, 422);
370
+ const meta = await sharp(input, { limitInputPixels: false }).metadata();
371
+ if (meta.format !== format) throw new ProviderError(`Unsupported image format: ${meta.format}`, 422);
372
+ const { width = 0, height = 0 } = meta;
373
+ if (width > MAX_INPUT_SIDE || height > MAX_INPUT_SIDE) throw new ProviderError(`Image is more than ${MAX_INPUT_SIDE} pixels on a side`, 422);
430
374
  if (width * height > MAX_INPUT_PIXELS) throw new ProviderError("Image has too many pixels", 422);
431
375
  return await sharp(input, { limitInputPixels: MAX_INPUT_PIXELS }).autoOrient().resize({
432
376
  width: IMAGE_MAX_WIDTH,
@@ -436,15 +380,19 @@ async function rasterize(sharp, input, contentType, storagePath) {
436
380
  }).webp({ quality: 85 }).timeout({ seconds: TRANSCODE_TIMEOUT_SECONDS }).toBuffer();
437
381
  } catch (err) {
438
382
  if (err instanceof ProviderError) throw err;
383
+ if (err instanceof Error && /^timeout:/m.test(err.message)) throw new ProviderError(`The image took more than ${TRANSCODE_TIMEOUT_SECONDS} seconds to process`, 422);
439
384
  throw new ProviderError("The image could not be read", 422);
440
385
  }
441
386
  }
442
387
  var activeTranscodes = 0;
443
388
  var waitingTranscodes = [];
444
- /** Runs `fn` when a slot is free. A finishing transcode hands its slot straight to the next. */
389
+ /**
390
+ * Runs `fn` when a slot is free. A finishing transcode hands its slot straight to
391
+ * the next. Throws `ProviderError(503)` when the queue is full or the wait runs out.
392
+ */
445
393
  async function withTranscodeSlot(fn) {
446
394
  if (activeTranscodes < 2) activeTranscodes += 1;
447
- else await new Promise((resolve) => waitingTranscodes.push(resolve));
395
+ else await waitForSlot();
448
396
  try {
449
397
  return await fn();
450
398
  } finally {
@@ -453,6 +401,21 @@ async function withTranscodeSlot(fn) {
453
401
  else activeTranscodes -= 1;
454
402
  }
455
403
  }
404
+ function waitForSlot() {
405
+ const busy = () => new ProviderError("Too many images are being processed. Try again shortly.", 503);
406
+ if (waitingTranscodes.length >= 8) return Promise.reject(busy());
407
+ return new Promise((resolve, reject) => {
408
+ const timer = setTimeout(() => {
409
+ waitingTranscodes.splice(waitingTranscodes.indexOf(start), 1);
410
+ reject(busy());
411
+ }, TRANSCODE_WAIT_MS);
412
+ const start = () => {
413
+ clearTimeout(timer);
414
+ resolve();
415
+ };
416
+ waitingTranscodes.push(start);
417
+ });
418
+ }
456
419
  var SHARP_MODULE = "sharp";
457
420
  var cachedSharp = null;
458
421
  async function loadSharp() {
@@ -556,6 +519,16 @@ function emptyProfile(userId) {
556
519
  recentRuns: []
557
520
  };
558
521
  }
522
+ // ../platform/src/userProfile/guards.ts
523
+ /**
524
+ * For provider authors: may `ctx` read or change `userId`'s profile? Throws
525
+ * `ProviderError(403)` if not.
526
+ */
527
+ function assertCanAccessProfile(ctx, userId) {
528
+ assertNotShareContext(ctx, "access user profiles");
529
+ if (ctx.userId === userId || hasPermission(ctx, "instance_admin")) return;
530
+ throw new ProviderError("Forbidden: cannot access another user’s profile", 403);
531
+ }
559
532
  // ../platform/src/utils/audit.ts
560
533
  /**
561
534
  * Audit-field stamping helpers. Every mutable entity carries `createdAt` /
@@ -588,31 +561,36 @@ function auditSoftDelete(ctx, fallbackActor) {
588
561
  var NoopSolveMetricSink = class {
589
562
  async record(_ctx, _metric) {}
590
563
  };
591
- // ../platform/src/errors/interface.ts
592
- /**
593
- * Default `IErrorReporter` — discards every report. Used when no error-tracking
594
- * backend is configured (e.g. `SENTRY_DSN` unset), so call sites can report
595
- * unconditionally. Swap in a real reporter to ship errors off-box.
596
- */
597
- var NoopErrorReporter = class {
598
- capture(_error, _context) {}
599
- };
600
564
  // ../platform/src/computeServer/secrets.ts
601
565
  var ALGO = "aes-256-gcm";
602
566
  var IV_BYTES = 12;
567
+ var TAG_BYTES = 16;
603
568
  var PREFIX_V1 = "enc:v1:";
604
569
  var PREFIX_V2 = "enc:v2:";
570
+ var PREFIX_V3 = "enc:v3:";
571
+ var PREFIX_LENGTH = 7;
605
572
  function isEncryptedSecret(value) {
573
+ return isLegacyEnvelope(value) || value.startsWith(PREFIX_V3);
574
+ }
575
+ /**
576
+ * An `enc:v1:` or `enc:v2:` envelope: sealed without a {@link SecretBinding}, so it
577
+ * still opens after its record's URL changes. Stores re-seal these.
578
+ */
579
+ function isLegacyEnvelope(value) {
606
580
  return value.startsWith(PREFIX_V1) || value.startsWith(PREFIX_V2);
607
581
  }
582
+ function bindingAad({ id, url }) {
583
+ return Buffer.from(JSON.stringify([id, url]), "utf8");
584
+ }
608
585
  /**
609
- * AES-256-GCM envelope for at-rest secrets (e.g. compute API keys).
610
- *
611
- * Wire format: `enc:v2:<base64(iv|tag|ciphertext)>`. `v2` authenticates the
612
- * record the secret belongs to as AAD, so ciphertext copied onto another record
613
- * fails to decrypt instead of handing the plaintext to that record's URL.
614
- * `enc:v1:` envelopes have no AAD and still read: a store rewrites them as `v2`
615
- * on its next save.
586
+ * AES-256-GCM envelope for at-rest secrets (e.g. compute API keys):
587
+ * `enc:v<n>:<base64(iv|tag|ciphertext)>`. What `aad` is picks the version, and
588
+ * the version says what GCM authenticates besides the ciphertext:
589
+ * - a {@link SecretBinding} gives `v3`: the record's id and URL. Ciphertext copied
590
+ * onto another record, or a record pointed at another host, fails to decrypt
591
+ * instead of handing the plaintext to that host.
592
+ * - a string gives `v2`: that string, which stores set to the record's id.
593
+ * - nothing gives `v1`: nothing.
616
594
  *
617
595
  * Defends against backup leaks, accidental file/DB sharing, and read-only
618
596
  * storage access — not against an attacker who also has the master key
@@ -621,39 +599,50 @@ function isEncryptedSecret(value) {
621
599
  *
622
600
  * Pure `node:crypto`, no fs or DB coupling, so the local and Supabase
623
601
  * compute-server stores share this one implementation.
624
- *
625
- * Pass `aad` to bind the secret to its record. {@link decryptSecret} then needs the
626
- * same value.
627
602
  */
628
603
  function encryptSecret(plaintext, key, aad) {
629
604
  if (key.length !== 32) throw new Error(`Secret key must be 32 bytes; got ${key.length}`);
630
605
  if (isEncryptedSecret(plaintext)) throw new Error("Refusing to encrypt a value that is already encrypted");
606
+ const [prefix, aadBytes] = aad === void 0 ? [PREFIX_V1, void 0] : typeof aad === "string" ? [PREFIX_V2, Buffer.from(aad, "utf8")] : [PREFIX_V3, bindingAad(aad)];
631
607
  const iv = randomBytes(IV_BYTES);
632
608
  const cipher = createCipheriv(ALGO, key, iv);
633
- if (aad !== void 0) cipher.setAAD(Buffer.from(aad, "utf8"));
609
+ if (aadBytes) cipher.setAAD(aadBytes);
634
610
  const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
635
611
  const tag = cipher.getAuthTag();
636
- return (aad === void 0 ? PREFIX_V1 : PREFIX_V2) + Buffer.concat([
612
+ return prefix + Buffer.concat([
637
613
  iv,
638
614
  tag,
639
615
  ciphertext
640
616
  ]).toString("base64");
641
617
  }
642
- /** `aad` is ignored for an `enc:v1:` envelope and required for an `enc:v2:` one. */
618
+ function aadToOpen(envelope, aad) {
619
+ if (envelope.startsWith(PREFIX_V1)) return void 0;
620
+ if (envelope.startsWith(PREFIX_V2)) {
621
+ if (aad === void 0) throw new Error("This secret is bound to a record: pass its id");
622
+ return Buffer.from(typeof aad === "string" ? aad : aad.id, "utf8");
623
+ }
624
+ if (aad === void 0 || typeof aad === "string") throw new Error("This secret is bound to a record and its URL: pass both");
625
+ return bindingAad(aad);
626
+ }
627
+ /**
628
+ * `aad` is ignored for `v1`. `v2` takes the string it was sealed with, or a
629
+ * binding's `id`; `v3` needs the binding.
630
+ */
643
631
  function decryptSecret(envelope, key, aad) {
644
632
  if (key.length !== 32) throw new Error(`Secret key must be 32 bytes; got ${key.length}`);
645
633
  if (!isEncryptedSecret(envelope)) throw new Error("Value is not an encrypted secret envelope");
646
- const bound = envelope.startsWith(PREFIX_V2);
647
- if (bound && aad === void 0) throw new Error("This secret is bound to a record: pass its id");
648
- const buf = Buffer.from(envelope.slice(7), "base64");
634
+ const aadBytes = aadToOpen(envelope, aad);
635
+ const buf = Buffer.from(envelope.slice(PREFIX_LENGTH), "base64");
636
+ if (buf.length < 28) throw new Error("Encrypted secret is shorter than its IV and tag");
649
637
  const iv = buf.subarray(0, IV_BYTES);
650
638
  const tag = buf.subarray(IV_BYTES, 28);
651
639
  const ciphertext = buf.subarray(28);
652
- const decipher = createDecipheriv(ALGO, key, iv);
640
+ const decipher = createDecipheriv(ALGO, key, iv, { authTagLength: TAG_BYTES });
653
641
  decipher.setAuthTag(tag);
654
- if (bound) decipher.setAAD(Buffer.from(aad, "utf8"));
642
+ if (aadBytes) decipher.setAAD(aadBytes);
655
643
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
656
644
  }
645
+ var GENERATE_HINT = "Generate one with: node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"";
657
646
  /**
658
647
  * Decodes a `SELVA_AT_REST_KEY` env var into a 32-byte buffer (64-char hex or
659
648
  * base64, with or without padding). Throws on anything else so a
@@ -661,11 +650,22 @@ function decryptSecret(envelope, key, aad) {
661
650
  * ciphertext nothing can decrypt.
662
651
  */
663
652
  function decodeSecretKey(raw) {
664
- const key = raw.trim();
665
- if (/^[0-9a-fA-F]{64}$/.test(key)) return Buffer.from(key, "hex");
666
- const buf = Buffer.from(key, "base64");
667
- if (buf.length === 32 && trimTrailing$1(buf.toString("base64"), "=") === trimTrailing$1(key, "=")) return buf;
668
- throw new Error("SELVA_AT_REST_KEY must be 32 bytes encoded as 64-char hex or base64. Generate one with: node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"");
653
+ const key = parseKey32(raw);
654
+ if (key) return key;
655
+ throw new Error(`SELVA_AT_REST_KEY must be 32 bytes encoded as 64-char hex or base64. ${GENERATE_HINT}`);
656
+ }
657
+ /**
658
+ * `SELVA_AT_REST_KEY`, plus `SELVA_AT_REST_KEY_PREVIOUS` while it is within its
659
+ * deadline. Throws when the current key is missing or malformed.
660
+ */
661
+ function readAtRestKeys(env) {
662
+ if (!env.SELVA_AT_REST_KEY) throw new Error(`Missing required env var: SELVA_AT_REST_KEY (32-byte hex or base64). ${GENERATE_HINT}`);
663
+ const current = decodeSecretKey(env.SELVA_AT_REST_KEY);
664
+ const previous = previousKey(env, "SELVA_AT_REST_KEY").key;
665
+ return previous ? {
666
+ current,
667
+ previous: decodeSecretKey(previous)
668
+ } : { current };
669
669
  }
670
670
  /**
671
671
  * {@link decryptSecret} under each key in turn, current first. AES-GCM
@@ -1066,7 +1066,9 @@ async function createSelvaProviders(env, options) {
1066
1066
  let solveMetricSink;
1067
1067
  function resolve() {
1068
1068
  if (config) return config;
1069
- config = typeof raw === "function" ? raw(env) : raw;
1069
+ const candidate = typeof raw === "function" ? raw(env) : raw;
1070
+ if (isFlagEnabled(candidate, "ENABLE_PLATFORM_PROJECTS") && candidate.data.platformProjectGrants.unsupported) throw new Error(`ENABLE_PLATFORM_PROJECTS is on, but ${candidate.data.constructor.name} cannot store platform-project grants. Turn SELVA_FLAG_ENABLE_PLATFORM_PROJECTS off.`);
1071
+ config = candidate;
1070
1072
  const wiring = {
1071
1073
  component: "selva",
1072
1074
  auth: config.auth.name,
@@ -1578,6 +1580,7 @@ var LocalInviteStore = class LocalInviteStore {
1578
1580
  const file = await this.load();
1579
1581
  const target = file.invites.find((i) => i.id === id);
1580
1582
  if (!target || target.acceptedAt) return null;
1583
+ if (Date.parse(target.expiresAt) <= Date.now()) return null;
1581
1584
  target.acceptedAt = (/* @__PURE__ */ new Date()).toISOString();
1582
1585
  target.acceptedByUserId = userId;
1583
1586
  await this.save(file);
@@ -1593,6 +1596,17 @@ var LocalInviteStore = class LocalInviteStore {
1593
1596
  });
1594
1597
  return true;
1595
1598
  }
1599
+ async reopen(_ctx, id, userId) {
1600
+ return this.locked(async () => {
1601
+ const file = await this.load();
1602
+ const target = file.invites.find((i) => i.id === id);
1603
+ if (!target?.acceptedAt || target.acceptedByUserId !== userId) return false;
1604
+ delete target.acceptedAt;
1605
+ delete target.acceptedByUserId;
1606
+ await this.save(file);
1607
+ return true;
1608
+ });
1609
+ }
1596
1610
  async revoke(ctx, id) {
1597
1611
  const target = await this.locked(async () => {
1598
1612
  const file = await this.load();
@@ -1779,11 +1793,10 @@ function assertIdsFree(incoming, otherScopes) {
1779
1793
  const taken = new Set(otherScopes.map((s) => s.id));
1780
1794
  if (incoming.some((s) => taken.has(s.id))) throw new ProviderError("A compute server id is already in use", 409);
1781
1795
  }
1782
- /** SELVA_AT_REST_KEY_PREVIOUS, while within its deadline. */
1783
- function previousAtRestKey(env) {
1784
- const key = previousKey(env, "SELVA_AT_REST_KEY").key;
1785
- return key ? decodeSecretKey(key) : void 0;
1786
- }
1796
+ var bindingOf$1 = (s) => ({
1797
+ id: s.id,
1798
+ url: s.serverUrl
1799
+ });
1787
1800
  /**
1788
1801
  * Reads/writes compute.config.json, re-read on every call so edits take
1789
1802
  * effect without a restart. Mutation methods are scope-targeted
@@ -1795,8 +1808,8 @@ var LocalComputeServerStore = class LocalComputeServerStore {
1795
1808
  secretKey;
1796
1809
  static fromEnv(env, logger) {
1797
1810
  if (!env.DATA_PATH) throw new Error("Missing required env var: DATA_PATH");
1798
- if (!env.SELVA_AT_REST_KEY) throw new Error("Missing required env var: SELVA_AT_REST_KEY (32-byte hex or base64). Generate one with: node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"");
1799
- return new LocalComputeServerStore(path$1.join(env.DATA_PATH, "compute.config.json"), decodeSecretKey(env.SELVA_AT_REST_KEY), logger, previousAtRestKey(env));
1811
+ const keys = readAtRestKeys(env);
1812
+ return new LocalComputeServerStore(path$1.join(env.DATA_PATH, "compute.config.json"), keys.current, logger, keys.previous);
1800
1813
  }
1801
1814
  logger;
1802
1815
  /** Current key first; the previous one still opens rows sealed before a rotation. */
@@ -1834,7 +1847,7 @@ var LocalComputeServerStore = class LocalComputeServerStore {
1834
1847
  try {
1835
1848
  return {
1836
1849
  ...s,
1837
- apiKey: decryptWithKeys(s.apiKey, this.keys, s.id).plaintext
1850
+ apiKey: decryptWithKeys(s.apiKey, this.keys, bindingOf$1(s)).plaintext
1838
1851
  };
1839
1852
  } catch (cause) {
1840
1853
  this.logger.warn("Could not decrypt apiKey: the stored ciphertext does not match the current SELVA_AT_REST_KEY. This server is returned without an apiKey and solves against it will fail. Re-enter the key via /admin/compute, or restore the original SELVA_AT_REST_KEY.", {
@@ -1862,6 +1875,7 @@ var LocalComputeServerStore = class LocalComputeServerStore {
1862
1875
  const failures = [];
1863
1876
  let plaintextFound = false;
1864
1877
  let onPreviousKey = 0;
1878
+ let legacyEnvelopes = 0;
1865
1879
  for (const s of all.servers) {
1866
1880
  if (!s.apiKey) continue;
1867
1881
  if (!isEncryptedSecret(s.apiKey)) {
@@ -1873,8 +1887,9 @@ var LocalComputeServerStore = class LocalComputeServerStore {
1873
1887
  });
1874
1888
  continue;
1875
1889
  }
1890
+ if (isLegacyEnvelope(s.apiKey)) legacyEnvelopes += 1;
1876
1891
  try {
1877
- if (decryptWithKeys(s.apiKey, this.keys, s.id).keyIndex > 0) onPreviousKey += 1;
1892
+ if (decryptWithKeys(s.apiKey, this.keys, bindingOf$1(s)).keyIndex > 0) onPreviousKey += 1;
1878
1893
  } catch (cause) {
1879
1894
  failures.push({
1880
1895
  serverId: s.id,
@@ -1888,28 +1903,28 @@ var LocalComputeServerStore = class LocalComputeServerStore {
1888
1903
  ok: failures.length === 0,
1889
1904
  failures,
1890
1905
  plaintextFound,
1891
- ...this.keys.length > 1 ? { onPreviousKey } : {}
1906
+ ...this.keys.length > 1 ? { onPreviousKey } : {},
1907
+ ...legacyEnvelopes > 0 ? { legacyEnvelopes } : {}
1892
1908
  };
1893
1909
  }
1894
1910
  /**
1895
- * Re-seal every row that only the previous key opens, under the current one,
1896
- * so the previous key can be dropped. Under the file lock, so it can't
1897
- * interleave with an admin save. Returns how many rows it re-sealed.
1911
+ * Re-seal every row that only the previous key opens, or that sits in a legacy
1912
+ * envelope, under the current key and the row's binding. Under the file lock,
1913
+ * so it can't interleave with an admin save. Returns how many rows it re-sealed.
1898
1914
  */
1899
1915
  async reencryptSecrets() {
1900
- if (this.keys.length < 2) return 0;
1901
1916
  return withFileLock(this.configFilePath, async () => {
1902
1917
  const all = await this.readAll();
1903
1918
  let changed = 0;
1904
1919
  const servers = all.servers.map((s) => {
1905
1920
  if (!s.apiKey || !isEncryptedSecret(s.apiKey)) return s;
1906
1921
  try {
1907
- const { plaintext, keyIndex } = decryptWithKeys(s.apiKey, this.keys, s.id);
1908
- if (keyIndex === 0) return s;
1922
+ const { plaintext, keyIndex } = decryptWithKeys(s.apiKey, this.keys, bindingOf$1(s));
1923
+ if (keyIndex === 0 && !isLegacyEnvelope(s.apiKey)) return s;
1909
1924
  changed += 1;
1910
1925
  return {
1911
1926
  ...s,
1912
- apiKey: encryptSecret(plaintext, this.secretKey, s.id)
1927
+ apiKey: encryptSecret(plaintext, this.secretKey, bindingOf$1(s))
1913
1928
  };
1914
1929
  } catch {
1915
1930
  return s;
@@ -1927,7 +1942,7 @@ var LocalComputeServerStore = class LocalComputeServerStore {
1927
1942
  if (!s.apiKey) return s;
1928
1943
  return {
1929
1944
  ...s,
1930
- apiKey: encryptSecret(s.apiKey, this.secretKey, s.id)
1945
+ apiKey: encryptSecret(s.apiKey, this.secretKey, bindingOf$1(s))
1931
1946
  };
1932
1947
  });
1933
1948
  }
@@ -2884,8 +2899,8 @@ var LocalShareLinkStore = class LocalShareLinkStore {
2884
2899
  this.events = opts.events ?? new NoopEventSink();
2885
2900
  }
2886
2901
  /**
2887
- * Wires the definition store so token resolution can check the parent
2888
- * definition's `deletedAt`, mirroring the JOIN Supabase does. Optional: if
2902
+ * Wires the definition store so token resolution and solve counting can check
2903
+ * the parent definition's `deletedAt`, as Supabase does in SQL. Optional: if
2889
2904
  * unset, this falls back to the local-only revoke check, and the selva
2890
2905
  * app's route layer does the parent lookup as a safety net either way.
2891
2906
  */
@@ -2967,16 +2982,18 @@ var LocalShareLinkStore = class LocalShareLinkStore {
2967
2982
  const all = await this.readAll();
2968
2983
  const found = Object.values(all.links).find((l) => l.tokenHash === tokenHash);
2969
2984
  if (!this.isLive(found)) return null;
2970
- if (this.definitionProvider) {
2971
- if (!await this.definitionProvider.get(SYSTEM_CONTEXT, found.definitionId)) return null;
2972
- }
2973
- return found;
2985
+ return await this.parentIsLive(found) ? found : null;
2986
+ }
2987
+ async parentIsLive(link) {
2988
+ if (!this.definitionProvider) return true;
2989
+ return await this.definitionProvider.get(SYSTEM_CONTEXT, link.definitionId) !== null;
2974
2990
  }
2975
2991
  async revoke(ctx, id) {
2976
2992
  if (!await this.locked(async () => {
2977
2993
  const all = await this.readAll();
2978
2994
  const l = all.links[id];
2979
- if (!l || !this.isLive(l)) return false;
2995
+ if (!l) throw new ProviderError(`Share link '${id}' not found`, 404);
2996
+ if (!this.isLive(l)) return false;
2980
2997
  l.revokedAt = (/* @__PURE__ */ new Date()).toISOString();
2981
2998
  await this.writeAll(all);
2982
2999
  return true;
@@ -2993,6 +3010,7 @@ var LocalShareLinkStore = class LocalShareLinkStore {
2993
3010
  const l = all.links[id];
2994
3011
  if (!l || !this.isLive(l)) return null;
2995
3012
  if (l.maxSolves != null && l.solveCount >= l.maxSolves) return null;
3013
+ if (!await this.parentIsLive(l)) return null;
2996
3014
  l.solveCount += 1;
2997
3015
  await this.writeAll(all);
2998
3016
  return l.solveCount;
@@ -3420,8 +3438,8 @@ var LocalStorageProvider = class LocalStorageProvider {
3420
3438
  resolvePath(storagePath) {
3421
3439
  const base = path$1.resolve(this.basePath);
3422
3440
  const full = path$1.resolve(base, storagePath);
3423
- if (full !== base && !full.startsWith(base + path$1.sep)) throw new Error(`Path escapes base: ${storagePath}`);
3424
- if (path$1.dirname(full) === base && full.endsWith(".json")) throw new Error(`Path is a data file, not an asset: ${storagePath}`);
3441
+ if (full !== base && !full.startsWith(base + path$1.sep)) throw new ProviderError(`Path escapes base: ${storagePath}`, 400);
3442
+ if (path$1.dirname(full) === base && full.endsWith(".json")) throw new ProviderError(`Path is a data file, not an asset: ${storagePath}`, 400);
3425
3443
  return full;
3426
3444
  }
3427
3445
  async get(storagePath) {
@@ -3456,7 +3474,7 @@ var LocalStorageProvider = class LocalStorageProvider {
3456
3474
  }
3457
3475
  async deletePrefix(prefix) {
3458
3476
  const fullPath = this.resolvePath(prefix);
3459
- if (fullPath === path$1.resolve(this.basePath)) throw new Error(`Refusing to delete the whole store: ${JSON.stringify(prefix)}`);
3477
+ if (fullPath === path$1.resolve(this.basePath)) throw new ProviderError(`Refusing to delete the whole store: ${JSON.stringify(prefix)}`, 400);
3460
3478
  await fs$1.rm(fullPath, {
3461
3479
  recursive: true,
3462
3480
  force: true
@@ -3466,12 +3484,6 @@ var LocalStorageProvider = class LocalStorageProvider {
3466
3484
  return `${this.publicUrlBase}/${storagePath}`;
3467
3485
  }
3468
3486
  };
3469
- // ../providers/supabase/src/trim.ts
3470
- function trimTrailing(s, ch) {
3471
- let end = s.length;
3472
- while (end > 0 && s[end - 1] === ch) end--;
3473
- return s.slice(0, end);
3474
- }
3475
3487
  // ../providers/supabase/src/storage/SupabaseStorageProvider.ts
3476
3488
  var LIST_PAGE_SIZE = 1e3;
3477
3489
  var SupabaseStorageProvider = class SupabaseStorageProvider {
@@ -3541,7 +3553,7 @@ var SupabaseStorageProvider = class SupabaseStorageProvider {
3541
3553
  if (error) throw error;
3542
3554
  }
3543
3555
  async deletePrefix(prefix) {
3544
- if (trimTrailing(prefix, "/") === "") throw new Error(`Refusing to delete the whole store: prefix ${JSON.stringify(prefix)}`);
3556
+ if (trimTrailing(prefix, "/") === "") throw new ProviderError(`Refusing to delete the whole store: prefix ${JSON.stringify(prefix)}`, 400);
3545
3557
  await Promise.all([this.deletePrefixInBucket(this.publicBucket, prefix), this.deletePrefixInBucket(this.privateBucket, prefix)]);
3546
3558
  }
3547
3559
  async deletePrefixInBucket(bucket, prefix) {
@@ -4245,8 +4257,9 @@ var SupabaseDefinitionStore = class {
4245
4257
  if (!data || data.length === 0) throw new ProviderError(`Definition '${guid}' not found`, 404);
4246
4258
  }
4247
4259
  async delete(ctx, guid) {
4248
- const { error } = await this.clients.forRequest(ctx).from("definitions").update(stampSoftDelete(ctx)).eq("guid", guid).is("deleted_at", null);
4260
+ const { data, error } = await this.clients.forRequest(ctx).from("definitions").update(stampSoftDelete(ctx)).eq("guid", guid).is("deleted_at", null).select("guid");
4249
4261
  if (error) throw mapPostgrestError(error);
4262
+ if (!data || data.length === 0) return;
4250
4263
  await this.events.emit({
4251
4264
  type: "definition.deleted",
4252
4265
  definitionId: guid,
@@ -4517,10 +4530,11 @@ var SupabaseInviteStore = class {
4517
4530
  };
4518
4531
  }
4519
4532
  async markAccepted(ctx, id, userId) {
4533
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4520
4534
  const { data, error } = await this.clients.forRequest(ctx).from("invites").update({
4521
- accepted_at: (/* @__PURE__ */ new Date()).toISOString(),
4535
+ accepted_at: now,
4522
4536
  accepted_by_user_id: userId
4523
- }).eq("id", id).is("accepted_at", null).select("org_id");
4537
+ }).eq("id", id).is("accepted_at", null).gt("expires_at", now).select("org_id");
4524
4538
  if (error) throw mapPostgrestError(error);
4525
4539
  const row = data?.[0];
4526
4540
  if (!row) return false;
@@ -4533,6 +4547,14 @@ var SupabaseInviteStore = class {
4533
4547
  });
4534
4548
  return true;
4535
4549
  }
4550
+ async reopen(ctx, id, userId) {
4551
+ const { data, error } = await this.clients.forRequest(ctx).from("invites").update({
4552
+ accepted_at: null,
4553
+ accepted_by_user_id: null
4554
+ }).eq("id", id).eq("accepted_by_user_id", userId).select("id");
4555
+ if (error) throw mapPostgrestError(error);
4556
+ return (data?.length ?? 0) > 0;
4557
+ }
4536
4558
  async revoke(ctx, id) {
4537
4559
  const { data, error } = await this.clients.forRequest(ctx).from("invites").delete().eq("id", id).is("accepted_at", null).select("org_id");
4538
4560
  if (error) throw mapPostgrestError(error);
@@ -4598,6 +4620,10 @@ function inviteToRow(i) {
4598
4620
  var SERVER_COLUMNS = "id, scope, owner_org_id, shared_with_all, label, server_url, has_api_key";
4599
4621
  var SHARE_COLUMNS = "server_id, org_id";
4600
4622
  var ORG_DEFAULT_COLUMNS = "org_id, default_server_id";
4623
+ var bindingOf = (row) => ({
4624
+ id: row.id,
4625
+ url: row.server_url
4626
+ });
4601
4627
  /**
4602
4628
  * Compute-server config backed by three tables:
4603
4629
  * - `compute_servers`: one row per server. `scope = 'platform' | 'org'`.
@@ -4669,7 +4695,7 @@ var SupabaseComputeServerStore = class {
4669
4695
  const { data: visible, error: visibleError } = await this.clients.forRequest(ctx).from("compute_servers").select("id").eq("id", serverId).maybeSingle();
4670
4696
  if (visibleError) throw mapPostgrestError(visibleError);
4671
4697
  if (!visible) return void 0;
4672
- const { data, error } = await this.clients.serviceClient.from("compute_servers").select("id, label, api_key").eq("id", serverId).maybeSingle();
4698
+ const { data, error } = await this.clients.serviceClient.from("compute_servers").select("id, label, server_url, api_key").eq("id", serverId).maybeSingle();
4673
4699
  if (error) throw mapPostgrestError(error);
4674
4700
  if (!data) return void 0;
4675
4701
  return this.decryptRowApiKey(data).api_key ?? void 0;
@@ -4734,16 +4760,19 @@ var SupabaseComputeServerStore = class {
4734
4760
  if (shErr) throw mapPostgrestError(shErr);
4735
4761
  }
4736
4762
  /**
4737
- * Encrypt a server's `apiKey` before it is written to the DB, bound to its id.
4738
- * Throws on a value that is already an envelope, and if the store was built
4739
- * without a key, so we never silently persist plaintext.
4763
+ * Encrypt a server's `apiKey` before it is written to the DB, bound to its id
4764
+ * and URL. Throws on a value that is already an envelope, and if the store was
4765
+ * built without a key, so we never silently persist plaintext.
4740
4766
  */
4741
4767
  encryptServerApiKey(s) {
4742
4768
  if (!s.apiKey) return s;
4743
4769
  if (!this.secretKey) throw new Error("Cannot store a compute-server apiKey: SELVA_AT_REST_KEY is not configured. Set it so secrets are encrypted at rest.");
4744
4770
  return {
4745
4771
  ...s,
4746
- apiKey: encryptSecret(s.apiKey, this.secretKey, s.id)
4772
+ apiKey: encryptSecret(s.apiKey, this.secretKey, {
4773
+ id: s.id,
4774
+ url: s.serverUrl
4775
+ })
4747
4776
  };
4748
4777
  }
4749
4778
  /**
@@ -4778,7 +4807,7 @@ var SupabaseComputeServerStore = class {
4778
4807
  try {
4779
4808
  return {
4780
4809
  ...row,
4781
- api_key: decryptWithKeys(row.api_key, this.keys, row.id).plaintext
4810
+ api_key: decryptWithKeys(row.api_key, this.keys, bindingOf(row)).plaintext
4782
4811
  };
4783
4812
  } catch (cause) {
4784
4813
  this.logger.warn("Could not decrypt api_key: the stored ciphertext does not match the current SELVA_AT_REST_KEY. This server is returned without an apiKey and solves against it will fail. Re-enter the key via /admin/compute, or restore the original SELVA_AT_REST_KEY", {
@@ -4800,15 +4829,14 @@ var SupabaseComputeServerStore = class {
4800
4829
  * report for boot health to drive `/api/health`.
4801
4830
  */
4802
4831
  async verifySecrets() {
4803
- const { data, error } = await this.clients.serviceClient.from("compute_servers").select("id, label, api_key");
4832
+ const { data, error } = await this.clients.serviceClient.from("compute_servers").select("id, label, server_url, api_key");
4804
4833
  if (error) throw mapPostgrestError(error);
4805
4834
  const failures = [];
4806
4835
  let plaintextFound = false;
4807
4836
  let onPreviousKey = 0;
4837
+ let legacyEnvelopes = 0;
4808
4838
  for (const row of data ?? []) {
4809
- const apiKey = row.api_key;
4810
- const id = row.id;
4811
- const label = row.label;
4839
+ const { api_key: apiKey, id, label } = row;
4812
4840
  if (!apiKey) continue;
4813
4841
  if (!isEncryptedSecret(apiKey)) {
4814
4842
  plaintextFound = true;
@@ -4828,8 +4856,9 @@ var SupabaseComputeServerStore = class {
4828
4856
  });
4829
4857
  continue;
4830
4858
  }
4859
+ if (isLegacyEnvelope(apiKey)) legacyEnvelopes += 1;
4831
4860
  try {
4832
- if (decryptWithKeys(apiKey, this.keys, id).keyIndex > 0) onPreviousKey += 1;
4861
+ if (decryptWithKeys(apiKey, this.keys, bindingOf(row)).keyIndex > 0) onPreviousKey += 1;
4833
4862
  } catch (cause) {
4834
4863
  failures.push({
4835
4864
  serverId: id,
@@ -4843,29 +4872,31 @@ var SupabaseComputeServerStore = class {
4843
4872
  ok: failures.length === 0,
4844
4873
  failures,
4845
4874
  plaintextFound,
4846
- ...this.keys.length > 1 ? { onPreviousKey } : {}
4875
+ ...this.keys.length > 1 ? { onPreviousKey } : {},
4876
+ ...legacyEnvelopes > 0 ? { legacyEnvelopes } : {}
4847
4877
  };
4848
4878
  }
4849
4879
  /**
4850
- * Re-seal under the current key every row only the previous key opens. The
4851
- * update matches on the old ciphertext too, so a row an admin re-saved in
4852
- * between is left alone rather than overwritten.
4880
+ * Re-seal, under the current key and the row's binding, every row only the
4881
+ * previous key opens or that sits in a legacy envelope. The update matches on
4882
+ * the old ciphertext and URL too, so a row an admin re-saved in between is
4883
+ * left alone rather than overwritten.
4853
4884
  */
4854
4885
  async reencryptSecrets() {
4855
- if (this.keys.length < 2 || !this.secretKey) return 0;
4856
- const { data, error } = await this.clients.serviceClient.from("compute_servers").select("id, api_key");
4886
+ if (!this.secretKey) return 0;
4887
+ const { data, error } = await this.clients.serviceClient.from("compute_servers").select("id, label, server_url, api_key");
4857
4888
  if (error) throw mapPostgrestError(error);
4858
4889
  let changed = 0;
4859
4890
  for (const row of data ?? []) {
4860
4891
  if (!row.api_key || !isEncryptedSecret(row.api_key)) continue;
4861
4892
  let opened;
4862
4893
  try {
4863
- opened = decryptWithKeys(row.api_key, this.keys, row.id);
4894
+ opened = decryptWithKeys(row.api_key, this.keys, bindingOf(row));
4864
4895
  } catch {
4865
4896
  continue;
4866
4897
  }
4867
- if (opened.keyIndex === 0) continue;
4868
- const { error: updateError, count } = await this.clients.serviceClient.from("compute_servers").update({ api_key: encryptSecret(opened.plaintext, this.secretKey, row.id) }, { count: "exact" }).eq("id", row.id).eq("api_key", row.api_key);
4898
+ if (opened.keyIndex === 0 && !isLegacyEnvelope(row.api_key)) continue;
4899
+ const { error: updateError, count } = await this.clients.serviceClient.from("compute_servers").update({ api_key: encryptSecret(opened.plaintext, this.secretKey, bindingOf(row)) }, { count: "exact" }).eq("id", row.id).eq("server_url", row.server_url).eq("api_key", row.api_key);
4869
4900
  if (updateError) throw mapPostgrestError(updateError);
4870
4901
  changed += count ?? 0;
4871
4902
  }
@@ -5180,7 +5211,7 @@ function tokenToRow(t) {
5180
5211
  * whenever a migration is added — `migration-head.test.ts` asserts it
5181
5212
  * matches the migrations directory, so CI catches drift.
5182
5213
  */
5183
- var EXPECTED_MIGRATION_HEAD = "20261101200000";
5214
+ var EXPECTED_MIGRATION_HEAD = "20261107120100";
5184
5215
  // ../providers/supabase/src/data/client.ts
5185
5216
  /** Default schema every engine store targets. */
5186
5217
  var DEFAULT_SCHEMA = "selva";
@@ -5447,8 +5478,6 @@ var SupabaseSolveMetricSink = class {
5447
5478
  }
5448
5479
  };
5449
5480
  // ../providers/supabase/src/data/SupabaseAuditQuery.ts
5450
- var MAX_LIMIT = 200;
5451
- var DEFAULT_LIMIT = 100;
5452
5481
  var ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})$/;
5453
5482
  var UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
5454
5483
  /**
@@ -5465,7 +5494,7 @@ var SupabaseAuditQuery = class {
5465
5494
  this.clients = clients;
5466
5495
  }
5467
5496
  async list(_ctx, filters) {
5468
- const limit = clampLimit(filters.limit);
5497
+ const limit = clampPageLimit(filters.limit);
5469
5498
  let q = this.clients.serviceClient.from("audit_events").select("id, type, actor_id, occurred_at, data").order("occurred_at", { ascending: false }).order("id", { ascending: false }).limit(limit + 1);
5470
5499
  if (filters.types && filters.types.length > 0) q = q.in("type", [...filters.types]);
5471
5500
  if (filters.actorId) q = q.eq("actor_id", filters.actorId);
@@ -5498,11 +5527,6 @@ var SupabaseAuditQuery = class {
5498
5527
  };
5499
5528
  }
5500
5529
  };
5501
- function clampLimit(requested) {
5502
- if (!requested || requested <= 0) return DEFAULT_LIMIT;
5503
- if (requested > MAX_LIMIT) return MAX_LIMIT;
5504
- return Math.max(1, Math.floor(requested));
5505
- }
5506
5530
  // ../providers/supabase/src/userProfile/SupabaseUserProfileProvider.ts
5507
5531
  /**
5508
5532
  * Backed by `public.user_profiles` (one row per `auth.users.id`), auto-seeded
@@ -5687,6 +5711,7 @@ function mapError(e) {
5687
5711
  */
5688
5712
  var NOT_IMPLEMENTED_MSG = "Platform projects are not supported on this deployment yet.";
5689
5713
  var notImplementedGrantStore = {
5714
+ unsupported: true,
5690
5715
  listByProject: async () => {
5691
5716
  throw new ProviderError(NOT_IMPLEMENTED_MSG, 501);
5692
5717
  },
@@ -5741,10 +5766,8 @@ var SupabaseDataProvider = class SupabaseDataProvider {
5741
5766
  }
5742
5767
  static fromEnv(env, events, logger = new NoopLogger()) {
5743
5768
  const bundle = clientBundleFromEnv(env);
5744
- if (!env.SELVA_AT_REST_KEY) throw new Error("Missing required env var: SELVA_AT_REST_KEY (32-byte hex or base64). Required to encrypt compute-server API keys at rest. Generate one with: node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"");
5745
- const secretKey = decodeSecretKey(env.SELVA_AT_REST_KEY);
5746
- const previous = previousKey(env, "SELVA_AT_REST_KEY").key;
5747
- return new SupabaseDataProvider(bundle, events ?? new SupabaseEventSink(bundle, { logger }), secretKey, logger, previous ? decodeSecretKey(previous) : void 0);
5769
+ const keys = readAtRestKeys(env);
5770
+ return new SupabaseDataProvider(bundle, events ?? new SupabaseEventSink(bundle, { logger }), keys.current, logger, keys.previous);
5748
5771
  }
5749
5772
  static create(opts, events, secretKey, logger = new NoopLogger()) {
5750
5773
  const bundle = buildClientBundle(opts);
@@ -6268,10 +6291,11 @@ var SupabaseAuthProvider = class SupabaseAuthProvider {
6268
6291
  return this.hydrate(data.user);
6269
6292
  }
6270
6293
  async listUsers(opts) {
6271
- const perPage = opts?.limit ?? 50;
6272
- const page = opts?.cursor ? parseInt(opts.cursor, 10) : 1;
6294
+ const perPage = clampPageLimit(opts?.limit);
6295
+ const requested = opts?.cursor ? parseInt(opts.cursor, 10) : 1;
6296
+ const page = Number.isFinite(requested) && requested >= 1 ? requested : 1;
6273
6297
  const { data, error } = await this.admin.auth.admin.listUsers({
6274
- page: Number.isFinite(page) && page >= 1 ? page : 1,
6298
+ page,
6275
6299
  perPage
6276
6300
  });
6277
6301
  if (error) throw error;
@@ -6850,13 +6874,13 @@ var HeaderAuthProvider = class HeaderAuthProvider {
6850
6874
  }
6851
6875
  async listUsers(opts) {
6852
6876
  const all = await this.users.listUsers();
6853
- const limit = Math.min(Math.max(1, opts?.limit ?? 25), 200);
6854
- const offset = opts?.cursor ? parseInt(opts.cursor, 10) || 0 : 0;
6877
+ const limit = clampPageLimit(opts?.limit);
6878
+ const offset = decodeOffsetCursor(opts?.cursor);
6855
6879
  const slice = all.slice(offset, offset + limit).map(toAuthUser);
6856
6880
  const nextOffset = offset + slice.length;
6857
6881
  return {
6858
6882
  items: slice,
6859
- nextCursor: nextOffset < all.length ? String(nextOffset) : void 0
6883
+ nextCursor: nextOffset < all.length ? encodeOffsetCursor(nextOffset) : void 0
6860
6884
  };
6861
6885
  }
6862
6886
  /**
@@ -34567,27 +34591,43 @@ function createSolveCacheSingleFlight(options = {}) {
34567
34591
  };
34568
34592
  }
34569
34593
  /**
34570
- * What `SolveEngine.solve` takes as `inputs`, from a schema the host stored. The bounds live on
34571
- * the number widgets in the layout, not on `schema.inputs`, so without them nothing clamps.
34594
+ * What `SolveEngine.solve` takes as `inputs`, from a schema the host stored. The layout, not
34595
+ * `schema.inputs`, carries the number widgets' bounds and each input's source: without this,
34596
+ * nothing clamps and a `server` input takes the caller's value.
34572
34597
  */
34573
34598
  function solveInputsFromSchema(schema) {
34574
34599
  const bounds = /* @__PURE__ */ new Map();
34575
34600
  for (const item of getInputItems(schema)) if (item.widgetType === "number" && item.config) bounds.set(item.paramId, item.config);
34601
+ const serverSourced = serverSourcedInputIds(schema);
34576
34602
  return schema.inputs.map((input) => {
34577
34603
  const widget = bounds.get(input.id);
34578
- return widget ? {
34604
+ if (!widget && !serverSourced.has(input.id)) return input;
34605
+ return {
34579
34606
  ...input,
34580
- minimum: widget.minimum,
34581
- maximum: widget.maximum
34582
- } : input;
34607
+ ...widget ? {
34608
+ minimum: widget.minimum,
34609
+ maximum: widget.maximum
34610
+ } : {},
34611
+ ...serverSourced.has(input.id) ? { serverSourced: true } : {}
34612
+ };
34583
34613
  });
34584
34614
  }
34585
- /** The input tree a solve sends: each input's value, or its schema default when it has none. */
34615
+ /**
34616
+ * Ids in `values` that set a server-sourced input. A host refuses a request carrying any: the
34617
+ * input tree would ignore them, and the caller should hear so rather than solve on the default.
34618
+ */
34619
+ function postedServerSourcedIds(inputs, values) {
34620
+ return inputs.filter((input) => input.serverSourced && Object.hasOwn(values, input.id)).map((input) => input.id);
34621
+ }
34622
+ /**
34623
+ * The input tree a solve sends: each input's value, or its schema default when it has none. A
34624
+ * server-sourced input always takes its default.
34625
+ */
34586
34626
  function buildSolveInputTree(inputs, values) {
34587
34627
  return TreeBuilder.fromValues(inputs.filter((input) => input.paramType).map((input) => ({
34588
34628
  paramName: input.nickname,
34589
34629
  paramType: input.paramType,
34590
- value: (Object.hasOwn(values, input.id) ? values[input.id] : void 0) ?? input.default,
34630
+ value: (!input.serverSourced && Object.hasOwn(values, input.id) ? values[input.id] : void 0) ?? input.default,
34591
34631
  minimum: input.minimum,
34592
34632
  maximum: input.maximum
34593
34633
  })));
@@ -35182,6 +35222,325 @@ var SmtpNotificationProvider = class {
35182
35222
  }
35183
35223
  }
35184
35224
  };
35225
+ // ../providers/header-auth/src/config.ts
35226
+ var header = (key, fallback, slot) => defineSetting({
35227
+ key,
35228
+ label: `${slot[0].toUpperCase()}${slot.slice(1)} header`,
35229
+ type: "string",
35230
+ default: fallback,
35231
+ onInvalid: "fail",
35232
+ class: "bootstrap",
35233
+ description: `Header the proxy puts the user's ${slot} in.`,
35234
+ impact: "A name the proxy never sends signs nobody in. Override all three or none."
35235
+ });
35236
+ var HEADER_AUTH_SETTINGS = composeManifest([
35237
+ defineSetting({
35238
+ key: "HEADER_AUTH_DATA_DIR",
35239
+ label: "Allowlist folder",
35240
+ type: "string",
35241
+ onInvalid: "fail",
35242
+ class: "bootstrap",
35243
+ description: "Directory holding header-allowlist.json. Falls back to DATA_PATH."
35244
+ }),
35245
+ header("HEADER_AUTH_UPN_HEADER", "SELVA-UserPrincipalName", "UPN"),
35246
+ header("HEADER_AUTH_EMAIL_HEADER", "SELVA-Email", "email"),
35247
+ header("HEADER_AUTH_DISPLAY_NAME_HEADER", "SELVA-DisplayName", "display name")
35248
+ ]);
35249
+ // ../providers/local/src/config.ts
35250
+ var LOCAL_SETTINGS = composeManifest([defineSetting({
35251
+ key: "DATA_PATH",
35252
+ label: "Data folder",
35253
+ type: "string",
35254
+ required: true,
35255
+ onInvalid: "fail",
35256
+ class: "bootstrap",
35257
+ summary: true,
35258
+ description: "Folder on this server holding users, orgs, projects and uploads. Back it up.",
35259
+ impact: "Pointing it elsewhere starts an empty instance; the old data stays where it was."
35260
+ })]);
35261
+ // src/lib/server/config/settings.ts
35262
+ var COMPUTE_DEBUG = defineSetting({
35263
+ key: "SELVA_FLAG_COMPUTE_DEBUG",
35264
+ label: "Compute debug logging",
35265
+ type: "string",
35266
+ default: "off",
35267
+ onInvalid: "default",
35268
+ class: "setting",
35269
+ description: "off, on (cache and timing lines per solve) or verbose (adds Compute’s raw error bodies).",
35270
+ impact: "verbose can write what was solved to the log, which erasure cannot reach."
35271
+ });
35272
+ /** `SELVA_FLAG_COMPUTE_DEBUG`: `verbose`, or on and off in the manifest's boolean words. */
35273
+ function computeDebugMode(env) {
35274
+ if (readSetting(COMPUTE_DEBUG, env).toLowerCase() === "verbose") return "verbose";
35275
+ return readSetting({
35276
+ ...COMPUTE_DEBUG,
35277
+ type: "bool",
35278
+ default: false
35279
+ }, env) ? "on" : "off";
35280
+ }
35281
+ /** Keys only this app reads. adapter-node's own keys are here too: they decide whether it works. */
35282
+ var APP_SETTINGS = composeManifest([
35283
+ defineSetting({
35284
+ key: "ORIGIN",
35285
+ label: "Public address",
35286
+ type: "url",
35287
+ origin: true,
35288
+ onInvalid: "fail",
35289
+ class: "bootstrap",
35290
+ summary: true,
35291
+ description: "The URL people use to reach Selva, such as https://selva.example.com.",
35292
+ impact: "Wrong or unset behind a proxy: form posts fail the CSRF check and invite links carry an internal host."
35293
+ }),
35294
+ defineSetting({
35295
+ key: "PORT",
35296
+ label: "Port",
35297
+ type: "int",
35298
+ min: 1,
35299
+ max: 65535,
35300
+ default: 3e3,
35301
+ onInvalid: "fail",
35302
+ class: "bootstrap",
35303
+ description: "Port the app listens on."
35304
+ }),
35305
+ defineSetting({
35306
+ key: "HOST",
35307
+ label: "Listen address",
35308
+ type: "string",
35309
+ default: "0.0.0.0",
35310
+ onInvalid: "fail",
35311
+ class: "bootstrap",
35312
+ summary: true,
35313
+ description: "Which network address the app accepts connections on. 127.0.0.1 when a proxy sits in front.",
35314
+ impact: "Under header auth, anything that reaches the port directly can claim to be any user."
35315
+ }),
35316
+ defineSetting({
35317
+ key: "BODY_SIZE_LIMIT",
35318
+ label: "Max request size",
35319
+ type: "string",
35320
+ default: "512K",
35321
+ onInvalid: "fail",
35322
+ class: "bootstrap",
35323
+ summary: true,
35324
+ description: "Largest request the server accepts at all, uploads included (K, M or G suffix).",
35325
+ impact: "Below COMPUTE_REQUEST_MAX_BYTES, uploads and file inputs fail with 413."
35326
+ }),
35327
+ defineSetting({
35328
+ key: "ADDRESS_HEADER",
35329
+ label: "Visitor IP header",
35330
+ type: "string",
35331
+ onInvalid: "fail",
35332
+ class: "bootstrap",
35333
+ summary: true,
35334
+ description: "Header your proxy uses to pass on the visitor’s IP address. Usually X-Forwarded-For.",
35335
+ impact: "Unset behind a proxy: every client shares one rate-limit bucket."
35336
+ }),
35337
+ defineSetting({
35338
+ key: "XFF_DEPTH",
35339
+ label: "Proxies in front",
35340
+ type: "int",
35341
+ min: 1,
35342
+ onInvalid: "fail",
35343
+ class: "bootstrap",
35344
+ summary: true,
35345
+ description: "How many proxies sit between visitors and the app. Usually 1."
35346
+ }),
35347
+ defineSetting({
35348
+ key: "PROTOCOL_HEADER",
35349
+ label: "Protocol header",
35350
+ type: "string",
35351
+ onInvalid: "fail",
35352
+ class: "bootstrap",
35353
+ description: "Header carrying the original protocol, when ORIGIN is unset."
35354
+ }),
35355
+ defineSetting({
35356
+ key: "HOST_HEADER",
35357
+ label: "Host header",
35358
+ type: "string",
35359
+ onInvalid: "fail",
35360
+ class: "bootstrap",
35361
+ description: "Header carrying the original host, when ORIGIN is unset."
35362
+ }),
35363
+ defineSetting({
35364
+ key: "NODE_ENV",
35365
+ label: "Run mode",
35366
+ type: "string",
35367
+ onInvalid: "fail",
35368
+ class: "bootstrap",
35369
+ description: "production in deployments: hides stack traces and makes cookies Secure."
35370
+ }),
35371
+ defineSetting({
35372
+ key: "ALLOW_INSECURE_COOKIES",
35373
+ label: "Allow sign-in over http",
35374
+ type: "bool",
35375
+ default: false,
35376
+ onInvalid: "fail",
35377
+ class: "bootstrap",
35378
+ description: "Drop the Secure cookie flag so sign-in works over plain http.",
35379
+ legacy: { bool: "exact-true" }
35380
+ }),
35381
+ defineSetting({
35382
+ key: "INSTALL_DIR",
35383
+ label: "Install folder",
35384
+ type: "string",
35385
+ onInvalid: "fail",
35386
+ class: "bootstrap",
35387
+ description: "Deployment directory the admin updater runs in. Defaults to the working directory."
35388
+ }),
35389
+ defineSetting({
35390
+ key: "SELVA_EVENT_CALLBACK_ORIGIN",
35391
+ label: "Solve event callback address",
35392
+ type: "url",
35393
+ origin: true,
35394
+ onInvalid: "fail",
35395
+ class: "bootstrap",
35396
+ description: "Origin Rhino.Compute posts live solve events to, when it differs from the browser’s."
35397
+ }),
35398
+ defineSetting({
35399
+ key: "MCP_ALLOWED_ORIGINS",
35400
+ label: "Extra MCP origins",
35401
+ type: "list",
35402
+ default: [],
35403
+ onInvalid: "fail",
35404
+ class: "setting",
35405
+ description: "Browser origins /mcp accepts besides its own."
35406
+ }),
35407
+ defineSetting({
35408
+ key: "LOG_LEVEL",
35409
+ label: "Log level",
35410
+ type: "enum",
35411
+ values: [
35412
+ "debug",
35413
+ "info",
35414
+ "warn",
35415
+ "error"
35416
+ ],
35417
+ onInvalid: "default",
35418
+ class: "setting",
35419
+ description: "Lowest severity written to the log. Default info (debug in development)."
35420
+ }),
35421
+ COMPUTE_DEBUG,
35422
+ defineSetting({
35423
+ key: "SENTRY_DSN",
35424
+ label: "Sentry error reporting",
35425
+ type: "url",
35426
+ onInvalid: "fail",
35427
+ class: "secret",
35428
+ sensitive: true,
35429
+ description: "Ship unexpected server errors to Sentry, scrubbed of cookies, auth headers, bodies and query strings."
35430
+ }),
35431
+ defineSetting({
35432
+ key: "SENTRY_TRACES_SAMPLE_RATE",
35433
+ label: "Sentry trace sampling",
35434
+ type: "string",
35435
+ default: "0",
35436
+ onInvalid: "default",
35437
+ class: "tunable",
35438
+ description: "Share of requests traced to Sentry, 0–1 (out of range is clamped). 0 sends errors only."
35439
+ }),
35440
+ defineSetting({
35441
+ key: "SELVA_RELEASE",
35442
+ label: "Release tag",
35443
+ type: "string",
35444
+ onInvalid: "fail",
35445
+ class: "tunable",
35446
+ description: "Release tag on Sentry events and log records."
35447
+ })
35448
+ ]);
35449
+ /** Prefixes whose undeclared keys are reported as unknown (likely typos). */
35450
+ var WATCHED_PREFIXES = [
35451
+ "SELVA_",
35452
+ "SUPABASE_",
35453
+ "COMPUTE_",
35454
+ "SMTP_",
35455
+ "HEADER_AUTH_",
35456
+ "API_TOKEN_",
35457
+ "MAX_",
35458
+ "REMOTE_DEFINITION_",
35459
+ "SIGN_IN_",
35460
+ "BOOTSTRAP_"
35461
+ ];
35462
+ /** Read by tooling, not by the app: not unknown, not reported. */
35463
+ var EXTERNAL_KEYS = ["SELVA_REQUIRE_SUPABASE"];
35464
+ /**
35465
+ * Keys no release reads any more, with what took their place. Boot and doctor
35466
+ * name them instead of calling them typos; `selva migrate` removes them.
35467
+ */
35468
+ var RETIRED_KEYS = {
35469
+ SELVA_FLAG_COMPUTE_DEBUG_VERBOSE: "use SELVA_FLAG_COMPUTE_DEBUG=verbose",
35470
+ COMPUTE_RATE_LIMIT_WINDOW_MS: "fixed at 100 s",
35471
+ API_TOKEN_RATE_LIMIT_WINDOW_MS: "fixed at 60 s",
35472
+ MAX_IMAGE_FILE_SIZE_BYTES: "fixed at 10 MB",
35473
+ COMPUTE_REQUEST_MAX_BYTES: "fixed at 256 MB",
35474
+ COMPUTE_RESPONSE_MAX_BYTES: "fixed at 300 MB",
35475
+ REMOTE_DEFINITION_FETCH_TIMEOUT_MS: "fixed at 30 s",
35476
+ REMOTE_DEFINITION_CACHE_TTL_MS: "fixed at 5 min",
35477
+ DEFINITION_CACHE_TTL_MS: "fixed at 5 min",
35478
+ SUPABASE_TOKEN_VERIFICATION: "always hybrid",
35479
+ SUPABASE_REVALIDATE_MS: "fixed at 60 s",
35480
+ SUPABASE_PRIVATE_URL_PREFIX: "fixed at /api/files",
35481
+ COMPUTE_SOLVE_DEADLINE_MS: "set --timeout (RHINO_COMPUTE_TIMEOUT) on the compute server",
35482
+ MAX_SOLVE_DURATION_MS: "set --timeout (RHINO_COMPUTE_TIMEOUT) on the compute server",
35483
+ COMPUTE_REUSE_DEFINITION_CACHE: "on whenever the compute server reports /limits",
35484
+ COMPUTE_CACHE_ERRORED_SOLVES: "removed"
35485
+ };
35486
+ /**
35487
+ * The manifest for this deployment: engine and app keys, plus the slices of
35488
+ * the providers it selects. A provider's required keys only apply when it is
35489
+ * in use, so slices are chosen here rather than all composed at once.
35490
+ */
35491
+ function deploymentManifest(env) {
35492
+ const chosen = new Set([
35493
+ "SELVA_AUTH_PROVIDER",
35494
+ "SELVA_DATA_PROVIDER",
35495
+ "SELVA_STORAGE_PROVIDER"
35496
+ ].map((k) => (env[k] ?? "local").toLowerCase()));
35497
+ return composeManifest([
35498
+ ENGINE_SETTINGS,
35499
+ APP_SETTINGS,
35500
+ ...chosen.has("local") ? [LOCAL_SETTINGS] : [],
35501
+ ...chosen.has("supabase") ? [SUPABASE_SETTINGS] : [],
35502
+ ...chosen.has("header") ? [HEADER_AUTH_SETTINGS] : []
35503
+ ]);
35504
+ }
35505
+ /** Every key any slice declares, whichever providers are chosen. */
35506
+ var ALL_SETTINGS = composeManifest([
35507
+ ENGINE_SETTINGS,
35508
+ APP_SETTINGS,
35509
+ LOCAL_SETTINGS,
35510
+ SUPABASE_SETTINGS,
35511
+ HEADER_AUTH_SETTINGS
35512
+ ]);
35513
+ /** The report for this deployment. Keys of providers it doesn't use are known, not typos. */
35514
+ function deploymentReport(env) {
35515
+ const manifest = deploymentManifest(env);
35516
+ const active = new Set(manifest.flatMap((s) => [s.key, ...s.aliases ?? []]));
35517
+ const inactive = ALL_SETTINGS.flatMap((s) => [s.key, ...s.aliases ?? []]).filter((k) => !active.has(k));
35518
+ return buildConfigReport(manifest, env, {
35519
+ prefixes: WATCHED_PREFIXES,
35520
+ external: [
35521
+ ...EXTERNAL_KEYS,
35522
+ ...Object.keys(RETIRED_KEYS),
35523
+ ...inactive
35524
+ ]
35525
+ });
35526
+ }
35527
+ var NOT_FROM_ENV_FILE = /* @__PURE__ */ new Set(["NODE_ENV"]);
35528
+ /** What the boot snapshot and the CLI's drift check compare. */
35529
+ function deploymentSnapshot(env, salt) {
35530
+ return takeSnapshot(deploymentManifest(env).filter((s) => !NOT_FROM_ENV_FILE.has(s.key)), env, salt);
35531
+ }
35532
+ /** The rotation overlap of each root key: what the admin page and doctor count down. */
35533
+ function keyRotationStatus(env, now = Date.now()) {
35534
+ return ["SELVA_HMAC_KEY", "SELVA_AT_REST_KEY"].map((key) => {
35535
+ const p = previousKey(env, key, now);
35536
+ return {
35537
+ key,
35538
+ state: p.state,
35539
+ ..."expires" in p ? { expires: p.expires } : {},
35540
+ ..."daysLeft" in p ? { daysLeft: p.daysLeft } : {}
35541
+ };
35542
+ });
35543
+ }
35185
35544
  // src/lib/server/providers.server.ts
35186
35545
  var lazyLogger = {
35187
35546
  debug: (m, f) => getLogger().debug(m, f),
@@ -35305,13 +35664,7 @@ function getNotificationProvider() {
35305
35664
  function parseLogLevel(raw) {
35306
35665
  const value = raw?.trim().toLowerCase();
35307
35666
  if (value === "debug" || value === "info" || value === "warn" || value === "error") return value;
35308
- if ([
35309
- "true",
35310
- "1",
35311
- "yes",
35312
- "on",
35313
- "verbose"
35314
- ].includes((env.SELVA_FLAG_COMPUTE_DEBUG ?? "").toLowerCase())) return "debug";
35667
+ if (computeDebugMode(env) !== "off") return "debug";
35315
35668
  return env.NODE_ENV === "development" ? "debug" : "info";
35316
35669
  }
35317
35670
  createLogger({
@@ -35360,6 +35713,6 @@ if (!globalThis[ERROR_HOOKS_FLAG]) {
35360
35713
  getErrorReporter().capture(error, { tags: { origin: "uncaughtException" } });
35361
35714
  });
35362
35715
  }
35363
- export { SUPABASE_SETTINGS as A, DefinitionChannelSchema as B, getUserProfileStore as C, SolveEngine as D, MAX_SOLVE_DEADLINE_MS as E, orgPaths as F, definitionPaths as G, PublishVersionInputSchema as H, NoopEventSink as I, defineSetting as J, resolveConfig as K, actorFrom as L, isEncryptedSecret as M, emptyProfile as N, acceptsGzip as O, classifyAssetPath as P, actorOf as R, getTenancy as S, providers as T, UpdateMetadataInputSchema as U, GuidSchema as V, toSourceDocumentId as W, getPlatformProjectGrantStore as _, getComputeServerConfigStore as a, getSolveMetricSink as b, getDefinitionService as c, getInviteStore as d, getLogger as f, getPermissionStore as g, getOrganizationProvider as h, getBranding as i, LocalComputeServerStore as j, solveInputsFromSchema as k, getErrorReporter as l, getOrgAssetService as m, getAuditQuery as n, getDataProvider as o, getNotificationProvider as p, composeManifest as q, getAuthProvider as r, getDefinitionMeta as s, flag as t, getEventSink as u, getProjectProvider as v, lazyLogger as w, getStorageProvider as x, getShareLinkStore as y, CreateDefinitionInputSchema as z };
35716
+ export { deploymentSnapshot as A, classifyAssetPath as B, getUserProfileStore as C, computeDebugMode as D, RETIRED_KEYS as E, postedServerSourcedIds as F, definitionPaths as G, NoopEventSink as H, solveInputsFromSchema as I, diffSnapshots as K, LocalComputeServerStore as L, MAX_SOLVE_DEADLINE_MS as M, SolveEngine as N, deploymentManifest as O, acceptsGzip as P, isEncryptedSecret as R, getTenancy as S, providers as T, actorFrom as U, orgPaths as V, actorOf as W, getPlatformProjectGrantStore as _, getComputeServerConfigStore as a, getSolveMetricSink as b, getDefinitionService as c, getInviteStore as d, getLogger as f, getPermissionStore as g, getOrganizationProvider as h, getBranding as i, keyRotationStatus as j, deploymentReport as k, getErrorReporter as l, getOrgAssetService as m, getAuditQuery as n, getDataProvider as o, getNotificationProvider as p, getAuthProvider as r, getDefinitionMeta as s, flag as t, getEventSink as u, getProjectProvider as v, lazyLogger as w, getStorageProvider as x, getShareLinkStore as y, emptyProfile as z };
35364
35717
 
35365
35718
  //# sourceMappingURL=providers.server.js.map