@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.
- package/.dockerignore +23 -0
- package/.env.example +66 -0
- package/CHANGELOG.md +283 -0
- package/CONTRIBUTING.md +149 -0
- package/Dockerfile +53 -0
- package/LICENSE +37 -0
- package/README.md +587 -0
- package/SECURITY.md +79 -0
- package/TOOLS.md +429 -0
- package/WHOOP.md +2673 -0
- package/assets/banner.svg +38 -0
- package/dist/cli/index.js +589 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli/setup.js +1127 -0
- package/dist/cli/setup.js.map +1 -0
- package/dist/cli/ui.js +512 -0
- package/dist/cli/ui.js.map +1 -0
- package/dist/cli/update.js +465 -0
- package/dist/cli/update.js.map +1 -0
- package/dist/data/behaviors.js +2777 -0
- package/dist/data/behaviors.js.map +1 -0
- package/dist/data/endpoints.js +320 -0
- package/dist/data/endpoints.js.map +1 -0
- package/dist/data/exercises.js +4863 -0
- package/dist/data/exercises.js.map +1 -0
- package/dist/data/sports.js +212 -0
- package/dist/data/sports.js.map +1 -0
- package/dist/lib/concurrency.js +27 -0
- package/dist/lib/concurrency.js.map +1 -0
- package/dist/lib/dates.js +29 -0
- package/dist/lib/dates.js.map +1 -0
- package/dist/lib/format.js +22 -0
- package/dist/lib/format.js.map +1 -0
- package/dist/lib/stats.js +32 -0
- package/dist/lib/stats.js.map +1 -0
- package/dist/lib/timezone.js +249 -0
- package/dist/lib/timezone.js.map +1 -0
- package/dist/lib/walk.js +396 -0
- package/dist/lib/walk.js.map +1 -0
- package/dist/projections/behavior_impact.js +96 -0
- package/dist/projections/behavior_impact.js.map +1 -0
- package/dist/projections/calendar.js +33 -0
- package/dist/projections/calendar.js.map +1 -0
- package/dist/projections/communities.js +105 -0
- package/dist/projections/communities.js.map +1 -0
- package/dist/projections/cycle.js +81 -0
- package/dist/projections/cycle.js.map +1 -0
- package/dist/projections/hr_zones.js +35 -0
- package/dist/projections/hr_zones.js.map +1 -0
- package/dist/projections/journal.js +56 -0
- package/dist/projections/journal.js.map +1 -0
- package/dist/projections/leaderboard.js +37 -0
- package/dist/projections/leaderboard.js.map +1 -0
- package/dist/projections/lift_exercise.js +22 -0
- package/dist/projections/lift_exercise.js.map +1 -0
- package/dist/projections/lift_history.js +133 -0
- package/dist/projections/lift_history.js.map +1 -0
- package/dist/projections/lift_library.js +71 -0
- package/dist/projections/lift_library.js.map +1 -0
- package/dist/projections/lift_progression.js +138 -0
- package/dist/projections/lift_progression.js.map +1 -0
- package/dist/projections/lift_prs.js +20 -0
- package/dist/projections/lift_prs.js.map +1 -0
- package/dist/projections/live_hr.js +19 -0
- package/dist/projections/live_hr.js.map +1 -0
- package/dist/projections/live_state.js +23 -0
- package/dist/projections/live_state.js.map +1 -0
- package/dist/projections/live_stress.js +11 -0
- package/dist/projections/live_stress.js.map +1 -0
- package/dist/projections/performance_assessment.js +15 -0
- package/dist/projections/performance_assessment.js.map +1 -0
- package/dist/projections/profile.js +59 -0
- package/dist/projections/profile.js.map +1 -0
- package/dist/projections/recovery.js +131 -0
- package/dist/projections/recovery.js.map +1 -0
- package/dist/projections/sleep.js +256 -0
- package/dist/projections/sleep.js.map +1 -0
- package/dist/projections/sleep_need.js +32 -0
- package/dist/projections/sleep_need.js.map +1 -0
- package/dist/projections/smart_alarm.js +45 -0
- package/dist/projections/smart_alarm.js.map +1 -0
- package/dist/projections/strain.js +128 -0
- package/dist/projections/strain.js.map +1 -0
- package/dist/projections/stress.js +86 -0
- package/dist/projections/stress.js.map +1 -0
- package/dist/projections/today.js +129 -0
- package/dist/projections/today.js.map +1 -0
- package/dist/projections/trend.js +149 -0
- package/dist/projections/trend.js.map +1 -0
- package/dist/projections/workout.js +161 -0
- package/dist/projections/workout.js.map +1 -0
- package/dist/projections/workouts.js +37 -0
- package/dist/projections/workouts.js.map +1 -0
- package/dist/schemas/calendar.js +12 -0
- package/dist/schemas/calendar.js.map +1 -0
- package/dist/schemas/coach.js +11 -0
- package/dist/schemas/coach.js.map +1 -0
- package/dist/schemas/communities.js +51 -0
- package/dist/schemas/communities.js.map +1 -0
- package/dist/schemas/compare.js +15 -0
- package/dist/schemas/compare.js.map +1 -0
- package/dist/schemas/escape.js +18 -0
- package/dist/schemas/escape.js.map +1 -0
- package/dist/schemas/journal.js +69 -0
- package/dist/schemas/journal.js.map +1 -0
- package/dist/schemas/leaderboard.js +25 -0
- package/dist/schemas/leaderboard.js.map +1 -0
- package/dist/schemas/live.js +26 -0
- package/dist/schemas/live.js.map +1 -0
- package/dist/schemas/performance.js +12 -0
- package/dist/schemas/performance.js.map +1 -0
- package/dist/schemas/primitives.js +29 -0
- package/dist/schemas/primitives.js.map +1 -0
- package/dist/schemas/profile.js +39 -0
- package/dist/schemas/profile.js.map +1 -0
- package/dist/schemas/recovery.js +27 -0
- package/dist/schemas/recovery.js.map +1 -0
- package/dist/schemas/settings.js +26 -0
- package/dist/schemas/settings.js.map +1 -0
- package/dist/schemas/sleep.js +38 -0
- package/dist/schemas/sleep.js.map +1 -0
- package/dist/schemas/sleep_need.js +15 -0
- package/dist/schemas/sleep_need.js.map +1 -0
- package/dist/schemas/smart_alarm.js +36 -0
- package/dist/schemas/smart_alarm.js.map +1 -0
- package/dist/schemas/strain.js +24 -0
- package/dist/schemas/strain.js.map +1 -0
- package/dist/schemas/strength.js +170 -0
- package/dist/schemas/strength.js.map +1 -0
- package/dist/schemas/stress.js +16 -0
- package/dist/schemas/stress.js.map +1 -0
- package/dist/schemas/today.js +38 -0
- package/dist/schemas/today.js.map +1 -0
- package/dist/schemas/trend.js +50 -0
- package/dist/schemas/trend.js.map +1 -0
- package/dist/schemas/womens_health.js +23 -0
- package/dist/schemas/womens_health.js.map +1 -0
- package/dist/schemas/workouts.js +50 -0
- package/dist/schemas/workouts.js.map +1 -0
- package/dist/scripts/cognito_bootstrap.js +278 -0
- package/dist/scripts/cognito_bootstrap.js.map +1 -0
- package/dist/server-http.js +221 -0
- package/dist/server-http.js.map +1 -0
- package/dist/server.js +74 -0
- package/dist/server.js.map +1 -0
- package/dist/tools/register.js +117 -0
- package/dist/tools/register.js.map +1 -0
- package/dist/tools/v2/activity_create.js +64 -0
- package/dist/tools/v2/activity_create.js.map +1 -0
- package/dist/tools/v2/activity_delete.js +26 -0
- package/dist/tools/v2/activity_delete.js.map +1 -0
- package/dist/tools/v2/behavior_impact.js +36 -0
- package/dist/tools/v2/behavior_impact.js.map +1 -0
- package/dist/tools/v2/calendar.js +28 -0
- package/dist/tools/v2/calendar.js.map +1 -0
- package/dist/tools/v2/coach_ask.js +117 -0
- package/dist/tools/v2/coach_ask.js.map +1 -0
- package/dist/tools/v2/communities.js +60 -0
- package/dist/tools/v2/communities.js.map +1 -0
- package/dist/tools/v2/compare.js +67 -0
- package/dist/tools/v2/compare.js.map +1 -0
- package/dist/tools/v2/cycle.js +23 -0
- package/dist/tools/v2/cycle.js.map +1 -0
- package/dist/tools/v2/cycle_log.js +43 -0
- package/dist/tools/v2/cycle_log.js.map +1 -0
- package/dist/tools/v2/day.js +32 -0
- package/dist/tools/v2/day.js.map +1 -0
- package/dist/tools/v2/endpoints.js +28 -0
- package/dist/tools/v2/endpoints.js.map +1 -0
- package/dist/tools/v2/hidden_metric.js +28 -0
- package/dist/tools/v2/hidden_metric.js.map +1 -0
- package/dist/tools/v2/hr_zones.js +24 -0
- package/dist/tools/v2/hr_zones.js.map +1 -0
- package/dist/tools/v2/hr_zones_set.js +51 -0
- package/dist/tools/v2/hr_zones_set.js.map +1 -0
- package/dist/tools/v2/journal.js +26 -0
- package/dist/tools/v2/journal.js.map +1 -0
- package/dist/tools/v2/journal_autopop.js +19 -0
- package/dist/tools/v2/journal_autopop.js.map +1 -0
- package/dist/tools/v2/journal_catalog.js +44 -0
- package/dist/tools/v2/journal_catalog.js.map +1 -0
- package/dist/tools/v2/journal_log.js +78 -0
- package/dist/tools/v2/journal_log.js.map +1 -0
- package/dist/tools/v2/leaderboard.js +79 -0
- package/dist/tools/v2/leaderboard.js.map +1 -0
- package/dist/tools/v2/lift_catalog.js +47 -0
- package/dist/tools/v2/lift_catalog.js.map +1 -0
- package/dist/tools/v2/lift_custom_exercise.js +108 -0
- package/dist/tools/v2/lift_custom_exercise.js.map +1 -0
- package/dist/tools/v2/lift_exercise.js +31 -0
- package/dist/tools/v2/lift_exercise.js.map +1 -0
- package/dist/tools/v2/lift_history.js +39 -0
- package/dist/tools/v2/lift_history.js.map +1 -0
- package/dist/tools/v2/lift_library.js +22 -0
- package/dist/tools/v2/lift_library.js.map +1 -0
- package/dist/tools/v2/lift_log.js +95 -0
- package/dist/tools/v2/lift_log.js.map +1 -0
- package/dist/tools/v2/lift_progression.js +30 -0
- package/dist/tools/v2/lift_progression.js.map +1 -0
- package/dist/tools/v2/lift_prs.js +21 -0
- package/dist/tools/v2/lift_prs.js.map +1 -0
- package/dist/tools/v2/lift_template_save.js +83 -0
- package/dist/tools/v2/lift_template_save.js.map +1 -0
- package/dist/tools/v2/live_hr.js +21 -0
- package/dist/tools/v2/live_hr.js.map +1 -0
- package/dist/tools/v2/live_state.js +21 -0
- package/dist/tools/v2/live_state.js.map +1 -0
- package/dist/tools/v2/live_stress.js +22 -0
- package/dist/tools/v2/live_stress.js.map +1 -0
- package/dist/tools/v2/performance_assessment.js +38 -0
- package/dist/tools/v2/performance_assessment.js.map +1 -0
- package/dist/tools/v2/profile.js +28 -0
- package/dist/tools/v2/profile.js.map +1 -0
- package/dist/tools/v2/profile_update.js +66 -0
- package/dist/tools/v2/profile_update.js.map +1 -0
- package/dist/tools/v2/raw.js +43 -0
- package/dist/tools/v2/raw.js.map +1 -0
- package/dist/tools/v2/recovery.js +31 -0
- package/dist/tools/v2/recovery.js.map +1 -0
- package/dist/tools/v2/sleep.js +23 -0
- package/dist/tools/v2/sleep.js.map +1 -0
- package/dist/tools/v2/sleep_need.js +21 -0
- package/dist/tools/v2/sleep_need.js.map +1 -0
- package/dist/tools/v2/smart_alarm.js +24 -0
- package/dist/tools/v2/smart_alarm.js.map +1 -0
- package/dist/tools/v2/smart_alarm_set.js +94 -0
- package/dist/tools/v2/smart_alarm_set.js.map +1 -0
- package/dist/tools/v2/sports_catalog.js +26 -0
- package/dist/tools/v2/sports_catalog.js.map +1 -0
- package/dist/tools/v2/strain.js +23 -0
- package/dist/tools/v2/strain.js.map +1 -0
- package/dist/tools/v2/stress.js +23 -0
- package/dist/tools/v2/stress.js.map +1 -0
- package/dist/tools/v2/symptom_log.js +72 -0
- package/dist/tools/v2/symptom_log.js.map +1 -0
- package/dist/tools/v2/today.js +30 -0
- package/dist/tools/v2/today.js.map +1 -0
- package/dist/tools/v2/trend.js +26 -0
- package/dist/tools/v2/trend.js.map +1 -0
- package/dist/tools/v2/workout.js +23 -0
- package/dist/tools/v2/workout.js.map +1 -0
- package/dist/tools/v2/workouts.js +32 -0
- package/dist/tools/v2/workouts.js.map +1 -0
- package/dist/whoop/build_lift_body.js +67 -0
- package/dist/whoop/build_lift_body.js.map +1 -0
- package/dist/whoop/client.js +84 -0
- package/dist/whoop/client.js.map +1 -0
- package/dist/whoop/cognito.js +110 -0
- package/dist/whoop/cognito.js.map +1 -0
- package/dist/whoop/constants.js +4 -0
- package/dist/whoop/constants.js.map +1 -0
- package/dist/whoop/device.js +103 -0
- package/dist/whoop/device.js.map +1 -0
- package/dist/whoop/errors.js +42 -0
- package/dist/whoop/errors.js.map +1 -0
- package/dist/whoop/init_timezone.js +62 -0
- package/dist/whoop/init_timezone.js.map +1 -0
- package/dist/whoop/installation.js +62 -0
- package/dist/whoop/installation.js.map +1 -0
- package/dist/whoop/json_out.js +9 -0
- package/dist/whoop/json_out.js.map +1 -0
- package/dist/whoop/oauth_provider.js +297 -0
- package/dist/whoop/oauth_provider.js.map +1 -0
- package/dist/whoop/session_state.js +34 -0
- package/dist/whoop/session_state.js.map +1 -0
- package/dist/whoop/token_manager.js +60 -0
- package/dist/whoop/token_manager.js.map +1 -0
- package/dist/whoop/token_store.js +47 -0
- package/dist/whoop/token_store.js.map +1 -0
- package/dist/whoop/types.js +82 -0
- package/dist/whoop/types.js.map +1 -0
- package/dist/whoop/write_safety.js +23 -0
- package/dist/whoop/write_safety.js.map +1 -0
- package/package.json +66 -0
- package/src/cli/index.ts +597 -0
- package/src/cli/setup.ts +1106 -0
- package/src/cli/ui.ts +505 -0
- package/src/cli/update.ts +442 -0
- package/src/data/behaviors.ts +2784 -0
- package/src/data/endpoints.ts +319 -0
- package/src/data/exercises.ts +4868 -0
- package/src/data/sports.ts +218 -0
- package/src/lib/concurrency.ts +28 -0
- package/src/lib/dates.ts +35 -0
- package/src/lib/format.ts +27 -0
- package/src/lib/stats.ts +35 -0
- package/src/lib/timezone.ts +269 -0
- package/src/lib/walk.ts +418 -0
- package/src/projections/behavior_impact.ts +98 -0
- package/src/projections/calendar.ts +46 -0
- package/src/projections/communities.ts +135 -0
- package/src/projections/cycle.ts +85 -0
- package/src/projections/hr_zones.ts +43 -0
- package/src/projections/journal.ts +55 -0
- package/src/projections/leaderboard.ts +49 -0
- package/src/projections/lift_exercise.ts +29 -0
- package/src/projections/lift_history.ts +140 -0
- package/src/projections/lift_library.ts +70 -0
- package/src/projections/lift_progression.ts +138 -0
- package/src/projections/lift_prs.ts +23 -0
- package/src/projections/live_hr.ts +21 -0
- package/src/projections/live_state.ts +28 -0
- package/src/projections/live_stress.ts +13 -0
- package/src/projections/performance_assessment.ts +19 -0
- package/src/projections/profile.ts +71 -0
- package/src/projections/recovery.ts +133 -0
- package/src/projections/sleep.ts +276 -0
- package/src/projections/sleep_need.ts +36 -0
- package/src/projections/smart_alarm.ts +70 -0
- package/src/projections/strain.ts +131 -0
- package/src/projections/stress.ts +95 -0
- package/src/projections/today.ts +166 -0
- package/src/projections/trend.ts +149 -0
- package/src/projections/workout.ts +168 -0
- package/src/projections/workouts.ts +36 -0
- package/src/schemas/calendar.ts +13 -0
- package/src/schemas/coach.ts +11 -0
- package/src/schemas/communities.ts +56 -0
- package/src/schemas/compare.ts +17 -0
- package/src/schemas/escape.ts +21 -0
- package/src/schemas/journal.ts +80 -0
- package/src/schemas/leaderboard.ts +26 -0
- package/src/schemas/live.ts +31 -0
- package/src/schemas/performance.ts +13 -0
- package/src/schemas/primitives.ts +35 -0
- package/src/schemas/profile.ts +40 -0
- package/src/schemas/recovery.ts +28 -0
- package/src/schemas/settings.ts +30 -0
- package/src/schemas/sleep.ts +40 -0
- package/src/schemas/sleep_need.ts +16 -0
- package/src/schemas/smart_alarm.ts +40 -0
- package/src/schemas/strain.ts +25 -0
- package/src/schemas/strength.ts +189 -0
- package/src/schemas/stress.ts +17 -0
- package/src/schemas/today.ts +39 -0
- package/src/schemas/trend.ts +53 -0
- package/src/schemas/womens_health.ts +26 -0
- package/src/schemas/workouts.ts +55 -0
- package/src/scripts/cognito_bootstrap.ts +249 -0
- package/src/server-http.ts +241 -0
- package/src/server.ts +85 -0
- package/src/tools/register.ts +120 -0
- package/src/tools/v2/activity_create.ts +74 -0
- package/src/tools/v2/activity_delete.ts +33 -0
- package/src/tools/v2/behavior_impact.ts +39 -0
- package/src/tools/v2/calendar.ts +33 -0
- package/src/tools/v2/coach_ask.ts +131 -0
- package/src/tools/v2/communities.ts +65 -0
- package/src/tools/v2/compare.ts +83 -0
- package/src/tools/v2/cycle.ts +28 -0
- package/src/tools/v2/cycle_log.ts +51 -0
- package/src/tools/v2/day.ts +37 -0
- package/src/tools/v2/endpoints.ts +32 -0
- package/src/tools/v2/hidden_metric.ts +33 -0
- package/src/tools/v2/hr_zones.ts +29 -0
- package/src/tools/v2/hr_zones_set.ts +57 -0
- package/src/tools/v2/journal.ts +31 -0
- package/src/tools/v2/journal_autopop.ts +26 -0
- package/src/tools/v2/journal_catalog.ts +48 -0
- package/src/tools/v2/journal_log.ts +84 -0
- package/src/tools/v2/leaderboard.ts +92 -0
- package/src/tools/v2/lift_catalog.ts +48 -0
- package/src/tools/v2/lift_custom_exercise.ts +117 -0
- package/src/tools/v2/lift_exercise.ts +35 -0
- package/src/tools/v2/lift_history.ts +52 -0
- package/src/tools/v2/lift_library.ts +28 -0
- package/src/tools/v2/lift_log.ts +102 -0
- package/src/tools/v2/lift_progression.ts +34 -0
- package/src/tools/v2/lift_prs.ts +26 -0
- package/src/tools/v2/lift_template_save.ts +89 -0
- package/src/tools/v2/live_hr.ts +26 -0
- package/src/tools/v2/live_state.ts +26 -0
- package/src/tools/v2/live_stress.ts +27 -0
- package/src/tools/v2/performance_assessment.ts +44 -0
- package/src/tools/v2/profile.ts +33 -0
- package/src/tools/v2/profile_update.ts +76 -0
- package/src/tools/v2/raw.ts +50 -0
- package/src/tools/v2/recovery.ts +36 -0
- package/src/tools/v2/sleep.ts +28 -0
- package/src/tools/v2/sleep_need.ts +26 -0
- package/src/tools/v2/smart_alarm.ts +29 -0
- package/src/tools/v2/smart_alarm_set.ts +103 -0
- package/src/tools/v2/sports_catalog.ts +32 -0
- package/src/tools/v2/strain.ts +28 -0
- package/src/tools/v2/stress.ts +28 -0
- package/src/tools/v2/symptom_log.ts +78 -0
- package/src/tools/v2/today.ts +35 -0
- package/src/tools/v2/trend.ts +31 -0
- package/src/tools/v2/workout.ts +28 -0
- package/src/tools/v2/workouts.ts +37 -0
- package/src/whoop/build_lift_body.ts +84 -0
- package/src/whoop/client.ts +118 -0
- package/src/whoop/cognito.ts +150 -0
- package/src/whoop/constants.ts +3 -0
- package/src/whoop/device.ts +106 -0
- package/src/whoop/errors.ts +41 -0
- package/src/whoop/init_timezone.ts +64 -0
- package/src/whoop/installation.ts +58 -0
- package/src/whoop/json_out.ts +9 -0
- package/src/whoop/oauth_provider.ts +377 -0
- package/src/whoop/session_state.ts +41 -0
- package/src/whoop/token_manager.ts +76 -0
- package/src/whoop/token_store.ts +45 -0
- package/src/whoop/types.ts +89 -0
- package/src/whoop/write_safety.ts +30 -0
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
// Minimal OAuth 2.1 + PKCE authorization server for totem, so the deployed
|
|
2
|
+
// server can be added as a "custom connector" on claude.ai web + the Claude
|
|
3
|
+
// mobile app (those clients require OAuth — they have no bearer-token field).
|
|
4
|
+
//
|
|
5
|
+
// Design for a single-user, auto-stopping host (Fly):
|
|
6
|
+
// - Access + refresh tokens are stateless HS256 JWTs signed with a server
|
|
7
|
+
// secret. No token store → they survive machine restarts.
|
|
8
|
+
// - Registered clients (dynamic client registration) are also stateless: the
|
|
9
|
+
// client_id is itself a signed token encoding the client's redirect_uris.
|
|
10
|
+
// getClient() verifies + decodes it, so clients survive restarts too and
|
|
11
|
+
// Claude never has to re-register after a cold start.
|
|
12
|
+
// - Authorization codes are the only in-memory state. They live ~60s (the gap
|
|
13
|
+
// between the user approving and Claude redeeming the code), so a restart in
|
|
14
|
+
// that window just means re-clicking approve. Negligible.
|
|
15
|
+
// - The /authorize step is gated by a password (AUTH_PASSWORD). The user
|
|
16
|
+
// enters it once when adding the connector; on success a code is issued.
|
|
17
|
+
// - verifyAccessToken also accepts the static MCP_AUTH_TOKEN, so Claude Code
|
|
18
|
+
// (--header) and the Claude Desktop mcp-remote bridge keep working unchanged.
|
|
19
|
+
|
|
20
|
+
import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
21
|
+
import type { Response } from "express";
|
|
22
|
+
import type {
|
|
23
|
+
OAuthServerProvider,
|
|
24
|
+
AuthorizationParams,
|
|
25
|
+
} from "@modelcontextprotocol/sdk/server/auth/provider.js";
|
|
26
|
+
import type { OAuthRegisteredClientsStore } from "@modelcontextprotocol/sdk/server/auth/clients.js";
|
|
27
|
+
import type {
|
|
28
|
+
OAuthClientInformationFull,
|
|
29
|
+
OAuthTokens,
|
|
30
|
+
} from "@modelcontextprotocol/sdk/shared/auth.js";
|
|
31
|
+
import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
|
|
32
|
+
import { InvalidTokenError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
|
|
33
|
+
|
|
34
|
+
const ACCESS_TTL_S = 3600; // 1 hour
|
|
35
|
+
const REFRESH_TTL_S = 30 * 24 * 3600; // 30 days
|
|
36
|
+
const CODE_TTL_MS = 60_000; // 60 seconds
|
|
37
|
+
|
|
38
|
+
// ─── tiny HS256 JWT (no external dep) ──────────────────────────────────────
|
|
39
|
+
function b64url(buf: Buffer): string {
|
|
40
|
+
return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
41
|
+
}
|
|
42
|
+
function b64urlDecode(s: string): Buffer {
|
|
43
|
+
return Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
44
|
+
}
|
|
45
|
+
function signToken(payload: Record<string, unknown>, secret: string): string {
|
|
46
|
+
const header = b64url(Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })));
|
|
47
|
+
const body = b64url(Buffer.from(JSON.stringify(payload)));
|
|
48
|
+
const data = `${header}.${body}`;
|
|
49
|
+
const sig = b64url(createHmac("sha256", secret).update(data).digest());
|
|
50
|
+
return `${data}.${sig}`;
|
|
51
|
+
}
|
|
52
|
+
function verifyToken(token: string, secret: string): Record<string, unknown> | null {
|
|
53
|
+
const parts = token.split(".");
|
|
54
|
+
if (parts.length !== 3) return null;
|
|
55
|
+
const [h, b, s] = parts as [string, string, string];
|
|
56
|
+
const expected = b64url(createHmac("sha256", secret).update(`${h}.${b}`).digest());
|
|
57
|
+
const sBuf = Buffer.from(s);
|
|
58
|
+
const eBuf = Buffer.from(expected);
|
|
59
|
+
if (sBuf.length !== eBuf.length || !timingSafeEqual(sBuf, eBuf)) return null;
|
|
60
|
+
try {
|
|
61
|
+
const payload = JSON.parse(b64urlDecode(b).toString("utf8")) as Record<string, unknown>;
|
|
62
|
+
if (typeof payload.exp === "number" && Date.now() / 1000 > payload.exp) return null;
|
|
63
|
+
return payload;
|
|
64
|
+
} catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function constantTimeEqual(a: string, b: string): boolean {
|
|
70
|
+
const ba = Buffer.from(a);
|
|
71
|
+
const bb = Buffer.from(b);
|
|
72
|
+
return ba.length === bb.length && timingSafeEqual(ba, bb);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface AuthCodeEntry {
|
|
76
|
+
challenge: string;
|
|
77
|
+
redirectUri: string;
|
|
78
|
+
clientId: string;
|
|
79
|
+
scopes: string[];
|
|
80
|
+
resource: string | undefined;
|
|
81
|
+
expiresAt: number;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface WhoopOAuthOptions {
|
|
85
|
+
/** Secret used to sign JWT tokens + client IDs. */
|
|
86
|
+
signingSecret: string;
|
|
87
|
+
/** Password the user enters at /authorize. */
|
|
88
|
+
password: string;
|
|
89
|
+
/** Static bearer token (MCP_AUTH_TOKEN) kept working for Claude Code / Desktop bridge. */
|
|
90
|
+
staticToken: string;
|
|
91
|
+
/** This server's MCP resource URL (…/mcp). When set, a token carrying a
|
|
92
|
+
* `resource` claim must match it — so a token minted for a different server
|
|
93
|
+
* can't be replayed here (RFC 8707 audience binding). */
|
|
94
|
+
resourceUrl?: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export class WhoopOAuthProvider implements OAuthServerProvider {
|
|
98
|
+
private readonly codes = new Map<string, AuthCodeEntry>();
|
|
99
|
+
private readonly signingSecret: string;
|
|
100
|
+
private readonly password: string;
|
|
101
|
+
private readonly staticToken: string;
|
|
102
|
+
private readonly resourceUrl: string | undefined;
|
|
103
|
+
|
|
104
|
+
constructor(opts: WhoopOAuthOptions) {
|
|
105
|
+
this.signingSecret = opts.signingSecret;
|
|
106
|
+
this.password = opts.password;
|
|
107
|
+
this.staticToken = opts.staticToken;
|
|
108
|
+
this.resourceUrl = opts.resourceUrl;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Decode the stateless signed client_id back into client info (synchronous).
|
|
112
|
+
private decodeClient(clientId: string): OAuthClientInformationFull | undefined {
|
|
113
|
+
if (!clientId.startsWith("c.")) return undefined;
|
|
114
|
+
const payload = verifyToken(clientId.slice(2), this.signingSecret);
|
|
115
|
+
if (!payload || payload.t !== "client") return undefined;
|
|
116
|
+
return {
|
|
117
|
+
client_id: clientId,
|
|
118
|
+
redirect_uris: (payload.ru as string[]) ?? [],
|
|
119
|
+
token_endpoint_auth_method: "none",
|
|
120
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
121
|
+
response_types: ["code"],
|
|
122
|
+
scope: (payload.sc as string) ?? "",
|
|
123
|
+
} as OAuthClientInformationFull;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ─── stateless client store (DCR) ────────────────────────────────────────
|
|
127
|
+
get clientsStore(): OAuthRegisteredClientsStore {
|
|
128
|
+
return {
|
|
129
|
+
getClient: (clientId: string): OAuthClientInformationFull | undefined =>
|
|
130
|
+
this.decodeClient(clientId),
|
|
131
|
+
registerClient: (
|
|
132
|
+
client: Omit<OAuthClientInformationFull, "client_id" | "client_id_issued_at">,
|
|
133
|
+
): OAuthClientInformationFull => {
|
|
134
|
+
// Encode the client's redirect_uris into a signed client_id so the
|
|
135
|
+
// registration survives server restarts with no storage.
|
|
136
|
+
const signed = signToken(
|
|
137
|
+
{ t: "client", ru: client.redirect_uris ?? [], sc: client.scope ?? "", jti: randomUUID() },
|
|
138
|
+
this.signingSecret,
|
|
139
|
+
);
|
|
140
|
+
const clientId = `c.${signed}`;
|
|
141
|
+
return {
|
|
142
|
+
...client,
|
|
143
|
+
client_id: clientId,
|
|
144
|
+
client_id_issued_at: Math.floor(Date.now() / 1000),
|
|
145
|
+
} as OAuthClientInformationFull;
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ─── authorize: render the password form ─────────────────────────────────
|
|
151
|
+
// The SDK's authorize handler validated client_id + redirect_uri + PKCE and
|
|
152
|
+
// calls this. We render an HTML form that POSTs the password (plus the OAuth
|
|
153
|
+
// params as hidden fields) to /oauth/consent, which we handle ourselves.
|
|
154
|
+
async authorize(
|
|
155
|
+
client: OAuthClientInformationFull,
|
|
156
|
+
params: AuthorizationParams,
|
|
157
|
+
res: Response,
|
|
158
|
+
): Promise<void> {
|
|
159
|
+
setConsentSecurityHeaders(res);
|
|
160
|
+
res.setHeader("content-type", "text/html; charset=utf-8");
|
|
161
|
+
res.setHeader("cache-control", "no-store");
|
|
162
|
+
res.end(renderConsentForm({
|
|
163
|
+
clientId: client.client_id,
|
|
164
|
+
redirectUri: params.redirectUri,
|
|
165
|
+
codeChallenge: params.codeChallenge,
|
|
166
|
+
state: params.state ?? "",
|
|
167
|
+
scopes: (params.scopes ?? []).join(" "),
|
|
168
|
+
resource: params.resource?.toString() ?? "",
|
|
169
|
+
error: false,
|
|
170
|
+
}));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ─── consent POST: validate password, issue an auth code ─────────────────
|
|
174
|
+
// Returns the redirect URL to send the browser to, or null if the password
|
|
175
|
+
// was wrong (caller re-renders the form with an error).
|
|
176
|
+
consent(input: {
|
|
177
|
+
clientId: string;
|
|
178
|
+
redirectUri: string;
|
|
179
|
+
codeChallenge: string;
|
|
180
|
+
state: string;
|
|
181
|
+
scopes: string;
|
|
182
|
+
resource: string;
|
|
183
|
+
password: string;
|
|
184
|
+
}): string | null {
|
|
185
|
+
if (!constantTimeEqual(input.password, this.password)) {
|
|
186
|
+
console.error("[totem] consent REJECTED: password mismatch");
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
// Validate the client + redirect again (defense in depth).
|
|
190
|
+
const client = this.decodeClient(input.clientId);
|
|
191
|
+
if (!client) {
|
|
192
|
+
console.error("[totem] consent REJECTED: client_id failed to decode (stale registration / signing-key mismatch) — password was correct");
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
if (!client.redirect_uris.includes(input.redirectUri)) {
|
|
196
|
+
console.error(`[totem] consent REJECTED: redirect_uri not registered: ${input.redirectUri} — password was correct`);
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const code = b64url(randomBytes(32));
|
|
201
|
+
this.codes.set(code, {
|
|
202
|
+
challenge: input.codeChallenge,
|
|
203
|
+
redirectUri: input.redirectUri,
|
|
204
|
+
clientId: input.clientId,
|
|
205
|
+
scopes: input.scopes ? input.scopes.split(" ").filter(Boolean) : [],
|
|
206
|
+
resource: input.resource || undefined,
|
|
207
|
+
expiresAt: Date.now() + CODE_TTL_MS,
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
const url = new URL(input.redirectUri);
|
|
211
|
+
url.searchParams.set("code", code);
|
|
212
|
+
if (input.state) url.searchParams.set("state", input.state);
|
|
213
|
+
return url.toString();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async challengeForAuthorizationCode(
|
|
217
|
+
client: OAuthClientInformationFull,
|
|
218
|
+
authorizationCode: string,
|
|
219
|
+
): Promise<string> {
|
|
220
|
+
const entry = this.codes.get(authorizationCode);
|
|
221
|
+
if (!entry || entry.expiresAt < Date.now() || entry.clientId !== client.client_id) {
|
|
222
|
+
throw new Error("invalid or expired authorization code");
|
|
223
|
+
}
|
|
224
|
+
return entry.challenge;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async exchangeAuthorizationCode(
|
|
228
|
+
client: OAuthClientInformationFull,
|
|
229
|
+
authorizationCode: string,
|
|
230
|
+
): Promise<OAuthTokens> {
|
|
231
|
+
const entry = this.codes.get(authorizationCode);
|
|
232
|
+
if (!entry || entry.expiresAt < Date.now() || entry.clientId !== client.client_id) {
|
|
233
|
+
throw new Error("invalid or expired authorization code");
|
|
234
|
+
}
|
|
235
|
+
this.codes.delete(authorizationCode); // one-time use
|
|
236
|
+
return this.issueTokens(client.client_id, entry.scopes, entry.resource);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async exchangeRefreshToken(
|
|
240
|
+
client: OAuthClientInformationFull,
|
|
241
|
+
refreshToken: string,
|
|
242
|
+
scopes?: string[],
|
|
243
|
+
): Promise<OAuthTokens> {
|
|
244
|
+
const payload = verifyToken(refreshToken, this.signingSecret);
|
|
245
|
+
if (!payload || payload.typ !== "refresh" || payload.cid !== client.client_id) {
|
|
246
|
+
throw new Error("invalid refresh token");
|
|
247
|
+
}
|
|
248
|
+
const grantScopes = scopes ?? ((payload.scopes as string[]) ?? []);
|
|
249
|
+
return this.issueTokens(client.client_id, grantScopes, payload.resource as string | undefined);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
private issueTokens(clientId: string, scopes: string[], resource: string | undefined): OAuthTokens {
|
|
253
|
+
const now = Math.floor(Date.now() / 1000);
|
|
254
|
+
const base = { cid: clientId, scopes, resource, iat: now };
|
|
255
|
+
const access = signToken({ ...base, typ: "access", exp: now + ACCESS_TTL_S }, this.signingSecret);
|
|
256
|
+
const refresh = signToken({ ...base, typ: "refresh", exp: now + REFRESH_TTL_S }, this.signingSecret);
|
|
257
|
+
return {
|
|
258
|
+
access_token: access,
|
|
259
|
+
token_type: "Bearer",
|
|
260
|
+
expires_in: ACCESS_TTL_S,
|
|
261
|
+
refresh_token: refresh,
|
|
262
|
+
scope: scopes.join(" "),
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async verifyAccessToken(token: string): Promise<AuthInfo> {
|
|
267
|
+
// 1. Static token — keeps Claude Code + Desktop-bridge working. The SDK's
|
|
268
|
+
// bearer middleware requires a numeric expiresAt, so give it a far-future
|
|
269
|
+
// one (the static token doesn't expire on its own).
|
|
270
|
+
if (this.staticToken && constantTimeEqual(token, this.staticToken)) {
|
|
271
|
+
return {
|
|
272
|
+
token,
|
|
273
|
+
clientId: "static",
|
|
274
|
+
scopes: [],
|
|
275
|
+
expiresAt: Math.floor(Date.now() / 1000) + REFRESH_TTL_S,
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
// 2. OAuth-issued JWT.
|
|
279
|
+
const payload = verifyToken(token, this.signingSecret);
|
|
280
|
+
if (payload && payload.typ === "access") {
|
|
281
|
+
// Audience binding (RFC 8707): a token carrying a `resource` claim should
|
|
282
|
+
// only be valid at the server it was minted for. LOG-ONLY for now (no
|
|
283
|
+
// reject): rejecting on a mismatch would 401 a valid Claude token and
|
|
284
|
+
// brick the connector, and the exact `resource` value Claude sends isn't
|
|
285
|
+
// verified yet. The log tells us whether a real token would have matched;
|
|
286
|
+
// flip back to throwing once confirmed.
|
|
287
|
+
if (this.resourceUrl && typeof payload.resource === "string") {
|
|
288
|
+
const norm = (u: string): string => u.replace(/\/+$/, "");
|
|
289
|
+
if (norm(payload.resource) !== norm(this.resourceUrl)) {
|
|
290
|
+
console.error(`[totem] token resource mismatch (got "${payload.resource}", expected "${this.resourceUrl}") — allowing; enforcement is disabled`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const info: AuthInfo = {
|
|
294
|
+
token,
|
|
295
|
+
clientId: String(payload.cid),
|
|
296
|
+
scopes: (payload.scopes as string[]) ?? [],
|
|
297
|
+
expiresAt: payload.exp as number,
|
|
298
|
+
};
|
|
299
|
+
if (typeof payload.resource === "string") info.resource = new URL(payload.resource);
|
|
300
|
+
return info;
|
|
301
|
+
}
|
|
302
|
+
// Throw the SDK's typed error so the bearer middleware returns 401 (a
|
|
303
|
+
// generic Error would be mapped to 500).
|
|
304
|
+
throw new InvalidTokenError("invalid or expired access token");
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Anti-clickjacking header for the HTML consent page (a password form) ONLY.
|
|
309
|
+
// Deliberately NO Content-Security-Policy: a `form-action` directive blocks the
|
|
310
|
+
// OAuth 302 redirect back to the client (the browser refuses the cross-origin
|
|
311
|
+
// navigation to claude.ai), silently bricking the password submit; and a
|
|
312
|
+
// document CSP on the JSON metadata/API responses made Claude's connector flag
|
|
313
|
+
// a "server configuration issue". X-Frame-Options: DENY is the clickjacking
|
|
314
|
+
// control this page actually needs, and the page has no scripts/external
|
|
315
|
+
// resources to lock down.
|
|
316
|
+
export function setConsentSecurityHeaders(res: Response): void {
|
|
317
|
+
res.setHeader("X-Frame-Options", "DENY");
|
|
318
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
319
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// ─── consent form HTML ──────────────────────────────────────────────────────
|
|
323
|
+
export function renderConsentForm(d: {
|
|
324
|
+
clientId: string;
|
|
325
|
+
redirectUri: string;
|
|
326
|
+
codeChallenge: string;
|
|
327
|
+
state: string;
|
|
328
|
+
scopes: string;
|
|
329
|
+
resource: string;
|
|
330
|
+
error: boolean;
|
|
331
|
+
}): string {
|
|
332
|
+
const esc = (s: string): string =>
|
|
333
|
+
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
334
|
+
const errorBanner = d.error
|
|
335
|
+
? `<p style="color:#dc2626;margin:0 0 16px">Incorrect password. Try again.</p>`
|
|
336
|
+
: "";
|
|
337
|
+
return `<!doctype html>
|
|
338
|
+
<html lang="en">
|
|
339
|
+
<head>
|
|
340
|
+
<meta charset="utf-8">
|
|
341
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
342
|
+
<title>totem — authorize</title>
|
|
343
|
+
<style>
|
|
344
|
+
body { font-family: ui-monospace, "SF Mono", Menlo, monospace; background: #0d1117; color: #e6e6e6;
|
|
345
|
+
display: flex; min-height: 100vh; align-items: center; justify-content: center; margin: 0; }
|
|
346
|
+
.card { background: #161b22; border: 1px solid #30363d; border-radius: 12px; padding: 32px;
|
|
347
|
+
width: 320px; box-shadow: 0 8px 32px rgba(0,0,0,.4); }
|
|
348
|
+
h1 { font-size: 18px; margin: 0 0 4px; }
|
|
349
|
+
p.sub { color: #969696; font-size: 13px; margin: 0 0 24px; }
|
|
350
|
+
label { display: block; font-size: 13px; margin: 0 0 8px; color: #b0b0b0; }
|
|
351
|
+
input[type=password] { width: 100%; box-sizing: border-box; padding: 10px 12px; border-radius: 8px;
|
|
352
|
+
border: 1px solid #30363d; background: #0d1117; color: #e6e6e6; font-size: 14px; margin: 0 0 20px; }
|
|
353
|
+
button { width: 100%; padding: 11px; border: none; border-radius: 8px; background: #e6e6e6; color: #0d1117;
|
|
354
|
+
font-weight: 700; font-size: 14px; cursor: pointer; }
|
|
355
|
+
button:hover { background: #fff; }
|
|
356
|
+
</style>
|
|
357
|
+
</head>
|
|
358
|
+
<body>
|
|
359
|
+
<div class="card">
|
|
360
|
+
<h1>totem</h1>
|
|
361
|
+
<p class="sub">Enter your access password to connect this server to Claude.</p>
|
|
362
|
+
${errorBanner}
|
|
363
|
+
<form method="POST" action="/oauth/consent">
|
|
364
|
+
<input type="hidden" name="client_id" value="${esc(d.clientId)}">
|
|
365
|
+
<input type="hidden" name="redirect_uri" value="${esc(d.redirectUri)}">
|
|
366
|
+
<input type="hidden" name="code_challenge" value="${esc(d.codeChallenge)}">
|
|
367
|
+
<input type="hidden" name="state" value="${esc(d.state)}">
|
|
368
|
+
<input type="hidden" name="scope" value="${esc(d.scopes)}">
|
|
369
|
+
<input type="hidden" name="resource" value="${esc(d.resource)}">
|
|
370
|
+
<label for="pw">Password</label>
|
|
371
|
+
<input type="password" id="pw" name="password" autofocus autocomplete="current-password">
|
|
372
|
+
<button type="submit">Authorize</button>
|
|
373
|
+
</form>
|
|
374
|
+
</div>
|
|
375
|
+
</body>
|
|
376
|
+
</html>`;
|
|
377
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Per-process "catalog consulted" gate. (One Set per server process. In stdio
|
|
2
|
+
// mode that's one client; in HTTP multi-session mode it's shared across
|
|
3
|
+
// sessions — harmless for this single-user MCP, but not literally per-session.)
|
|
4
|
+
//
|
|
5
|
+
// MCP servers run as a persistent process per client. Tools that take large-
|
|
6
|
+
// enum-style IDs (sport_id, exercise_id, behavior_tracker_id) refuse to run
|
|
7
|
+
// until the AI has called the corresponding lookup tool at least once in the
|
|
8
|
+
// session. This lets us keep example IDs out of every tool's description (saves
|
|
9
|
+
// ~3-5k system-prompt tokens per session) while still enforcing that the AI
|
|
10
|
+
// has actually seen the real catalog before guessing.
|
|
11
|
+
//
|
|
12
|
+
// Catalog → unlock tool → gated tools:
|
|
13
|
+
// sports ← whoop_sports_catalog → whoop_activity_create
|
|
14
|
+
// exercises ← whoop_lift_catalog → whoop_lift_log, whoop_lift_exercise,
|
|
15
|
+
// whoop_lift_progression, whoop_lift_template_save,
|
|
16
|
+
// whoop_lift_custom_exercise
|
|
17
|
+
// behaviors ← whoop_journal_catalog → whoop_journal_log, whoop_symptom_log
|
|
18
|
+
|
|
19
|
+
export type CatalogName = "sports" | "exercises" | "behaviors";
|
|
20
|
+
|
|
21
|
+
const consulted = new Set<CatalogName>();
|
|
22
|
+
|
|
23
|
+
export function markConsulted(c: CatalogName): void {
|
|
24
|
+
consulted.add(c);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function gateError(
|
|
28
|
+
catalog: CatalogName,
|
|
29
|
+
lookupTool: string,
|
|
30
|
+
): { error: string; hint: string } | null {
|
|
31
|
+
if (consulted.has(catalog)) return null;
|
|
32
|
+
return {
|
|
33
|
+
error: `Must call ${lookupTool} first to view the ${catalog} catalog. This MCP enforces lookup-first to keep tool descriptions small (your system prompt does not contain the full ${catalog} list).`,
|
|
34
|
+
hint: `Call ${lookupTool} once (e.g. with no args or with search='...') to unlock every tool that takes ${catalog} IDs for the rest of this session.`,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Test-only — reset state between matrix runs etc.
|
|
39
|
+
export function _resetConsulted(): void {
|
|
40
|
+
consulted.clear();
|
|
41
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Holds the current access token + refresh token, auto-refreshes via Cognito
|
|
2
|
+
// when the access token is within `refreshSkewSeconds` of expiry. Writes
|
|
3
|
+
// rotated tokens to an injected TokenStore so server restarts pick up fresh
|
|
4
|
+
// state without re-bootstrapping.
|
|
5
|
+
import { decodeJwtExp, refreshCognitoSession } from "./cognito.js";
|
|
6
|
+
import { EnvFileTokenStore, type TokenStore } from "./token_store.js";
|
|
7
|
+
|
|
8
|
+
export interface TokenManagerConfig {
|
|
9
|
+
email: string;
|
|
10
|
+
accessToken: string;
|
|
11
|
+
refreshToken: string;
|
|
12
|
+
/** How many seconds before exp to preemptively refresh. Default 60. */
|
|
13
|
+
refreshSkewSeconds?: number;
|
|
14
|
+
/**
|
|
15
|
+
* Where to persist rotated tokens. Pass `EnvFileTokenStore(path)` (default
|
|
16
|
+
* when `envPath` is given) or `MemoryTokenStore` for ephemeral hosts.
|
|
17
|
+
*/
|
|
18
|
+
store?: TokenStore;
|
|
19
|
+
/** Convenience: provide envPath instead of `store` to get the default file store. */
|
|
20
|
+
envPath?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class TokenManager {
|
|
24
|
+
private email: string;
|
|
25
|
+
private accessToken: string;
|
|
26
|
+
private refreshToken: string;
|
|
27
|
+
private expiresAt: number; // epoch ms
|
|
28
|
+
private skewMs: number;
|
|
29
|
+
private store: TokenStore;
|
|
30
|
+
private refreshing: Promise<void> | null = null;
|
|
31
|
+
|
|
32
|
+
constructor(config: TokenManagerConfig) {
|
|
33
|
+
this.email = config.email;
|
|
34
|
+
this.accessToken = config.accessToken;
|
|
35
|
+
this.refreshToken = config.refreshToken;
|
|
36
|
+
this.skewMs = (config.refreshSkewSeconds ?? 60) * 1000;
|
|
37
|
+
this.expiresAt = decodeJwtExp(config.accessToken) * 1000;
|
|
38
|
+
if (config.store) {
|
|
39
|
+
this.store = config.store;
|
|
40
|
+
} else if (config.envPath) {
|
|
41
|
+
this.store = new EnvFileTokenStore(config.envPath);
|
|
42
|
+
} else {
|
|
43
|
+
throw new Error("TokenManager: pass either `store` or `envPath`");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async getToken(): Promise<string> {
|
|
48
|
+
if (this.isFresh()) return this.accessToken;
|
|
49
|
+
// Single-flight: if a refresh is already running, wait on it
|
|
50
|
+
if (!this.refreshing) {
|
|
51
|
+
this.refreshing = this.doRefresh().finally(() => {
|
|
52
|
+
this.refreshing = null;
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
await this.refreshing;
|
|
56
|
+
return this.accessToken;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private isFresh(): boolean {
|
|
60
|
+
return Date.now() < this.expiresAt - this.skewMs;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private async doRefresh(): Promise<void> {
|
|
64
|
+
const next = await refreshCognitoSession(this.email, this.refreshToken);
|
|
65
|
+
this.accessToken = next.accessToken;
|
|
66
|
+
// Cognito may rotate the refresh token; if it does, persist the new one.
|
|
67
|
+
if (next.refreshToken && next.refreshToken !== this.refreshToken) {
|
|
68
|
+
this.refreshToken = next.refreshToken;
|
|
69
|
+
// Observable so a memory-store (non-persisting) deploy can tell when a
|
|
70
|
+
// restart would strand the old token. See SECURITY.md → token hygiene.
|
|
71
|
+
console.error("[totem] Cognito rotated the refresh token — persisting the new one.");
|
|
72
|
+
}
|
|
73
|
+
this.expiresAt = next.expiresAt;
|
|
74
|
+
this.store.save({ accessToken: this.accessToken, refreshToken: this.refreshToken });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Persistence layer for Cognito tokens. The TokenManager writes the rotated
|
|
2
|
+
// access + refresh tokens after every refresh so server restarts pick up the
|
|
3
|
+
// latest state without re-bootstrapping (until the refresh token itself
|
|
4
|
+
// expires, ~30 days).
|
|
5
|
+
//
|
|
6
|
+
// Two implementations:
|
|
7
|
+
// - EnvFileTokenStore: writes to a .env file. Used in local dev and on any
|
|
8
|
+
// host that lets you persist a small file (Fly volumes, Railway disks,
|
|
9
|
+
// a VPS). The default.
|
|
10
|
+
// - MemoryTokenStore: no persistence. Used on hosts with read-only file
|
|
11
|
+
// systems (Cloudflare Workers, read-only container disks). Accept that you'll
|
|
12
|
+
// re-bootstrap every 30 days. Opt in via WHOOP_TOKEN_STORE=memory.
|
|
13
|
+
|
|
14
|
+
import { readFileSync, writeFileSync, existsSync, chmodSync } from "node:fs";
|
|
15
|
+
|
|
16
|
+
export interface TokenStore {
|
|
17
|
+
save(updates: { accessToken: string; refreshToken: string }): void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class EnvFileTokenStore implements TokenStore {
|
|
21
|
+
constructor(private path: string) {}
|
|
22
|
+
|
|
23
|
+
save(updates: { accessToken: string; refreshToken: string }): void {
|
|
24
|
+
if (!existsSync(this.path)) return;
|
|
25
|
+
const lines = readFileSync(this.path, "utf8").split("\n");
|
|
26
|
+
const upsert = (key: string, value: string): void => {
|
|
27
|
+
const idx = lines.findIndex((l) => l.startsWith(`${key}=`));
|
|
28
|
+
const entry = `${key}=${value}`;
|
|
29
|
+
if (idx >= 0) lines[idx] = entry;
|
|
30
|
+
else lines.push(entry);
|
|
31
|
+
};
|
|
32
|
+
upsert("WHOOP_IOS_BEARER_TOKEN", updates.accessToken);
|
|
33
|
+
upsert("WHOOP_COGNITO_REFRESH_TOKEN", updates.refreshToken);
|
|
34
|
+
// 0600: this file holds the refresh token. mode only applies on create, so
|
|
35
|
+
// chmod too — repairs files written by older versions under a 0644 umask.
|
|
36
|
+
writeFileSync(this.path, lines.join("\n"), { mode: 0o600 });
|
|
37
|
+
try { chmodSync(this.path, 0o600); } catch { /* best-effort on exotic FS */ }
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class MemoryTokenStore implements TokenStore {
|
|
42
|
+
save(_updates: { accessToken: string; refreshToken: string }): void {
|
|
43
|
+
// intentionally no-op; tokens persist only for the lifetime of this process
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
// ─── Exercise info (clean /v1/exercise/{id}) ──────────────────────────────
|
|
4
|
+
export const ExerciseInfoSchema = z.object({
|
|
5
|
+
exercise_id: z.string(),
|
|
6
|
+
name: z.string(),
|
|
7
|
+
muscle_groups: z.array(z.string()),
|
|
8
|
+
translated_muscle_groups: z.string(),
|
|
9
|
+
equipment: z.string(),
|
|
10
|
+
translated_equipment: z.string(),
|
|
11
|
+
exercise_type: z.string(),
|
|
12
|
+
laterality: z.string(),
|
|
13
|
+
movement_pattern: z.string(),
|
|
14
|
+
translated_movement_pattern: z.string(),
|
|
15
|
+
instructions: z.array(z.string()),
|
|
16
|
+
image_url: z.string().nullable(),
|
|
17
|
+
video_url: z.string().nullable(),
|
|
18
|
+
volume_input_format: z.string(),
|
|
19
|
+
custom_exercise: z.boolean(),
|
|
20
|
+
deleted: z.boolean(),
|
|
21
|
+
trackable: z.boolean(),
|
|
22
|
+
});
|
|
23
|
+
export type ExerciseInfo = z.infer<typeof ExerciseInfoSchema>;
|
|
24
|
+
|
|
25
|
+
// ─── User bootstrap ───────────────────────────────────────────────────────
|
|
26
|
+
export const BootstrapSchema = z.object({
|
|
27
|
+
account: z.object({
|
|
28
|
+
id: z.number(),
|
|
29
|
+
username: z.string(),
|
|
30
|
+
email: z.string(),
|
|
31
|
+
type: z.string(),
|
|
32
|
+
user_id: z.number(),
|
|
33
|
+
}),
|
|
34
|
+
user: z.object({
|
|
35
|
+
id: z.number(),
|
|
36
|
+
first_name: z.string(),
|
|
37
|
+
last_name: z.string(),
|
|
38
|
+
country: z.string().nullable().optional(),
|
|
39
|
+
city: z.string().nullable().optional(),
|
|
40
|
+
}),
|
|
41
|
+
profile: z
|
|
42
|
+
.object({
|
|
43
|
+
user_id: z.number(),
|
|
44
|
+
height: z.number().nullable(),
|
|
45
|
+
weight: z.number().nullable(),
|
|
46
|
+
gender: z.string().nullable(),
|
|
47
|
+
unit_system: z.string(),
|
|
48
|
+
fitness_level: z.string().nullable().optional(),
|
|
49
|
+
birthday: z.string().nullable().optional(),
|
|
50
|
+
timezone_offset: z.string(),
|
|
51
|
+
})
|
|
52
|
+
.nullable()
|
|
53
|
+
.optional(),
|
|
54
|
+
bio_data: z
|
|
55
|
+
.object({
|
|
56
|
+
max_heart_rate: z.number(),
|
|
57
|
+
min_heart_rate: z.number().nullable().optional(),
|
|
58
|
+
resting_heart_rate: z.number(),
|
|
59
|
+
recovery_count: z.number().nullable().optional(),
|
|
60
|
+
})
|
|
61
|
+
.nullable()
|
|
62
|
+
.optional(),
|
|
63
|
+
membership: z.object({
|
|
64
|
+
status: z.string(),
|
|
65
|
+
in_effect: z.boolean(),
|
|
66
|
+
}),
|
|
67
|
+
});
|
|
68
|
+
export type Bootstrap = z.infer<typeof BootstrapSchema>;
|
|
69
|
+
|
|
70
|
+
// ─── Journal draft (current journal entry for a date) ─────────────────────
|
|
71
|
+
export const JournalDraftSchema = z.object({
|
|
72
|
+
integrations: z.unknown().nullable(),
|
|
73
|
+
journal: z.object({
|
|
74
|
+
tracked_behaviors: z.array(
|
|
75
|
+
z.object({
|
|
76
|
+
behavior_id: z.string(),
|
|
77
|
+
value: z.unknown(),
|
|
78
|
+
recorded_at: z.string().optional(),
|
|
79
|
+
}),
|
|
80
|
+
),
|
|
81
|
+
user_id: z.number(),
|
|
82
|
+
cycle_id: z.number(),
|
|
83
|
+
journal_entry_id: z.string().nullable(),
|
|
84
|
+
notes: z.string().nullable(),
|
|
85
|
+
user_reviewed: z.boolean().nullable(),
|
|
86
|
+
}),
|
|
87
|
+
metadata: z.unknown(),
|
|
88
|
+
});
|
|
89
|
+
export type JournalDraft = z.infer<typeof JournalDraftSchema>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Preview helper for write tools. Returns a structured "would-execute" payload
|
|
2
|
+
// when confirm:false; the tool handler executes the actual call when confirm:true.
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
export const WritePreviewSchema = z.object({
|
|
6
|
+
preview: z.literal(true),
|
|
7
|
+
will_execute: z.object({
|
|
8
|
+
method: z.string(),
|
|
9
|
+
path: z.string(),
|
|
10
|
+
body_summary: z.unknown(),
|
|
11
|
+
}),
|
|
12
|
+
set_confirm_true_to_run: z.literal(true),
|
|
13
|
+
});
|
|
14
|
+
export type WritePreview = z.infer<typeof WritePreviewSchema>;
|
|
15
|
+
|
|
16
|
+
export function preview(
|
|
17
|
+
method: string,
|
|
18
|
+
path: string,
|
|
19
|
+
bodySummary: unknown,
|
|
20
|
+
): WritePreview {
|
|
21
|
+
return {
|
|
22
|
+
preview: true,
|
|
23
|
+
will_execute: { method, path, body_summary: bodySummary },
|
|
24
|
+
set_confirm_true_to_run: true,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function withPreview<T extends z.ZodTypeAny>(receipt: T) {
|
|
29
|
+
return z.union([WritePreviewSchema, receipt]);
|
|
30
|
+
}
|