@thebriangao/totem 1.4.4

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 (405) hide show
  1. package/.dockerignore +23 -0
  2. package/.env.example +66 -0
  3. package/CHANGELOG.md +283 -0
  4. package/CONTRIBUTING.md +149 -0
  5. package/Dockerfile +53 -0
  6. package/LICENSE +37 -0
  7. package/README.md +587 -0
  8. package/SECURITY.md +79 -0
  9. package/TOOLS.md +429 -0
  10. package/WHOOP.md +2673 -0
  11. package/assets/banner.svg +38 -0
  12. package/dist/cli/index.js +589 -0
  13. package/dist/cli/index.js.map +1 -0
  14. package/dist/cli/setup.js +1127 -0
  15. package/dist/cli/setup.js.map +1 -0
  16. package/dist/cli/ui.js +512 -0
  17. package/dist/cli/ui.js.map +1 -0
  18. package/dist/cli/update.js +465 -0
  19. package/dist/cli/update.js.map +1 -0
  20. package/dist/data/behaviors.js +2777 -0
  21. package/dist/data/behaviors.js.map +1 -0
  22. package/dist/data/endpoints.js +320 -0
  23. package/dist/data/endpoints.js.map +1 -0
  24. package/dist/data/exercises.js +4863 -0
  25. package/dist/data/exercises.js.map +1 -0
  26. package/dist/data/sports.js +212 -0
  27. package/dist/data/sports.js.map +1 -0
  28. package/dist/lib/concurrency.js +27 -0
  29. package/dist/lib/concurrency.js.map +1 -0
  30. package/dist/lib/dates.js +29 -0
  31. package/dist/lib/dates.js.map +1 -0
  32. package/dist/lib/format.js +22 -0
  33. package/dist/lib/format.js.map +1 -0
  34. package/dist/lib/stats.js +32 -0
  35. package/dist/lib/stats.js.map +1 -0
  36. package/dist/lib/timezone.js +249 -0
  37. package/dist/lib/timezone.js.map +1 -0
  38. package/dist/lib/walk.js +396 -0
  39. package/dist/lib/walk.js.map +1 -0
  40. package/dist/projections/behavior_impact.js +96 -0
  41. package/dist/projections/behavior_impact.js.map +1 -0
  42. package/dist/projections/calendar.js +33 -0
  43. package/dist/projections/calendar.js.map +1 -0
  44. package/dist/projections/communities.js +105 -0
  45. package/dist/projections/communities.js.map +1 -0
  46. package/dist/projections/cycle.js +81 -0
  47. package/dist/projections/cycle.js.map +1 -0
  48. package/dist/projections/hr_zones.js +35 -0
  49. package/dist/projections/hr_zones.js.map +1 -0
  50. package/dist/projections/journal.js +56 -0
  51. package/dist/projections/journal.js.map +1 -0
  52. package/dist/projections/leaderboard.js +37 -0
  53. package/dist/projections/leaderboard.js.map +1 -0
  54. package/dist/projections/lift_exercise.js +22 -0
  55. package/dist/projections/lift_exercise.js.map +1 -0
  56. package/dist/projections/lift_history.js +133 -0
  57. package/dist/projections/lift_history.js.map +1 -0
  58. package/dist/projections/lift_library.js +71 -0
  59. package/dist/projections/lift_library.js.map +1 -0
  60. package/dist/projections/lift_progression.js +138 -0
  61. package/dist/projections/lift_progression.js.map +1 -0
  62. package/dist/projections/lift_prs.js +20 -0
  63. package/dist/projections/lift_prs.js.map +1 -0
  64. package/dist/projections/live_hr.js +19 -0
  65. package/dist/projections/live_hr.js.map +1 -0
  66. package/dist/projections/live_state.js +23 -0
  67. package/dist/projections/live_state.js.map +1 -0
  68. package/dist/projections/live_stress.js +11 -0
  69. package/dist/projections/live_stress.js.map +1 -0
  70. package/dist/projections/performance_assessment.js +15 -0
  71. package/dist/projections/performance_assessment.js.map +1 -0
  72. package/dist/projections/profile.js +59 -0
  73. package/dist/projections/profile.js.map +1 -0
  74. package/dist/projections/recovery.js +131 -0
  75. package/dist/projections/recovery.js.map +1 -0
  76. package/dist/projections/sleep.js +256 -0
  77. package/dist/projections/sleep.js.map +1 -0
  78. package/dist/projections/sleep_need.js +32 -0
  79. package/dist/projections/sleep_need.js.map +1 -0
  80. package/dist/projections/smart_alarm.js +45 -0
  81. package/dist/projections/smart_alarm.js.map +1 -0
  82. package/dist/projections/strain.js +128 -0
  83. package/dist/projections/strain.js.map +1 -0
  84. package/dist/projections/stress.js +86 -0
  85. package/dist/projections/stress.js.map +1 -0
  86. package/dist/projections/today.js +129 -0
  87. package/dist/projections/today.js.map +1 -0
  88. package/dist/projections/trend.js +149 -0
  89. package/dist/projections/trend.js.map +1 -0
  90. package/dist/projections/workout.js +161 -0
  91. package/dist/projections/workout.js.map +1 -0
  92. package/dist/projections/workouts.js +37 -0
  93. package/dist/projections/workouts.js.map +1 -0
  94. package/dist/schemas/calendar.js +12 -0
  95. package/dist/schemas/calendar.js.map +1 -0
  96. package/dist/schemas/coach.js +11 -0
  97. package/dist/schemas/coach.js.map +1 -0
  98. package/dist/schemas/communities.js +51 -0
  99. package/dist/schemas/communities.js.map +1 -0
  100. package/dist/schemas/compare.js +15 -0
  101. package/dist/schemas/compare.js.map +1 -0
  102. package/dist/schemas/escape.js +18 -0
  103. package/dist/schemas/escape.js.map +1 -0
  104. package/dist/schemas/journal.js +69 -0
  105. package/dist/schemas/journal.js.map +1 -0
  106. package/dist/schemas/leaderboard.js +25 -0
  107. package/dist/schemas/leaderboard.js.map +1 -0
  108. package/dist/schemas/live.js +26 -0
  109. package/dist/schemas/live.js.map +1 -0
  110. package/dist/schemas/performance.js +12 -0
  111. package/dist/schemas/performance.js.map +1 -0
  112. package/dist/schemas/primitives.js +29 -0
  113. package/dist/schemas/primitives.js.map +1 -0
  114. package/dist/schemas/profile.js +39 -0
  115. package/dist/schemas/profile.js.map +1 -0
  116. package/dist/schemas/recovery.js +27 -0
  117. package/dist/schemas/recovery.js.map +1 -0
  118. package/dist/schemas/settings.js +26 -0
  119. package/dist/schemas/settings.js.map +1 -0
  120. package/dist/schemas/sleep.js +38 -0
  121. package/dist/schemas/sleep.js.map +1 -0
  122. package/dist/schemas/sleep_need.js +15 -0
  123. package/dist/schemas/sleep_need.js.map +1 -0
  124. package/dist/schemas/smart_alarm.js +36 -0
  125. package/dist/schemas/smart_alarm.js.map +1 -0
  126. package/dist/schemas/strain.js +24 -0
  127. package/dist/schemas/strain.js.map +1 -0
  128. package/dist/schemas/strength.js +170 -0
  129. package/dist/schemas/strength.js.map +1 -0
  130. package/dist/schemas/stress.js +16 -0
  131. package/dist/schemas/stress.js.map +1 -0
  132. package/dist/schemas/today.js +38 -0
  133. package/dist/schemas/today.js.map +1 -0
  134. package/dist/schemas/trend.js +50 -0
  135. package/dist/schemas/trend.js.map +1 -0
  136. package/dist/schemas/womens_health.js +23 -0
  137. package/dist/schemas/womens_health.js.map +1 -0
  138. package/dist/schemas/workouts.js +50 -0
  139. package/dist/schemas/workouts.js.map +1 -0
  140. package/dist/scripts/cognito_bootstrap.js +278 -0
  141. package/dist/scripts/cognito_bootstrap.js.map +1 -0
  142. package/dist/server-http.js +221 -0
  143. package/dist/server-http.js.map +1 -0
  144. package/dist/server.js +74 -0
  145. package/dist/server.js.map +1 -0
  146. package/dist/tools/register.js +117 -0
  147. package/dist/tools/register.js.map +1 -0
  148. package/dist/tools/v2/activity_create.js +64 -0
  149. package/dist/tools/v2/activity_create.js.map +1 -0
  150. package/dist/tools/v2/activity_delete.js +26 -0
  151. package/dist/tools/v2/activity_delete.js.map +1 -0
  152. package/dist/tools/v2/behavior_impact.js +36 -0
  153. package/dist/tools/v2/behavior_impact.js.map +1 -0
  154. package/dist/tools/v2/calendar.js +28 -0
  155. package/dist/tools/v2/calendar.js.map +1 -0
  156. package/dist/tools/v2/coach_ask.js +117 -0
  157. package/dist/tools/v2/coach_ask.js.map +1 -0
  158. package/dist/tools/v2/communities.js +60 -0
  159. package/dist/tools/v2/communities.js.map +1 -0
  160. package/dist/tools/v2/compare.js +67 -0
  161. package/dist/tools/v2/compare.js.map +1 -0
  162. package/dist/tools/v2/cycle.js +23 -0
  163. package/dist/tools/v2/cycle.js.map +1 -0
  164. package/dist/tools/v2/cycle_log.js +43 -0
  165. package/dist/tools/v2/cycle_log.js.map +1 -0
  166. package/dist/tools/v2/day.js +32 -0
  167. package/dist/tools/v2/day.js.map +1 -0
  168. package/dist/tools/v2/endpoints.js +28 -0
  169. package/dist/tools/v2/endpoints.js.map +1 -0
  170. package/dist/tools/v2/hidden_metric.js +28 -0
  171. package/dist/tools/v2/hidden_metric.js.map +1 -0
  172. package/dist/tools/v2/hr_zones.js +24 -0
  173. package/dist/tools/v2/hr_zones.js.map +1 -0
  174. package/dist/tools/v2/hr_zones_set.js +51 -0
  175. package/dist/tools/v2/hr_zones_set.js.map +1 -0
  176. package/dist/tools/v2/journal.js +26 -0
  177. package/dist/tools/v2/journal.js.map +1 -0
  178. package/dist/tools/v2/journal_autopop.js +19 -0
  179. package/dist/tools/v2/journal_autopop.js.map +1 -0
  180. package/dist/tools/v2/journal_catalog.js +44 -0
  181. package/dist/tools/v2/journal_catalog.js.map +1 -0
  182. package/dist/tools/v2/journal_log.js +78 -0
  183. package/dist/tools/v2/journal_log.js.map +1 -0
  184. package/dist/tools/v2/leaderboard.js +79 -0
  185. package/dist/tools/v2/leaderboard.js.map +1 -0
  186. package/dist/tools/v2/lift_catalog.js +47 -0
  187. package/dist/tools/v2/lift_catalog.js.map +1 -0
  188. package/dist/tools/v2/lift_custom_exercise.js +108 -0
  189. package/dist/tools/v2/lift_custom_exercise.js.map +1 -0
  190. package/dist/tools/v2/lift_exercise.js +31 -0
  191. package/dist/tools/v2/lift_exercise.js.map +1 -0
  192. package/dist/tools/v2/lift_history.js +39 -0
  193. package/dist/tools/v2/lift_history.js.map +1 -0
  194. package/dist/tools/v2/lift_library.js +22 -0
  195. package/dist/tools/v2/lift_library.js.map +1 -0
  196. package/dist/tools/v2/lift_log.js +95 -0
  197. package/dist/tools/v2/lift_log.js.map +1 -0
  198. package/dist/tools/v2/lift_progression.js +30 -0
  199. package/dist/tools/v2/lift_progression.js.map +1 -0
  200. package/dist/tools/v2/lift_prs.js +21 -0
  201. package/dist/tools/v2/lift_prs.js.map +1 -0
  202. package/dist/tools/v2/lift_template_save.js +83 -0
  203. package/dist/tools/v2/lift_template_save.js.map +1 -0
  204. package/dist/tools/v2/live_hr.js +21 -0
  205. package/dist/tools/v2/live_hr.js.map +1 -0
  206. package/dist/tools/v2/live_state.js +21 -0
  207. package/dist/tools/v2/live_state.js.map +1 -0
  208. package/dist/tools/v2/live_stress.js +22 -0
  209. package/dist/tools/v2/live_stress.js.map +1 -0
  210. package/dist/tools/v2/performance_assessment.js +38 -0
  211. package/dist/tools/v2/performance_assessment.js.map +1 -0
  212. package/dist/tools/v2/profile.js +28 -0
  213. package/dist/tools/v2/profile.js.map +1 -0
  214. package/dist/tools/v2/profile_update.js +66 -0
  215. package/dist/tools/v2/profile_update.js.map +1 -0
  216. package/dist/tools/v2/raw.js +43 -0
  217. package/dist/tools/v2/raw.js.map +1 -0
  218. package/dist/tools/v2/recovery.js +31 -0
  219. package/dist/tools/v2/recovery.js.map +1 -0
  220. package/dist/tools/v2/sleep.js +23 -0
  221. package/dist/tools/v2/sleep.js.map +1 -0
  222. package/dist/tools/v2/sleep_need.js +21 -0
  223. package/dist/tools/v2/sleep_need.js.map +1 -0
  224. package/dist/tools/v2/smart_alarm.js +24 -0
  225. package/dist/tools/v2/smart_alarm.js.map +1 -0
  226. package/dist/tools/v2/smart_alarm_set.js +94 -0
  227. package/dist/tools/v2/smart_alarm_set.js.map +1 -0
  228. package/dist/tools/v2/sports_catalog.js +26 -0
  229. package/dist/tools/v2/sports_catalog.js.map +1 -0
  230. package/dist/tools/v2/strain.js +23 -0
  231. package/dist/tools/v2/strain.js.map +1 -0
  232. package/dist/tools/v2/stress.js +23 -0
  233. package/dist/tools/v2/stress.js.map +1 -0
  234. package/dist/tools/v2/symptom_log.js +72 -0
  235. package/dist/tools/v2/symptom_log.js.map +1 -0
  236. package/dist/tools/v2/today.js +30 -0
  237. package/dist/tools/v2/today.js.map +1 -0
  238. package/dist/tools/v2/trend.js +26 -0
  239. package/dist/tools/v2/trend.js.map +1 -0
  240. package/dist/tools/v2/workout.js +23 -0
  241. package/dist/tools/v2/workout.js.map +1 -0
  242. package/dist/tools/v2/workouts.js +32 -0
  243. package/dist/tools/v2/workouts.js.map +1 -0
  244. package/dist/whoop/build_lift_body.js +67 -0
  245. package/dist/whoop/build_lift_body.js.map +1 -0
  246. package/dist/whoop/client.js +84 -0
  247. package/dist/whoop/client.js.map +1 -0
  248. package/dist/whoop/cognito.js +110 -0
  249. package/dist/whoop/cognito.js.map +1 -0
  250. package/dist/whoop/constants.js +4 -0
  251. package/dist/whoop/constants.js.map +1 -0
  252. package/dist/whoop/device.js +103 -0
  253. package/dist/whoop/device.js.map +1 -0
  254. package/dist/whoop/errors.js +42 -0
  255. package/dist/whoop/errors.js.map +1 -0
  256. package/dist/whoop/init_timezone.js +62 -0
  257. package/dist/whoop/init_timezone.js.map +1 -0
  258. package/dist/whoop/installation.js +62 -0
  259. package/dist/whoop/installation.js.map +1 -0
  260. package/dist/whoop/json_out.js +9 -0
  261. package/dist/whoop/json_out.js.map +1 -0
  262. package/dist/whoop/oauth_provider.js +297 -0
  263. package/dist/whoop/oauth_provider.js.map +1 -0
  264. package/dist/whoop/session_state.js +34 -0
  265. package/dist/whoop/session_state.js.map +1 -0
  266. package/dist/whoop/token_manager.js +60 -0
  267. package/dist/whoop/token_manager.js.map +1 -0
  268. package/dist/whoop/token_store.js +47 -0
  269. package/dist/whoop/token_store.js.map +1 -0
  270. package/dist/whoop/types.js +82 -0
  271. package/dist/whoop/types.js.map +1 -0
  272. package/dist/whoop/write_safety.js +23 -0
  273. package/dist/whoop/write_safety.js.map +1 -0
  274. package/package.json +66 -0
  275. package/src/cli/index.ts +597 -0
  276. package/src/cli/setup.ts +1106 -0
  277. package/src/cli/ui.ts +505 -0
  278. package/src/cli/update.ts +442 -0
  279. package/src/data/behaviors.ts +2784 -0
  280. package/src/data/endpoints.ts +319 -0
  281. package/src/data/exercises.ts +4868 -0
  282. package/src/data/sports.ts +218 -0
  283. package/src/lib/concurrency.ts +28 -0
  284. package/src/lib/dates.ts +35 -0
  285. package/src/lib/format.ts +27 -0
  286. package/src/lib/stats.ts +35 -0
  287. package/src/lib/timezone.ts +269 -0
  288. package/src/lib/walk.ts +418 -0
  289. package/src/projections/behavior_impact.ts +98 -0
  290. package/src/projections/calendar.ts +46 -0
  291. package/src/projections/communities.ts +135 -0
  292. package/src/projections/cycle.ts +85 -0
  293. package/src/projections/hr_zones.ts +43 -0
  294. package/src/projections/journal.ts +55 -0
  295. package/src/projections/leaderboard.ts +49 -0
  296. package/src/projections/lift_exercise.ts +29 -0
  297. package/src/projections/lift_history.ts +140 -0
  298. package/src/projections/lift_library.ts +70 -0
  299. package/src/projections/lift_progression.ts +138 -0
  300. package/src/projections/lift_prs.ts +23 -0
  301. package/src/projections/live_hr.ts +21 -0
  302. package/src/projections/live_state.ts +28 -0
  303. package/src/projections/live_stress.ts +13 -0
  304. package/src/projections/performance_assessment.ts +19 -0
  305. package/src/projections/profile.ts +71 -0
  306. package/src/projections/recovery.ts +133 -0
  307. package/src/projections/sleep.ts +276 -0
  308. package/src/projections/sleep_need.ts +36 -0
  309. package/src/projections/smart_alarm.ts +70 -0
  310. package/src/projections/strain.ts +131 -0
  311. package/src/projections/stress.ts +95 -0
  312. package/src/projections/today.ts +166 -0
  313. package/src/projections/trend.ts +149 -0
  314. package/src/projections/workout.ts +168 -0
  315. package/src/projections/workouts.ts +36 -0
  316. package/src/schemas/calendar.ts +13 -0
  317. package/src/schemas/coach.ts +11 -0
  318. package/src/schemas/communities.ts +56 -0
  319. package/src/schemas/compare.ts +17 -0
  320. package/src/schemas/escape.ts +21 -0
  321. package/src/schemas/journal.ts +80 -0
  322. package/src/schemas/leaderboard.ts +26 -0
  323. package/src/schemas/live.ts +31 -0
  324. package/src/schemas/performance.ts +13 -0
  325. package/src/schemas/primitives.ts +35 -0
  326. package/src/schemas/profile.ts +40 -0
  327. package/src/schemas/recovery.ts +28 -0
  328. package/src/schemas/settings.ts +30 -0
  329. package/src/schemas/sleep.ts +40 -0
  330. package/src/schemas/sleep_need.ts +16 -0
  331. package/src/schemas/smart_alarm.ts +40 -0
  332. package/src/schemas/strain.ts +25 -0
  333. package/src/schemas/strength.ts +189 -0
  334. package/src/schemas/stress.ts +17 -0
  335. package/src/schemas/today.ts +39 -0
  336. package/src/schemas/trend.ts +53 -0
  337. package/src/schemas/womens_health.ts +26 -0
  338. package/src/schemas/workouts.ts +55 -0
  339. package/src/scripts/cognito_bootstrap.ts +249 -0
  340. package/src/server-http.ts +241 -0
  341. package/src/server.ts +85 -0
  342. package/src/tools/register.ts +120 -0
  343. package/src/tools/v2/activity_create.ts +74 -0
  344. package/src/tools/v2/activity_delete.ts +33 -0
  345. package/src/tools/v2/behavior_impact.ts +39 -0
  346. package/src/tools/v2/calendar.ts +33 -0
  347. package/src/tools/v2/coach_ask.ts +131 -0
  348. package/src/tools/v2/communities.ts +65 -0
  349. package/src/tools/v2/compare.ts +83 -0
  350. package/src/tools/v2/cycle.ts +28 -0
  351. package/src/tools/v2/cycle_log.ts +51 -0
  352. package/src/tools/v2/day.ts +37 -0
  353. package/src/tools/v2/endpoints.ts +32 -0
  354. package/src/tools/v2/hidden_metric.ts +33 -0
  355. package/src/tools/v2/hr_zones.ts +29 -0
  356. package/src/tools/v2/hr_zones_set.ts +57 -0
  357. package/src/tools/v2/journal.ts +31 -0
  358. package/src/tools/v2/journal_autopop.ts +26 -0
  359. package/src/tools/v2/journal_catalog.ts +48 -0
  360. package/src/tools/v2/journal_log.ts +84 -0
  361. package/src/tools/v2/leaderboard.ts +92 -0
  362. package/src/tools/v2/lift_catalog.ts +48 -0
  363. package/src/tools/v2/lift_custom_exercise.ts +117 -0
  364. package/src/tools/v2/lift_exercise.ts +35 -0
  365. package/src/tools/v2/lift_history.ts +52 -0
  366. package/src/tools/v2/lift_library.ts +28 -0
  367. package/src/tools/v2/lift_log.ts +102 -0
  368. package/src/tools/v2/lift_progression.ts +34 -0
  369. package/src/tools/v2/lift_prs.ts +26 -0
  370. package/src/tools/v2/lift_template_save.ts +89 -0
  371. package/src/tools/v2/live_hr.ts +26 -0
  372. package/src/tools/v2/live_state.ts +26 -0
  373. package/src/tools/v2/live_stress.ts +27 -0
  374. package/src/tools/v2/performance_assessment.ts +44 -0
  375. package/src/tools/v2/profile.ts +33 -0
  376. package/src/tools/v2/profile_update.ts +76 -0
  377. package/src/tools/v2/raw.ts +50 -0
  378. package/src/tools/v2/recovery.ts +36 -0
  379. package/src/tools/v2/sleep.ts +28 -0
  380. package/src/tools/v2/sleep_need.ts +26 -0
  381. package/src/tools/v2/smart_alarm.ts +29 -0
  382. package/src/tools/v2/smart_alarm_set.ts +103 -0
  383. package/src/tools/v2/sports_catalog.ts +32 -0
  384. package/src/tools/v2/strain.ts +28 -0
  385. package/src/tools/v2/stress.ts +28 -0
  386. package/src/tools/v2/symptom_log.ts +78 -0
  387. package/src/tools/v2/today.ts +35 -0
  388. package/src/tools/v2/trend.ts +31 -0
  389. package/src/tools/v2/workout.ts +28 -0
  390. package/src/tools/v2/workouts.ts +37 -0
  391. package/src/whoop/build_lift_body.ts +84 -0
  392. package/src/whoop/client.ts +118 -0
  393. package/src/whoop/cognito.ts +150 -0
  394. package/src/whoop/constants.ts +3 -0
  395. package/src/whoop/device.ts +106 -0
  396. package/src/whoop/errors.ts +41 -0
  397. package/src/whoop/init_timezone.ts +64 -0
  398. package/src/whoop/installation.ts +58 -0
  399. package/src/whoop/json_out.ts +9 -0
  400. package/src/whoop/oauth_provider.ts +377 -0
  401. package/src/whoop/session_state.ts +41 -0
  402. package/src/whoop/token_manager.ts +76 -0
  403. package/src/whoop/token_store.ts +45 -0
  404. package/src/whoop/types.ts +89 -0
  405. package/src/whoop/write_safety.ts +30 -0
@@ -0,0 +1,53 @@
1
+ import { z } from "zod";
2
+
3
+ export const METRICS = [
4
+ "HRV",
5
+ "RHR",
6
+ "RECOVERY",
7
+ "DAY_STRAIN",
8
+ "CALORIES",
9
+ "STEPS",
10
+ "AVERAGE_HR",
11
+ "HOURS_V_NEED",
12
+ "HOURS_V_NEEDED_PERCENT",
13
+ "TIME_IN_BED",
14
+ "SLEEP_PERFORMANCE",
15
+ "SLEEP_EFFICIENCY",
16
+ "SLEEP_CONSISTENCY",
17
+ "SLEEP_DEBT_POST",
18
+ "RESTORATIVE_SLEEP",
19
+ "HR_ZONES_1_3",
20
+ "HR_ZONES_4_5",
21
+ "RESPIRATORY_RATE",
22
+ "STRENGTH_ACTIVITY_TIME",
23
+ "STRESS",
24
+ "STRESS_DURING_SLEEP",
25
+ "STRESS_DURING_NON_STRAIN",
26
+ "VO2_MAX",
27
+ "BODY_COMPOSITION",
28
+ "WEIGHT",
29
+ ] as const;
30
+
31
+ export const TrendMetric = z.enum(METRICS);
32
+
33
+ export const TrendOut = z.object({
34
+ metric: TrendMetric,
35
+ end_date: z.iso.date(),
36
+ segments: z.array(z.object({
37
+ label: z.enum(["week", "month", "six_month", "year"]),
38
+ start_date: z.string(),
39
+ end_date: z.string(),
40
+ avg: z.number().nullable(),
41
+ min: z.number().nullable(),
42
+ max: z.number().nullable(),
43
+ delta_pct: z.number().nullable(),
44
+ unit: z.string().nullable(),
45
+ points: z.array(z.object({
46
+ date: z.string(),
47
+ value: z.number().nullable(),
48
+ value_display: z.string().nullable(),
49
+ })),
50
+ })),
51
+ cardio_fitness_level: z.string().nullable(),
52
+ });
53
+ export type TrendOutT = z.infer<typeof TrendOut>;
@@ -0,0 +1,26 @@
1
+ import { z } from "zod";
2
+ import { withPreview } from "./primitives.js";
3
+
4
+ export const CycleOut = z.object({
5
+ date: z.iso.date(),
6
+ phase: z.string().nullable().describe("e.g. Menstrual, Follicular, Luteal."),
7
+ cycle_day: z.number().int().nullable(),
8
+ cycle_length: z.number().int().nullable(),
9
+ next_period_predicted_date: z.iso.date().nullable(),
10
+ ovulation_predicted_date: z.iso.date().nullable(),
11
+ hormonal_mode: z.string().nullable(),
12
+ contraception_type: z.string().nullable(),
13
+ is_pregnant: z.boolean().nullable(),
14
+ });
15
+ export type CycleOutT = z.infer<typeof CycleOut>;
16
+
17
+ export const CycleLogOut = withPreview(z.object({
18
+ logged: z.literal(true),
19
+ date: z.iso.date(),
20
+ }));
21
+
22
+ export const SymptomLogOut = withPreview(z.object({
23
+ logged: z.literal(true),
24
+ date: z.iso.date(),
25
+ symptoms_count: z.number().int(),
26
+ }));
@@ -0,0 +1,55 @@
1
+ import { z } from "zod";
2
+ import { HrZoneDurations, IsoDateTime, withPreview } from "./primitives.js";
3
+
4
+ export const WorkoutListOut = z.array(z.object({
5
+ id: z.string(),
6
+ sport_name: z.string(),
7
+ start: IsoDateTime,
8
+ end: IsoDateTime,
9
+ duration_ms: z.number().int(),
10
+ strain: z.number().nullable(),
11
+ avg_hr_bpm: z.number().nullable(),
12
+ max_hr_bpm: z.number().nullable(),
13
+ calories: z.number().int().nullable(),
14
+ distance_m: z.number().nullable(),
15
+ }));
16
+ export type WorkoutListOutT = z.infer<typeof WorkoutListOut>;
17
+
18
+ export const WorkoutOut = z.object({
19
+ id: z.string(),
20
+ sport_name: z.string().nullable(),
21
+ start: IsoDateTime.nullable(),
22
+ end: IsoDateTime.nullable(),
23
+ duration_ms: z.number().int().nullable(),
24
+ strain: z.number().nullable(),
25
+ calories: z.number().int().nullable(),
26
+ distance_m: z.number().nullable(),
27
+ avg_hr_bpm: z.number().nullable(),
28
+ max_hr_bpm: z.number().nullable(),
29
+ zone_durations: HrZoneDurations,
30
+ hr_curve: z.array(z.object({
31
+ at: IsoDateTime,
32
+ bpm: z.number().int(),
33
+ })),
34
+ msk: z.object({
35
+ total_volume_kg: z.number().nullable(),
36
+ intensity_pct: z.number().nullable(),
37
+ strain_score: z.number().nullable(),
38
+ is_strength_workout: z.boolean(),
39
+ }),
40
+ });
41
+ export type WorkoutOutT = z.infer<typeof WorkoutOut>;
42
+
43
+ export const ActivityCreateOut = withPreview(z.object({
44
+ created: z.literal(true),
45
+ activity_id: z.string(),
46
+ cycle_id: z.number().int(),
47
+ start: IsoDateTime,
48
+ end: IsoDateTime,
49
+ sport_id: z.number().int(),
50
+ }));
51
+
52
+ export const ActivityDeleteOut = withPreview(z.object({
53
+ deleted: z.literal(true),
54
+ activity_id: z.string(),
55
+ }));
@@ -0,0 +1,249 @@
1
+ // `totem auth` — the one token command. It logs you into Whoop (Cognito),
2
+ // saves the tokens to .env, and — if you've deployed somewhere — pushes them to
3
+ // that deployment so the running server picks them up. Auto-detects:
4
+ // • new vs re-auth — whether you already have tokens (messaging only)
5
+ // • local vs deployed — reads .totem-deploy.json and pushes per-platform
6
+ // (Fly / Railway / Cloud Run / custom), or notes "restart your client" for a
7
+ // local install. Legacy: --app / $FLY_APP / fly.toml still target Fly.
8
+ // Run it for first-time setup, or whenever the ~30-day refresh token expires.
9
+ //
10
+ // When invoked as a sub-step of `totem cloud` / `local` (which handle the
11
+ // deploy themselves), set WHOOP_AUTH_TOKENS_ONLY=1 to skip the push step.
12
+ import "dotenv/config";
13
+ import { readFileSync, writeFileSync, existsSync, chmodSync } from "node:fs";
14
+ import { spawnSync } from "node:child_process";
15
+ import { createInterface } from "node:readline/promises";
16
+ import { resolve } from "node:path";
17
+ import { bootstrapCognito, refreshCognitoSession } from "../whoop/cognito.js";
18
+
19
+ const ENV_PATH = resolve(".env");
20
+ const RECORD_PATH = resolve(".totem-deploy.json");
21
+
22
+ function readEnv(key: string): string | undefined {
23
+ if (!existsSync(ENV_PATH)) return undefined;
24
+ const m = readFileSync(ENV_PATH, "utf8").match(new RegExp(`^${key}=(.+)$`, "m"));
25
+ return m ? m[1] : undefined;
26
+ }
27
+
28
+ function upsertEnv(updates: Record<string, string>): void {
29
+ const current = existsSync(ENV_PATH) ? readFileSync(ENV_PATH, "utf8") : "";
30
+ const lines = current.split("\n");
31
+ for (const [key, value] of Object.entries(updates)) {
32
+ const idx = lines.findIndex((l) => l.startsWith(`${key}=`));
33
+ const entry = `${key}=${value}`;
34
+ if (idx >= 0) lines[idx] = entry;
35
+ else lines.push(entry);
36
+ }
37
+ // 0600 — holds the refresh token (and, transiently, the password).
38
+ writeFileSync(ENV_PATH, lines.join("\n"), { mode: 0o600 });
39
+ try { chmodSync(ENV_PATH, 0o600); } catch { /* best-effort */ }
40
+ }
41
+
42
+ // Remove keys from .env (used to wipe the one-time password after bootstrap).
43
+ function deleteEnvKeys(keys: string[]): void {
44
+ if (!existsSync(ENV_PATH)) return;
45
+ const lines = readFileSync(ENV_PATH, "utf8").split("\n")
46
+ .filter((l) => !keys.some((k) => l.startsWith(`${k}=`)));
47
+ writeFileSync(ENV_PATH, lines.join("\n"), { mode: 0o600 });
48
+ try { chmodSync(ENV_PATH, 0o600); } catch { /* best-effort */ }
49
+ }
50
+
51
+ interface DeployTarget {
52
+ platform: string;
53
+ app?: string;
54
+ url?: string;
55
+ region?: string;
56
+ project?: string;
57
+ }
58
+
59
+ function getTarget(): DeployTarget {
60
+ // 1. The deploy record written by `totem cloud` / `local`.
61
+ if (existsSync(RECORD_PATH)) {
62
+ try {
63
+ const r = JSON.parse(readFileSync(RECORD_PATH, "utf8")) as DeployTarget;
64
+ if (r && typeof r.platform === "string") return r;
65
+ } catch { /* fall through */ }
66
+ }
67
+ // 2. Legacy Fly detection (deploys made before the record existed).
68
+ const argIdx = process.argv.indexOf("--app");
69
+ if (argIdx >= 0 && process.argv[argIdx + 1]) return { platform: "fly", app: process.argv[argIdx + 1]! };
70
+ if (process.env.FLY_APP) return { platform: "fly", app: process.env.FLY_APP };
71
+ if (existsSync("fly.toml")) {
72
+ const m = readFileSync("fly.toml", "utf8").match(/^app\s*=\s*['"]([^'"]+)['"]/m);
73
+ if (m && m[1]) return { platform: "fly", app: m[1] };
74
+ }
75
+ // 3. No remote → local stdio install.
76
+ return { platform: "local" };
77
+ }
78
+
79
+ // Push the rotated tokens to the deploy target. Token values go to the host CLIs
80
+ // as argv (never echoed by us), so they don't leak to the screen. Returns true on
81
+ // success (or when there's nothing remote to push — local/custom).
82
+ function pushTokens(t: DeployTarget, accessToken: string, refreshToken: string): boolean {
83
+ const inherit = { stdio: "inherit" as const };
84
+ const manual = (): void => {
85
+ console.error("Set these on your host yourself, then restart it:");
86
+ console.error(` WHOOP_IOS_BEARER_TOKEN=${accessToken}`);
87
+ console.error(` WHOOP_COGNITO_REFRESH_TOKEN=${refreshToken}`);
88
+ };
89
+
90
+ switch (t.platform) {
91
+ case "local":
92
+ console.log("Local install — nothing remote to update.");
93
+ console.log(" → If the server is running (Claude Desktop / Code), restart it to load the new tokens.");
94
+ return true;
95
+
96
+ case "custom":
97
+ console.log("Custom host — set these two on your server, then restart it:");
98
+ console.log(` WHOOP_IOS_BEARER_TOKEN=${accessToken}`);
99
+ console.log(` WHOOP_COGNITO_REFRESH_TOKEN=${refreshToken}`);
100
+ return true;
101
+
102
+ case "fly": {
103
+ if (!t.app) { console.error("No Fly app recorded."); manual(); return false; }
104
+ console.log(`Pushing to Fly app '${t.app}'…`);
105
+ // `secrets import` reads KEY=val from stdin — keeps the token values off
106
+ // the argv (which any local user could read from `ps`/`/proc`).
107
+ const r = spawnSync("fly", ["secrets", "import", "-a", t.app], {
108
+ input: `WHOOP_IOS_BEARER_TOKEN=${accessToken}\nWHOOP_COGNITO_REFRESH_TOKEN=${refreshToken}\n`,
109
+ stdio: ["pipe", "inherit", "inherit"],
110
+ });
111
+ if (r.status === 0) { console.log(` → done. Test: curl https://${t.app}.fly.dev/health`); return true; }
112
+ console.error("`fly secrets import` failed (is flyctl installed + `fly auth login` done?)."); manual(); return false;
113
+ }
114
+
115
+ case "railway": {
116
+ console.log(`Pushing to Railway project '${t.app ?? "(linked)"}'…`);
117
+ if (t.app) spawnSync("railway", ["link", "--project", t.app], inherit);
118
+ const r = spawnSync("railway", ["variables", "--set",
119
+ `WHOOP_IOS_BEARER_TOKEN=${accessToken}`, "--set",
120
+ `WHOOP_COGNITO_REFRESH_TOKEN=${refreshToken}`], inherit);
121
+ if (r.status === 0) { console.log(" → done. Railway is redeploying with the new tokens."); return true; }
122
+ console.error("`railway variables` failed (is the CLI installed, logged in, and the project linked?)."); manual(); return false;
123
+ }
124
+
125
+ case "cloudrun": {
126
+ if (!t.app) { console.error("No Cloud Run service recorded."); manual(); return false; }
127
+ const region = t.region ?? "us-west1";
128
+ console.log(`Pushing to Cloud Run service '${t.app}' (${region})…`);
129
+ const r = spawnSync("gcloud", ["run", "services", "update", t.app,
130
+ "--region", region,
131
+ ...(t.project ? ["--project", t.project] : []),
132
+ "--update-env-vars", `WHOOP_IOS_BEARER_TOKEN=${accessToken},WHOOP_COGNITO_REFRESH_TOKEN=${refreshToken}`,
133
+ "--quiet"], inherit);
134
+ if (r.status === 0) { console.log(" → done. Cloud Run deployed a new revision with the new tokens."); return true; }
135
+ console.error("`gcloud run services update` failed (is gcloud installed, authed, on the right project?)."); manual(); return false;
136
+ }
137
+
138
+ default:
139
+ console.log(`Unknown deploy platform '${t.platform}'. Tokens are saved in .env; update your host manually:`);
140
+ manual();
141
+ return true;
142
+ }
143
+ }
144
+
145
+ // Masked question — the typed password is never echoed to the screen (so it
146
+ // can't be read off a recording / over a shoulder). Only the prompt and the
147
+ // commit newline are written; per-character echoes are swallowed.
148
+ async function questionHidden(rl: ReturnType<typeof createInterface>, query: string): Promise<string> {
149
+ // Write the prompt ourselves, swallow ALL readline echo (no redraw can leak
150
+ // the secret), then RESTORE echo — the same readline handles the visible MFA
151
+ // prompt afterward.
152
+ process.stdout.write(query);
153
+ const out = rl as unknown as { _writeToOutput?: (s: string) => void };
154
+ const orig = out._writeToOutput?.bind(rl);
155
+ out._writeToOutput = (): void => {};
156
+ try {
157
+ const answer = (await rl.question("")).trim();
158
+ process.stdout.write("\n");
159
+ return answer;
160
+ } finally {
161
+ if (orig) out._writeToOutput = orig;
162
+ }
163
+ }
164
+
165
+ async function main(): Promise<void> {
166
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
167
+ // Ctrl-C at any prompt: readline swallows SIGINT, so exit explicitly.
168
+ rl.on("SIGINT", () => process.exit(130));
169
+
170
+ // Email + password — prompt + persist if not already in .env / env.
171
+ let email = process.env.WHOOP_EMAIL ?? readEnv("WHOOP_EMAIL");
172
+ if (!email) { email = (await rl.question("Your Whoop account email: ")).trim(); if (email) upsertEnv({ WHOOP_EMAIL: email }); }
173
+ let password = process.env.WHOOP_PASSWORD ?? readEnv("WHOOP_PASSWORD");
174
+ if (!password) { password = await questionHidden(rl, "Your Whoop account password (stored in local .env, used once): "); if (password) upsertEnv({ WHOOP_PASSWORD: password }); }
175
+ if (!email || !password) { console.error("Email + password are required."); rl.close(); process.exit(1); }
176
+
177
+ const tokensOnly = process.env.WHOOP_AUTH_TOKENS_ONLY === "1";
178
+ const hadTokens = Boolean(readEnv("WHOOP_IOS_BEARER_TOKEN") && readEnv("WHOOP_COGNITO_REFRESH_TOKEN"));
179
+ const target = getTarget();
180
+
181
+ console.log("");
182
+ console.log(hadTokens ? "Re-authenticating with Whoop — refreshing your tokens…" : "Authenticating with Whoop — first-time setup…");
183
+ if (!tokensOnly && target.platform !== "local") {
184
+ console.log(`Then updating your ${target.platform} deployment${target.app ? ` '${target.app}'` : ""}.`);
185
+ }
186
+ console.log("(you'll be asked for an SMS code only if your account has MFA)");
187
+ console.log("");
188
+
189
+ let tokens;
190
+ try {
191
+ tokens = await bootstrapCognito({
192
+ email,
193
+ password,
194
+ mfaPrompt: async () => {
195
+ console.log("");
196
+ return rl.question("Enter the SMS MFA code Whoop just texted you: ");
197
+ },
198
+ });
199
+ } catch (err) {
200
+ rl.close();
201
+ console.error("\nAuth failed:", err instanceof Error ? err.message : err);
202
+ process.exit(1);
203
+ }
204
+ rl.close();
205
+ console.log(" → got fresh access + refresh tokens.");
206
+
207
+ let access = tokens.accessToken;
208
+ let refresh = tokens.refreshToken;
209
+ upsertEnv({ WHOOP_IOS_BEARER_TOKEN: access, WHOOP_COGNITO_REFRESH_TOKEN: refresh });
210
+
211
+ // Verify auto-refresh works (catches "account requires MFA on every login").
212
+ // This rotates the access token, so push the freshest one afterward.
213
+ try {
214
+ const refreshed = await refreshCognitoSession(email, refresh);
215
+ if (refreshed.accessToken && refreshed.accessToken !== access) {
216
+ access = refreshed.accessToken;
217
+ if (refreshed.refreshToken && refreshed.refreshToken !== refresh) refresh = refreshed.refreshToken;
218
+ upsertEnv({ WHOOP_IOS_BEARER_TOKEN: access, WHOOP_COGNITO_REFRESH_TOKEN: refresh });
219
+ console.log(" → auto-refresh works (the server keeps the access token fresh on its own).");
220
+ }
221
+ } catch {
222
+ console.log(" ⚠ auto-refresh check failed — your account may require MFA on every login (expect to re-auth more often).");
223
+ }
224
+
225
+ // Save user_id (best-effort — saves a redundant bootstrap call per session).
226
+ try {
227
+ const r = await fetch("https://api.prod.whoop.com/users-service/v2/bootstrap?apiVersion=7", {
228
+ headers: { authorization: `bearer ${access}`, accept: "application/json" },
229
+ });
230
+ if (r.ok) {
231
+ const j = (await r.json()) as { user?: { id?: number } };
232
+ if (j.user?.id) { upsertEnv({ WHOOP_USER_ID: String(j.user.id) }); console.log(` → user_id ${j.user.id} saved.`); }
233
+ }
234
+ } catch { /* optional */ }
235
+
236
+ // The account password is only needed for this one bootstrap — every
237
+ // subsequent refresh uses the refresh token. Don't leave it on disk.
238
+ deleteEnvKeys(["WHOOP_PASSWORD"]);
239
+ console.log(" → removed your password from .env (only the tokens are needed now).");
240
+
241
+ console.log("");
242
+ if (tokensOnly) {
243
+ console.log("Tokens saved to .env.");
244
+ return;
245
+ }
246
+ pushTokens(target, access, refresh);
247
+ }
248
+
249
+ await main();
@@ -0,0 +1,241 @@
1
+ // HTTP transport entry point. Boots an MCP server over Streamable HTTP behind
2
+ // auth, on Express so we can mount the MCP SDK's OAuth 2.1 authorization-server
3
+ // endpoints (required for claude.ai web + the Claude mobile app, whose custom
4
+ // connectors only support OAuth — no bearer-header field).
5
+ //
6
+ // Two auth paths, both accepted on /mcp:
7
+ // 1. Static bearer (MCP_AUTH_TOKEN) — for Claude Code (--header) and the
8
+ // Claude Desktop mcp-remote bridge. Unchanged from before.
9
+ // 2. OAuth 2.1 + PKCE — for claude.ai web / mobile custom connectors. The
10
+ // /authorize step is gated by AUTH_PASSWORD. See whoop/oauth_provider.ts.
11
+ //
12
+ // Env:
13
+ // MCP_TRANSPORT=http (required to select this transport)
14
+ // MCP_AUTH_TOKEN=<≥16 char> (required; also the JWT signing secret)
15
+ // AUTH_PASSWORD=<password> (optional; enables the OAuth/web-connector path)
16
+ // PUBLIC_URL=https://... (optional; the server's public origin, used as the
17
+ // OAuth issuer. Defaults to http://localhost:<port>)
18
+ import express, { type Request, type Response } from "express";
19
+ import { randomUUID, createHmac } from "node:crypto";
20
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
21
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
22
+ import { mcpAuthRouter } from "@modelcontextprotocol/sdk/server/auth/router.js";
23
+ import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
24
+ import type { WhoopClient } from "./whoop/client.js";
25
+ import { registerTools } from "./tools/register.js";
26
+ import { WhoopOAuthProvider, renderConsentForm, setConsentSecurityHeaders } from "./whoop/oauth_provider.js";
27
+
28
+ export interface HttpServerOptions {
29
+ /** Bearer token clients must present + JWT signing secret. Required, ≥16 chars. */
30
+ authToken: string;
31
+ port?: number;
32
+ host?: string;
33
+ }
34
+
35
+ export async function startHttpServer(client: WhoopClient, opts: HttpServerOptions): Promise<void> {
36
+ if (!opts.authToken || opts.authToken.length < 16) {
37
+ throw new Error(
38
+ "MCP_AUTH_TOKEN must be set and at least 16 chars. Generate one with `openssl rand -hex 32`.",
39
+ );
40
+ }
41
+ const port = opts.port ?? Number(process.env.PORT ?? process.env.MCP_HTTP_PORT ?? 3000);
42
+ const host = opts.host ?? "0.0.0.0";
43
+ const password = process.env.AUTH_PASSWORD ?? "";
44
+ // `||` not `??`: an empty PUBLIC_URL (e.g. a host that injects "" for an unset
45
+ // var, or the first-pass deploy on Railway/Cloud Run before the real URL
46
+ // is known) must fall back to localhost, not become `new URL("")` → boot crash.
47
+ const publicUrl = process.env.PUBLIC_URL || `http://localhost:${port}`;
48
+ const oauthEnabled = password.length > 0;
49
+ const resourceUrl = `${publicUrl.replace(/\/$/, "")}/mcp`;
50
+ // Sign OAuth JWTs with a key DERIVED from MCP_AUTH_TOKEN, not the token itself
51
+ // — so the long-lived static bearer and the JWT signing secret aren't the same
52
+ // string in two roles (leaking one shouldn't let you forge the other).
53
+ const signingSecret = createHmac("sha256", opts.authToken)
54
+ .update("totem/oauth-jwt-signing/v1")
55
+ .digest("hex");
56
+
57
+ const provider = new WhoopOAuthProvider({
58
+ signingSecret,
59
+ password,
60
+ staticToken: opts.authToken,
61
+ resourceUrl,
62
+ });
63
+
64
+ // One McpServer + transport pair per active session (MCP spec: a server can't
65
+ // be re-initialized once initialize() runs). Routed by mcp-session-id header.
66
+ const sessions = new Map<string, { server: McpServer; transport: StreamableHTTPServerTransport }>();
67
+
68
+ async function getOrCreateSession(
69
+ existingSessionId: string | undefined,
70
+ ): Promise<{ server: McpServer; transport: StreamableHTTPServerTransport }> {
71
+ if (existingSessionId) {
72
+ const existing = sessions.get(existingSessionId);
73
+ if (existing) return existing;
74
+ }
75
+ const newId = randomUUID();
76
+ const newServer = new McpServer({ name: "totem", version: "1.4.4" });
77
+ registerTools(newServer, client);
78
+ const newTransport = new StreamableHTTPServerTransport({
79
+ sessionIdGenerator: () => newId,
80
+ enableJsonResponse: true,
81
+ });
82
+ newTransport.onclose = (): void => {
83
+ sessions.delete(newId);
84
+ };
85
+ await newServer.connect(newTransport as Parameters<typeof newServer.connect>[0]);
86
+ const entry = { server: newServer, transport: newTransport };
87
+ sessions.set(newId, entry);
88
+ return entry;
89
+ }
90
+
91
+ const app = express();
92
+ app.disable("x-powered-by");
93
+ // Behind Fly's reverse proxy the client IP is in X-Forwarded-For. Trust
94
+ // exactly ONE hop (Fly's edge proxy) so express-rate-limit (used by the SDK's
95
+ // OAuth endpoints) can identify clients. `true` (trust all) is rejected by
96
+ // express-rate-limit as too permissive — clients could spoof X-Forwarded-For
97
+ // — so we use the hop count instead.
98
+ app.set("trust proxy", 1);
99
+
100
+ // NOTE: anti-clickjacking headers (X-Frame-Options / CSP) are set ONLY on the
101
+ // HTML consent page (see setConsentSecurityHeaders), NOT globally. Putting
102
+ // document-level CSP + X-Frame-Options on the JSON metadata and /mcp API
103
+ // responses makes Claude's connector reject the server with a "configuration
104
+ // issue" at add-time — those headers protect HTML documents from clickjacking,
105
+ // and have no meaning on a machine-consumed JSON API.
106
+
107
+ // CORS — a browser-based MCP client (or the OAuth redirect dance) may hit this.
108
+ app.use((req, res, next) => {
109
+ res.setHeader("Access-Control-Allow-Origin", "*");
110
+ res.setHeader("Access-Control-Allow-Headers", "authorization, content-type, mcp-session-id");
111
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
112
+ res.setHeader("Access-Control-Expose-Headers", "mcp-session-id, www-authenticate");
113
+ if (req.method === "OPTIONS") {
114
+ res.status(204).end();
115
+ return;
116
+ }
117
+ next();
118
+ });
119
+
120
+ // Health probe — no auth. Container hosts (Fly/Docker HEALTHCHECK) hit this.
121
+ app.get("/health", (_req, res) => {
122
+ res.json({ status: "ok" });
123
+ });
124
+
125
+ // OAuth 2.1 authorization-server endpoints: /.well-known/oauth-authorization-server,
126
+ // /.well-known/oauth-protected-resource/mcp, /authorize, /token, /register, /revoke.
127
+ //
128
+ // resourceServerUrl MUST be the actual MCP endpoint (…/mcp), not the root.
129
+ // Claude's connector validates that the protected-resource metadata's
130
+ // `resource` matches the URL it's connecting to. If we let it default to the
131
+ // issuer (root), Claude sees resource=https://host/ ≠ https://host/mcp and
132
+ // refuses to connect. Setting it to /mcp also serves the metadata at the
133
+ // RFC 9728 path-specific location /.well-known/oauth-protected-resource/mcp.
134
+ const issuerUrl = new URL(publicUrl);
135
+ const resourceServerUrl = new URL(resourceUrl);
136
+ app.use(mcpAuthRouter({ provider, issuerUrl, resourceServerUrl }));
137
+
138
+ // Brute-force guard for the password gate: this consent route is custom and
139
+ // is NOT covered by the SDK's OAuth rate-limiter. Per-IP fixed window
140
+ // (trust proxy=1 gives us the real client IP via req.ip).
141
+ const consentHits = new Map<string, { count: number; resetAt: number }>();
142
+ const CONSENT_MAX = 10;
143
+ const CONSENT_WINDOW_MS = 15 * 60 * 1000;
144
+ // Global failed-password ceiling — a backstop that does NOT depend on the
145
+ // spoofable per-IP key (X-Forwarded-For). Counts wrong passwords across ALL
146
+ // IPs and trips a site-wide cooldown, so a distributed / IP-rotating guesser
147
+ // can't dilute the per-IP limiter.
148
+ let globalFails = 0;
149
+ let globalResetAt = 0;
150
+ const GLOBAL_FAIL_MAX = 50;
151
+
152
+ // Password-gate handler for the /authorize step. The form rendered by
153
+ // provider.authorize() POSTs here; we validate the password, mint an auth
154
+ // code, and redirect back to the client.
155
+ app.post("/oauth/consent", express.urlencoded({ extended: false }), (req: Request, res: Response) => {
156
+ if (!oauthEnabled) {
157
+ res.status(403).json({ error: "oauth_disabled", error_description: "AUTH_PASSWORD is not set on this server." });
158
+ return;
159
+ }
160
+ const ip = req.ip ?? "unknown";
161
+ const now = Date.now();
162
+ // Global cooldown (IP-independent) — trips before the per-IP check.
163
+ if (now > globalResetAt) { globalFails = 0; globalResetAt = now + CONSENT_WINDOW_MS; }
164
+ if (globalFails >= GLOBAL_FAIL_MAX) {
165
+ res.status(429).json({ error: "too_many_requests", error_description: "Too many failed attempts — wait 15 minutes." });
166
+ return;
167
+ }
168
+ const hit = consentHits.get(ip);
169
+ if (!hit || now > hit.resetAt) {
170
+ consentHits.set(ip, { count: 1, resetAt: now + CONSENT_WINDOW_MS });
171
+ } else if (++hit.count > CONSENT_MAX) {
172
+ res.status(429).json({ error: "too_many_requests", error_description: "Too many attempts — wait 15 minutes." });
173
+ return;
174
+ }
175
+ const body = req.body as Record<string, string>;
176
+ const redirect = provider.consent({
177
+ clientId: body.client_id ?? "",
178
+ redirectUri: body.redirect_uri ?? "",
179
+ codeChallenge: body.code_challenge ?? "",
180
+ state: body.state ?? "",
181
+ scopes: body.scope ?? "",
182
+ resource: body.resource ?? "",
183
+ password: body.password ?? "",
184
+ });
185
+ if (!redirect) {
186
+ // Wrong password (or bad client) — count it toward the global ceiling and
187
+ // re-render the form with an error.
188
+ globalFails++;
189
+ setConsentSecurityHeaders(res);
190
+ res.status(401).setHeader("content-type", "text/html; charset=utf-8");
191
+ res.end(renderConsentForm({
192
+ clientId: body.client_id ?? "",
193
+ redirectUri: body.redirect_uri ?? "",
194
+ codeChallenge: body.code_challenge ?? "",
195
+ state: body.state ?? "",
196
+ scopes: body.scope ?? "",
197
+ resource: body.resource ?? "",
198
+ error: true,
199
+ }));
200
+ return;
201
+ }
202
+ res.redirect(302, redirect);
203
+ });
204
+
205
+ // MCP endpoint — gated by OAuth token OR static bearer (provider.verifyAccessToken
206
+ // accepts both). 401s carry a WWW-Authenticate pointing at the resource metadata
207
+ // so OAuth clients can discover the authorization server.
208
+ const bearer = requireBearerAuth({
209
+ verifier: provider,
210
+ resourceMetadataUrl: `${publicUrl.replace(/\/$/, "")}/.well-known/oauth-protected-resource/mcp`,
211
+ });
212
+
213
+ const mcpHandler = async (req: Request, res: Response): Promise<void> => {
214
+ try {
215
+ const sessionIdHeader = req.headers["mcp-session-id"];
216
+ const sid = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
217
+ const session = await getOrCreateSession(sid);
218
+ await session.transport.handleRequest(req, res, req.body);
219
+ } catch (err) {
220
+ console.error("[totem] request error:", err);
221
+ if (!res.headersSent) res.status(500).json({ error: "internal server error" });
222
+ }
223
+ };
224
+
225
+ app.post("/mcp", bearer, express.json(), (req, res) => void mcpHandler(req, res));
226
+ app.get("/mcp", bearer, (req, res) => void mcpHandler(req, res));
227
+ app.delete("/mcp", bearer, (req, res) => void mcpHandler(req, res));
228
+
229
+ const httpServer = app.listen(port, host, () => {
230
+ console.error(`[totem] listening on ${publicUrl} (bound ${host}:${port})`);
231
+ console.error(`[totem] health: GET /health`);
232
+ console.error(`[totem] auth: static bearer (MCP_AUTH_TOKEN)${oauthEnabled ? " + OAuth (web/mobile connectors)" : " — OAuth disabled (set AUTH_PASSWORD to enable)"}`);
233
+ });
234
+
235
+ const close = (): void => {
236
+ httpServer.close(() => process.exit(0));
237
+ setTimeout(() => process.exit(1), 5000).unref();
238
+ };
239
+ process.on("SIGINT", close);
240
+ process.on("SIGTERM", close);
241
+ }