@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,37 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import type { WhoopClient } from "../../whoop/client.js";
|
|
4
|
+
import { WorkoutListOut } from "../../schemas/workouts.js";
|
|
5
|
+
import { projectWorkoutsList } from "../../projections/workouts.js";
|
|
6
|
+
import { WhoopProjectionError } from "../../whoop/errors.js";
|
|
7
|
+
import { jsonOut } from "../../whoop/json_out.js";
|
|
8
|
+
import { rangeFromDays } from "../../lib/dates.js";
|
|
9
|
+
|
|
10
|
+
export function registerWorkouts(server: McpServer, client: WhoopClient): void {
|
|
11
|
+
server.tool(
|
|
12
|
+
"whoop_workouts",
|
|
13
|
+
"Recent workouts — sport, start/end, duration, strain, avg/max HR, and calories. Optional sport-name filter, limit (≤25), and start/end date range; use whoop_workout(activity_id) for one workout's full detail (HR curve, zones).",
|
|
14
|
+
{
|
|
15
|
+
start: z.iso.datetime({ offset: true }).optional().describe("ISO timestamp lower bound. Default: 30 days ago."),
|
|
16
|
+
end: z.iso.datetime({ offset: true }).optional().describe("ISO timestamp upper bound. Default: now."),
|
|
17
|
+
sport: z.string().optional().describe("Case-insensitive substring match on sport_name."),
|
|
18
|
+
limit: z.number().int().min(1).max(25).default(10),
|
|
19
|
+
},
|
|
20
|
+
async ({ start, end, sport, limit }) => {
|
|
21
|
+
const window = start && end ? { start, end } : rangeFromDays(30);
|
|
22
|
+
const raw = await client.get("/developer/v2/activity/workout", {
|
|
23
|
+
start: start ?? window.start,
|
|
24
|
+
end: end ?? window.end,
|
|
25
|
+
limit: Math.min(limit + 10, 25),
|
|
26
|
+
});
|
|
27
|
+
const projected = projectWorkoutsList(raw, sport, limit);
|
|
28
|
+
try {
|
|
29
|
+
const out = WorkoutListOut.parse(projected);
|
|
30
|
+
return { content: [{ type: "text", text: jsonOut(out) }] };
|
|
31
|
+
} catch (e) {
|
|
32
|
+
if (e instanceof z.ZodError) throw new WhoopProjectionError("whoop_workouts", e);
|
|
33
|
+
throw e;
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
);
|
|
37
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// Build the workout_groups[].workout_exercises[].sets[] body for lift_log + template_save.
|
|
2
|
+
// Denormalizes EXERCISES_BY_ID into each workout_exercises[].exercise_details.
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { EXERCISES_BY_ID } from "../data/exercises.js";
|
|
5
|
+
|
|
6
|
+
export interface InputSet {
|
|
7
|
+
reps: number;
|
|
8
|
+
weight?: number | undefined;
|
|
9
|
+
time_seconds?: number | undefined;
|
|
10
|
+
strap_location?: "LEFT" | "RIGHT" | "BOTH" | undefined;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface InputExercise {
|
|
14
|
+
exercise_id: string;
|
|
15
|
+
sets: InputSet[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface BuildResult {
|
|
19
|
+
workout_groups: unknown[];
|
|
20
|
+
set_count: number;
|
|
21
|
+
unknown_exercises: string[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function buildExerciseGroups(exercises: InputExercise[], startMs: number): BuildResult {
|
|
25
|
+
const groups: unknown[] = [];
|
|
26
|
+
const unknown: string[] = [];
|
|
27
|
+
let cursor = startMs;
|
|
28
|
+
let setCount = 0;
|
|
29
|
+
for (const ex of exercises) {
|
|
30
|
+
const meta = EXERCISES_BY_ID.get(ex.exercise_id);
|
|
31
|
+
if (!meta) {
|
|
32
|
+
unknown.push(ex.exercise_id);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const sets = ex.sets.map((s) => {
|
|
36
|
+
const setStart = new Date(cursor).toISOString();
|
|
37
|
+
const setEnd = new Date(cursor + 100).toISOString();
|
|
38
|
+
cursor += 100;
|
|
39
|
+
setCount++;
|
|
40
|
+
const baseSet: Record<string, unknown> = {
|
|
41
|
+
during: `['${setStart}','${setEnd}')`,
|
|
42
|
+
msk_total_volume_kg: 0,
|
|
43
|
+
weight: s.weight ?? 0,
|
|
44
|
+
number_of_reps: s.reps,
|
|
45
|
+
strap_location: "1",
|
|
46
|
+
strap_location_laterality: s.strap_location ?? "LEFT",
|
|
47
|
+
weightlifting_workout_set_id: randomUUID().toUpperCase(),
|
|
48
|
+
};
|
|
49
|
+
if (s.time_seconds !== undefined) baseSet.time_in_seconds = s.time_seconds;
|
|
50
|
+
return baseSet;
|
|
51
|
+
});
|
|
52
|
+
groups.push({
|
|
53
|
+
workout_exercises: [
|
|
54
|
+
{
|
|
55
|
+
sets,
|
|
56
|
+
exercise_details: {
|
|
57
|
+
push_core_name: meta.exercise_id,
|
|
58
|
+
name: meta.name,
|
|
59
|
+
muscle_groups: meta.muscle_groups,
|
|
60
|
+
trackable: true,
|
|
61
|
+
// Whoop's POST validates these as non-empty ISO timestamps.
|
|
62
|
+
// The values don't drive any logic on the server side — they reflect
|
|
63
|
+
// when the exercise was added to Whoop's catalog.
|
|
64
|
+
updated_at: "2025-01-01T00:00:00.000Z",
|
|
65
|
+
created_at: "2022-01-01T00:00:00.000Z",
|
|
66
|
+
training_types: [],
|
|
67
|
+
translated_equipment: meta.equipment,
|
|
68
|
+
translated_muscle_groups: meta.primary_muscle,
|
|
69
|
+
translated_movement_pattern: meta.movement_pattern,
|
|
70
|
+
equipment: meta.raw_equipment,
|
|
71
|
+
exercise_id: meta.exercise_id,
|
|
72
|
+
movement_pattern: meta.raw_movement_pattern,
|
|
73
|
+
laterality: meta.laterality,
|
|
74
|
+
deleted: false,
|
|
75
|
+
volume_input_format: "REPS",
|
|
76
|
+
exercise_type: "STRENGTH",
|
|
77
|
+
instructions: [],
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
],
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
return { workout_groups: groups, set_count: setCount, unknown_exercises: unknown };
|
|
84
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { BASE_URL, API_VERSION, REQUEST_TIMEOUT_MS } from "./constants.js";
|
|
2
|
+
import { deviceHeaders } from "./device.js";
|
|
3
|
+
import {
|
|
4
|
+
WhoopApiError,
|
|
5
|
+
WhoopAuthExpiredError,
|
|
6
|
+
WhoopServerError,
|
|
7
|
+
} from "./errors.js";
|
|
8
|
+
|
|
9
|
+
export interface WhoopClientConfig {
|
|
10
|
+
/** Async function returning a fresh bearer token. Called before each request. */
|
|
11
|
+
getToken: () => Promise<string>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type QueryValue = string | number | boolean | undefined | null;
|
|
15
|
+
|
|
16
|
+
export class WhoopClient {
|
|
17
|
+
constructor(private readonly config: WhoopClientConfig) {}
|
|
18
|
+
|
|
19
|
+
async get<T = unknown>(
|
|
20
|
+
path: string,
|
|
21
|
+
query: Record<string, QueryValue> = {},
|
|
22
|
+
): Promise<T> {
|
|
23
|
+
return this.request<T>("GET", path, query, undefined);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async post<T = unknown>(
|
|
27
|
+
path: string,
|
|
28
|
+
body: unknown,
|
|
29
|
+
query: Record<string, QueryValue> = {},
|
|
30
|
+
): Promise<T> {
|
|
31
|
+
return this.request<T>("POST", path, query, body);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async put<T = unknown>(
|
|
35
|
+
path: string,
|
|
36
|
+
body: unknown,
|
|
37
|
+
query: Record<string, QueryValue> = {},
|
|
38
|
+
): Promise<T> {
|
|
39
|
+
return this.request<T>("PUT", path, query, body);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async delete<T = unknown>(
|
|
43
|
+
path: string,
|
|
44
|
+
query: Record<string, QueryValue> = {},
|
|
45
|
+
): Promise<T> {
|
|
46
|
+
return this.request<T>("DELETE", path, query, undefined);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
private async request<T>(
|
|
50
|
+
method: string,
|
|
51
|
+
path: string,
|
|
52
|
+
query: Record<string, QueryValue>,
|
|
53
|
+
body: unknown,
|
|
54
|
+
): Promise<T> {
|
|
55
|
+
const url = new URL(BASE_URL + path);
|
|
56
|
+
url.searchParams.set("apiVersion", API_VERSION);
|
|
57
|
+
for (const [k, v] of Object.entries(query)) {
|
|
58
|
+
if (v === undefined || v === null) continue;
|
|
59
|
+
url.searchParams.set(k, String(v));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const token = await this.config.getToken();
|
|
63
|
+
// Start from the iOS app's identity headers (user-agent, x-whoop-*, locale,
|
|
64
|
+
// accept, priority — see device.ts), then layer auth and, for writes, the
|
|
65
|
+
// body content-type on top so they always win. `accept-encoding` is left
|
|
66
|
+
// unset on purpose: setting it manually disables undici's automatic response
|
|
67
|
+
// decompression, which would break response.json().
|
|
68
|
+
const headers: Record<string, string> = {
|
|
69
|
+
...deviceHeaders(),
|
|
70
|
+
authorization: `Bearer ${token}`,
|
|
71
|
+
};
|
|
72
|
+
let bodyString: string | undefined;
|
|
73
|
+
if (body !== undefined) {
|
|
74
|
+
headers["content-type"] = "application/json";
|
|
75
|
+
bodyString = JSON.stringify(body);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const controller = new AbortController();
|
|
79
|
+
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
80
|
+
|
|
81
|
+
const init: RequestInit = {
|
|
82
|
+
method,
|
|
83
|
+
headers,
|
|
84
|
+
signal: controller.signal,
|
|
85
|
+
};
|
|
86
|
+
if (bodyString !== undefined) init.body = bodyString;
|
|
87
|
+
|
|
88
|
+
let response: Response;
|
|
89
|
+
try {
|
|
90
|
+
response = await fetch(url.toString(), init);
|
|
91
|
+
} finally {
|
|
92
|
+
clearTimeout(timeout);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (response.status === 401) {
|
|
96
|
+
throw new WhoopAuthExpiredError();
|
|
97
|
+
}
|
|
98
|
+
if (response.status >= 500) {
|
|
99
|
+
throw new WhoopServerError(response.status, path);
|
|
100
|
+
}
|
|
101
|
+
if (!response.ok) {
|
|
102
|
+
const text = await response.text().catch(() => "");
|
|
103
|
+
let description: string | undefined;
|
|
104
|
+
try {
|
|
105
|
+
const parsed = JSON.parse(text) as { error_description?: string; error?: string };
|
|
106
|
+
description = parsed.error_description ?? parsed.error;
|
|
107
|
+
} catch {
|
|
108
|
+
// body not JSON
|
|
109
|
+
}
|
|
110
|
+
throw new WhoopApiError(response.status, path, text, description);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (response.status === 204) {
|
|
114
|
+
return undefined as T;
|
|
115
|
+
}
|
|
116
|
+
return (await response.json()) as T;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// Auth via Whoop's own Cognito proxy at /auth-service/v3/whoop/.
|
|
2
|
+
// Whoop's backend fills in the ClientId + SECRET_HASH and forwards to AWS Cognito,
|
|
3
|
+
// so we don't need the iOS app's client secret. We just impersonate the iOS
|
|
4
|
+
// AWS Swift SDK headers to pass through Cloudflare.
|
|
5
|
+
//
|
|
6
|
+
// Flow:
|
|
7
|
+
// 1. InitiateAuth with USER_PASSWORD_AUTH (ClientId="")
|
|
8
|
+
// 2. If SMS_MFA challenge → RespondToAuthChallenge with the SMS code
|
|
9
|
+
// 3. Get AccessToken + RefreshToken from AuthenticationResult
|
|
10
|
+
// 4. To refresh: InitiateAuth with REFRESH_TOKEN_AUTH (no MFA needed)
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
12
|
+
|
|
13
|
+
const ENDPOINT = "https://api.prod.whoop.com/auth-service/v3/whoop/";
|
|
14
|
+
const USER_AGENT =
|
|
15
|
+
"aws-sdk-swift/1.5.86 ua/2.1 api/cognito_identity_provider#1.5.86 os/ios#26.3.1 lang/swift#5.10 m/D,N,Z,b";
|
|
16
|
+
|
|
17
|
+
interface AuthenticationResult {
|
|
18
|
+
AccessToken: string;
|
|
19
|
+
RefreshToken?: string; // omitted on refresh-token flow
|
|
20
|
+
IdToken: string;
|
|
21
|
+
ExpiresIn: number;
|
|
22
|
+
TokenType: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface CognitoResponse {
|
|
26
|
+
AuthenticationResult?: AuthenticationResult;
|
|
27
|
+
ChallengeName?: string;
|
|
28
|
+
Session?: string;
|
|
29
|
+
ChallengeParameters?: Record<string, string>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface CognitoTokens {
|
|
33
|
+
accessToken: string;
|
|
34
|
+
refreshToken: string;
|
|
35
|
+
idToken: string;
|
|
36
|
+
expiresAt: number; // epoch ms
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function decodeJwtExp(jwt: string): number {
|
|
40
|
+
const parts = jwt.split(".");
|
|
41
|
+
if (parts.length < 2) return 0;
|
|
42
|
+
const padded = parts[1]!.padEnd(parts[1]!.length + ((4 - (parts[1]!.length % 4)) % 4), "=");
|
|
43
|
+
const json = Buffer.from(padded, "base64").toString("utf8");
|
|
44
|
+
try {
|
|
45
|
+
const payload = JSON.parse(json) as { exp?: number };
|
|
46
|
+
return payload.exp ?? 0;
|
|
47
|
+
} catch {
|
|
48
|
+
return 0;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function callCognito(
|
|
53
|
+
target: "InitiateAuth" | "RespondToAuthChallenge",
|
|
54
|
+
body: object,
|
|
55
|
+
): Promise<CognitoResponse> {
|
|
56
|
+
const response = await fetch(ENDPOINT, {
|
|
57
|
+
method: "POST",
|
|
58
|
+
headers: {
|
|
59
|
+
"content-type": "application/x-amz-json-1.1",
|
|
60
|
+
"x-amz-target": `AWSCognitoIdentityProviderService.${target}`,
|
|
61
|
+
"amz-sdk-request": "attempt=1; max=1",
|
|
62
|
+
"amz-sdk-invocation-id": randomUUID(),
|
|
63
|
+
"user-agent": USER_AGENT,
|
|
64
|
+
accept: "*/*",
|
|
65
|
+
"accept-encoding": "gzip, deflate, br",
|
|
66
|
+
"accept-language": "en-US,en;q=0.9",
|
|
67
|
+
},
|
|
68
|
+
body: JSON.stringify(body),
|
|
69
|
+
});
|
|
70
|
+
const text = await response.text();
|
|
71
|
+
if (!response.ok) {
|
|
72
|
+
let detail = text.slice(0, 200);
|
|
73
|
+
try {
|
|
74
|
+
const j = JSON.parse(text) as { message?: string; __type?: string };
|
|
75
|
+
detail = `${j.__type ?? "error"}: ${j.message ?? text}`;
|
|
76
|
+
} catch {
|
|
77
|
+
// not JSON
|
|
78
|
+
}
|
|
79
|
+
throw new Error(`Cognito ${target} failed (${response.status}): ${detail}`);
|
|
80
|
+
}
|
|
81
|
+
return JSON.parse(text) as CognitoResponse;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function tokensFromAuth(ar: AuthenticationResult, fallbackRefresh?: string): CognitoTokens {
|
|
85
|
+
return {
|
|
86
|
+
accessToken: ar.AccessToken,
|
|
87
|
+
refreshToken: ar.RefreshToken ?? fallbackRefresh ?? "",
|
|
88
|
+
idToken: ar.IdToken,
|
|
89
|
+
expiresAt: decodeJwtExp(ar.AccessToken) * 1000,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface BootstrapInput {
|
|
94
|
+
email: string;
|
|
95
|
+
password: string;
|
|
96
|
+
/** Called when SMS_MFA challenge fires. Return the 6-digit code. */
|
|
97
|
+
mfaPrompt: () => Promise<string>;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function bootstrapCognito(input: BootstrapInput): Promise<CognitoTokens> {
|
|
101
|
+
const init = await callCognito("InitiateAuth", {
|
|
102
|
+
AuthFlow: "USER_PASSWORD_AUTH",
|
|
103
|
+
AuthParameters: { USERNAME: input.email, PASSWORD: input.password },
|
|
104
|
+
ClientId: "",
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
if (init.AuthenticationResult) {
|
|
108
|
+
return tokensFromAuth(init.AuthenticationResult);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (init.ChallengeName === "SMS_MFA" || init.ChallengeName === "SOFTWARE_TOKEN_MFA" || init.ChallengeName === "EMAIL_OTP") {
|
|
112
|
+
if (!init.Session) throw new Error("Cognito MFA challenge missing Session token");
|
|
113
|
+
const code = (await input.mfaPrompt()).trim();
|
|
114
|
+
const resp = await callCognito("RespondToAuthChallenge", {
|
|
115
|
+
ClientId: "",
|
|
116
|
+
ChallengeName: init.ChallengeName,
|
|
117
|
+
Session: init.Session,
|
|
118
|
+
ChallengeResponses: {
|
|
119
|
+
USERNAME: input.email,
|
|
120
|
+
[init.ChallengeName === "SMS_MFA" ? "SMS_MFA_CODE" : init.ChallengeName === "SOFTWARE_TOKEN_MFA" ? "SOFTWARE_TOKEN_MFA_CODE" : "EMAIL_OTP_CODE"]: code,
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
if (!resp.AuthenticationResult) {
|
|
124
|
+
throw new Error(`MFA verification did not return tokens: ${JSON.stringify(resp)}`);
|
|
125
|
+
}
|
|
126
|
+
return tokensFromAuth(resp.AuthenticationResult);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
throw new Error(`Unexpected challenge from Cognito: ${init.ChallengeName ?? "<none>"}`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Use the long-lived refresh token to mint a fresh access token.
|
|
134
|
+
* No MFA needed — refresh tokens are pre-authenticated.
|
|
135
|
+
* Returns new access token; refresh token usually NOT rotated (reuse the existing one).
|
|
136
|
+
*/
|
|
137
|
+
export async function refreshCognitoSession(
|
|
138
|
+
_email: string,
|
|
139
|
+
refreshToken: string,
|
|
140
|
+
): Promise<CognitoTokens> {
|
|
141
|
+
const resp = await callCognito("InitiateAuth", {
|
|
142
|
+
AuthFlow: "REFRESH_TOKEN_AUTH",
|
|
143
|
+
AuthParameters: { REFRESH_TOKEN: refreshToken },
|
|
144
|
+
ClientId: "",
|
|
145
|
+
});
|
|
146
|
+
if (!resp.AuthenticationResult) {
|
|
147
|
+
throw new Error(`Refresh did not return tokens: ${JSON.stringify(resp)}`);
|
|
148
|
+
}
|
|
149
|
+
return tokensFromAuth(resp.AuthenticationResult, refreshToken);
|
|
150
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Device-identity headers that make our data requests indistinguishable from
|
|
2
|
+
// the WHOOP iOS app's own traffic.
|
|
3
|
+
//
|
|
4
|
+
// Why this exists: the data endpoints on api.prod.whoop.com authenticate on the
|
|
5
|
+
// bearer token alone, so a bare request *works* — but it doesn't look like the
|
|
6
|
+
// app. The real app stamps every data request with a fixed set of `x-whoop-*`
|
|
7
|
+
// identity headers plus `user-agent: iOS`. Sending the same set puts our
|
|
8
|
+
// requests inside the legitimate-app traffic distribution instead of leaving us
|
|
9
|
+
// as the one client that omits them (a missing header is itself a tell).
|
|
10
|
+
//
|
|
11
|
+
// Design rule — so a WHOOP engineer reading this open-source file CANNOT write a
|
|
12
|
+
// one-line rule that catches us specifically:
|
|
13
|
+
// - The static values below are the app's OWN constants, shared by every real
|
|
14
|
+
// install on this version. They're camouflage, not a signature.
|
|
15
|
+
// - Per-install values (the installation identifier) are randomized per
|
|
16
|
+
// install, exactly like the app, so there is no shared constant to grep.
|
|
17
|
+
// - Environment values (time zone) are derived from the host, like a phone.
|
|
18
|
+
// - We add NOTHING the app doesn't send: no fabricated Sentry baggage/trace,
|
|
19
|
+
// no marketing cookies. A unique invented header would be the precise
|
|
20
|
+
// fingerprint we are trying not to leave.
|
|
21
|
+
//
|
|
22
|
+
// Captured from WHOOP iOS 5.52.0 (build 595097). Bump these when the app ships a
|
|
23
|
+
// new version so we keep blending with the current install base.
|
|
24
|
+
|
|
25
|
+
import { randomUUID } from "node:crypto";
|
|
26
|
+
|
|
27
|
+
export const IOS_APP_VERSION = "5.52.0";
|
|
28
|
+
export const IOS_BUILD_NUMBER = "595097";
|
|
29
|
+
export const IOS_BUNDLE_NAME = "com.whoop.iphone";
|
|
30
|
+
|
|
31
|
+
// When the constants above were captured from a real device. If the bundled
|
|
32
|
+
// version drifts too far behind the live install base it stops being camouflage
|
|
33
|
+
// and becomes a "this one frozen old version" cohort — warn at boot so it gets
|
|
34
|
+
// refreshed. Bump alongside the version/build when you re-capture.
|
|
35
|
+
export const IOS_VERSION_CAPTURED_AT = "2026-05"; // YYYY-MM
|
|
36
|
+
export function versionStaleWarning(maxAgeMonths = 6): string | null {
|
|
37
|
+
const [y, m] = IOS_VERSION_CAPTURED_AT.split("-").map(Number);
|
|
38
|
+
if (!y || !m) return null;
|
|
39
|
+
const ageMonths = (Date.now() - new Date(y, m - 1, 1).getTime()) / (30 * 86_400_000);
|
|
40
|
+
if (ageMonths < maxAgeMonths) return null;
|
|
41
|
+
return `[totem] bundled WHOOP iOS version (${IOS_APP_VERSION}, captured ${IOS_VERSION_CAPTURED_AT}) is ~${Math.round(ageMonths)} months old — update src/whoop/device.ts to keep blending with the current app install base.`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// The app sends an uppercase UUID; randomUUID() is lowercase, so we upcase it.
|
|
45
|
+
function newInstallationId(): string {
|
|
46
|
+
return randomUUID().toUpperCase();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
let cachedInstallationId: string | null = null;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The per-install identifier sent as `x-whoop-installation-identifier`.
|
|
53
|
+
*
|
|
54
|
+
* Resolution: `WHOOP_INSTALLATION_ID` env (persisted at boot by
|
|
55
|
+
* resolveInstallationId) → a random per-process UUID fallback. A real install
|
|
56
|
+
* keeps one stable ID for its lifetime; persisting the env value gives us the
|
|
57
|
+
* same stability across restarts, while the per-process fallback keeps tests and
|
|
58
|
+
* one-off scripts working with no setup. The value is randomized per install,
|
|
59
|
+
* so no two totem users share one — there is no constant to fingerprint.
|
|
60
|
+
*/
|
|
61
|
+
export function getInstallationId(): string {
|
|
62
|
+
if (cachedInstallationId) return cachedInstallationId;
|
|
63
|
+
cachedInstallationId = process.env.WHOOP_INSTALLATION_ID ?? newInstallationId();
|
|
64
|
+
return cachedInstallationId;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// IANA zone for the `x-whoop-time-zone` header. The app sends the phone's IANA
|
|
68
|
+
// name (e.g. "America/Los_Angeles"). We send the host's resolved zone. If
|
|
69
|
+
// WHOOP_TIMEZONE is set to an IANA name we honor it, but a fixed-offset value
|
|
70
|
+
// (which the Whoop-profile timezone tier can produce) is not a valid IANA name,
|
|
71
|
+
// so we fall back to the system zone in that case.
|
|
72
|
+
function deviceTimeZone(): string {
|
|
73
|
+
const env = process.env.WHOOP_TIMEZONE;
|
|
74
|
+
if (env && env.includes("/")) return env;
|
|
75
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone || "America/Los_Angeles";
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The identity header set the WHOOP iOS app stamps on every data request, minus
|
|
80
|
+
* the per-request telemetry (Sentry baggage/trace) and marketing cookies that
|
|
81
|
+
* carry no auth weight and would only add a fabricated, greppable signature.
|
|
82
|
+
* Merged into every request by WhoopClient; `authorization` and (for bodies)
|
|
83
|
+
* `content-type` are layered on top by the client itself.
|
|
84
|
+
*/
|
|
85
|
+
export function deviceHeaders(): Record<string, string> {
|
|
86
|
+
return {
|
|
87
|
+
"user-agent": "iOS",
|
|
88
|
+
"x-whoop-device-platform": "iOS",
|
|
89
|
+
"x-whoop-ios-version": IOS_APP_VERSION,
|
|
90
|
+
"x-whoop-ios-build-number": IOS_BUILD_NUMBER,
|
|
91
|
+
"x-whoop-bundle-name": IOS_BUNDLE_NAME,
|
|
92
|
+
"x-whoop-installation-identifier": getInstallationId(),
|
|
93
|
+
"x-whoop-time-zone": deviceTimeZone(),
|
|
94
|
+
// The app's clock-format preference. Our own captures show the sleep
|
|
95
|
+
// deep-dive already returns 12-hour clock labels by default; sending this
|
|
96
|
+
// explicitly makes that deterministic — the sleep projection's
|
|
97
|
+
// parseClockMinutes expects AM/PM — instead of leaning on an unstated
|
|
98
|
+
// server default.
|
|
99
|
+
"x-whoop-clock-format": "TWELVE_HOUR",
|
|
100
|
+
currency: "USD",
|
|
101
|
+
locale: "en_US",
|
|
102
|
+
"accept-language": "en",
|
|
103
|
+
accept: "*/*",
|
|
104
|
+
priority: "u=3",
|
|
105
|
+
};
|
|
106
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { z } from "zod";
|
|
2
|
+
|
|
3
|
+
export class WhoopAuthExpiredError extends Error {
|
|
4
|
+
constructor() {
|
|
5
|
+
super(
|
|
6
|
+
"Whoop bearer token expired. Run `totem auth` to capture a fresh one.",
|
|
7
|
+
);
|
|
8
|
+
this.name = "WhoopAuthExpiredError";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class WhoopApiError extends Error {
|
|
13
|
+
constructor(
|
|
14
|
+
public readonly status: number,
|
|
15
|
+
public readonly path: string,
|
|
16
|
+
public readonly body: string,
|
|
17
|
+
description?: string,
|
|
18
|
+
) {
|
|
19
|
+
// Keep the raw body on `.body` for debugging, but keep it OUT of the
|
|
20
|
+
// human/AI-facing message: a 4xx body can carry a fragment of health data,
|
|
21
|
+
// and this message surfaces to the model and stderr.
|
|
22
|
+
super(`Whoop API error ${status} on ${path}${description ? `: ${description}` : ""}`);
|
|
23
|
+
this.name = "WhoopApiError";
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class WhoopServerError extends Error {
|
|
28
|
+
constructor(public readonly status: number, public readonly path: string) {
|
|
29
|
+
super(
|
|
30
|
+
`Whoop API returned ${status} on ${path}. This is usually transient — try again in 30s.`,
|
|
31
|
+
);
|
|
32
|
+
this.name = "WhoopServerError";
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class WhoopProjectionError extends Error {
|
|
37
|
+
constructor(public readonly tool: string, public readonly issue: z.ZodError) {
|
|
38
|
+
super(`Projection for ${tool} failed zod parse: ${issue.message.slice(0, 200)}`);
|
|
39
|
+
this.name = "WhoopProjectionError";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Auto-detect the user's timezone from their Whoop profile on server boot,
|
|
2
|
+
// then cache it for use by jsonOut's timestamp localization. Tier 2 of the
|
|
3
|
+
// timezone resolution chain (see src/lib/timezone.ts):
|
|
4
|
+
// 1. WHOOP_TIMEZONE env var (explicit override)
|
|
5
|
+
// 2. THIS — Whoop profile timezone_offset (zero-config auto-detect)
|
|
6
|
+
// 3. System TZ (fallback if both above miss)
|
|
7
|
+
//
|
|
8
|
+
// Fire-and-forget. We don't want server startup to block on an API call —
|
|
9
|
+
// if the fetch fails, getTimezone() falls through to system TZ and tools
|
|
10
|
+
// still work, just possibly returning UTC timestamps until the next try.
|
|
11
|
+
//
|
|
12
|
+
// Refreshed every REFRESH_INTERVAL_MS (default: 1 hour) so a traveler whose
|
|
13
|
+
// phone updates their Whoop TZ mid-trip gets the new offset within an hour
|
|
14
|
+
// without restarting the server.
|
|
15
|
+
|
|
16
|
+
import type { WhoopClient } from "./client.js";
|
|
17
|
+
import { setProfileTimezone } from "../lib/timezone.js";
|
|
18
|
+
|
|
19
|
+
const REFRESH_INTERVAL_MS = 60 * 60 * 1000;
|
|
20
|
+
|
|
21
|
+
async function fetchProfileTimezone(client: WhoopClient): Promise<string | null> {
|
|
22
|
+
try {
|
|
23
|
+
const bootstrap = await client.get("/users-service/v2/bootstrap");
|
|
24
|
+
if (!bootstrap || typeof bootstrap !== "object") return null;
|
|
25
|
+
const profile = (bootstrap as Record<string, unknown>).profile;
|
|
26
|
+
if (!profile || typeof profile !== "object") return null;
|
|
27
|
+
const offset = (profile as Record<string, unknown>).timezone_offset;
|
|
28
|
+
return typeof offset === "string" && offset.length > 0 ? offset : null;
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
let refreshTimer: ReturnType<typeof setInterval> | null = null;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Start the background profile-TZ auto-detect loop. Safe to call multiple
|
|
38
|
+
* times — subsequent calls clear the previous timer first. The initial fetch
|
|
39
|
+
* fires immediately (not awaited) and the loop refreshes every hour.
|
|
40
|
+
*
|
|
41
|
+
* Skipped entirely if WHOOP_TIMEZONE is set — env var wins and we don't need
|
|
42
|
+
* to spend API calls keeping the cache warm.
|
|
43
|
+
*/
|
|
44
|
+
export function startTimezoneAutoDetect(client: WhoopClient): void {
|
|
45
|
+
if (process.env.WHOOP_TIMEZONE) return;
|
|
46
|
+
|
|
47
|
+
if (refreshTimer) clearInterval(refreshTimer);
|
|
48
|
+
|
|
49
|
+
const refresh = async (): Promise<void> => {
|
|
50
|
+
const tz = await fetchProfileTimezone(client);
|
|
51
|
+
if (tz) setProfileTimezone(tz);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
void refresh();
|
|
55
|
+
refreshTimer = setInterval(() => void refresh(), REFRESH_INTERVAL_MS);
|
|
56
|
+
if (typeof refreshTimer.unref === "function") refreshTimer.unref();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function stopTimezoneAutoDetect(): void {
|
|
60
|
+
if (refreshTimer) {
|
|
61
|
+
clearInterval(refreshTimer);
|
|
62
|
+
refreshTimer = null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Persist a stable per-install identifier so `x-whoop-installation-identifier`
|
|
2
|
+
// stays constant across restarts — a real app install keeps one ID for its
|
|
3
|
+
// whole lifetime, and a value that changed every boot would itself be an
|
|
4
|
+
// anomaly. Mirrors how the token store writes back to the .env file.
|
|
5
|
+
//
|
|
6
|
+
// Best-effort: on read-only filesystems (Cloudflare Workers, locked containers)
|
|
7
|
+
// the write is skipped and device.ts falls back to a per-process random ID,
|
|
8
|
+
// which is stable for that process's lifetime.
|
|
9
|
+
|
|
10
|
+
import { readFileSync, writeFileSync, existsSync, chmodSync } from "node:fs";
|
|
11
|
+
import { randomUUID, createHash } from "node:crypto";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Ensure `WHOOP_INSTALLATION_ID` exists in the environment, generating and
|
|
15
|
+
* persisting one to the env file on first run. Sets `process.env` so device.ts
|
|
16
|
+
* picks it up on its first header build. Idempotent; call once at boot before
|
|
17
|
+
* any request goes out.
|
|
18
|
+
*/
|
|
19
|
+
// Derive a STABLE id from the account email — used only when we can't persist a
|
|
20
|
+
// random one (read-only host). An id that changes on every cold start is itself
|
|
21
|
+
// the anomaly we're avoiding, so a deterministic-per-account value beats a fresh
|
|
22
|
+
// random one per process. Shaped like the app's uppercase UUID (8-4-4-4-12).
|
|
23
|
+
function deterministicId(email: string | undefined): string | null {
|
|
24
|
+
if (!email) return null;
|
|
25
|
+
const h = createHash("sha256").update(`totem/install/${email.toLowerCase()}`).digest("hex");
|
|
26
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`.toUpperCase();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function resolveInstallationId(envPath: string): string {
|
|
30
|
+
const existing = process.env.WHOOP_INSTALLATION_ID;
|
|
31
|
+
if (existing) return existing;
|
|
32
|
+
|
|
33
|
+
// The app sends an uppercase UUID; match its shape.
|
|
34
|
+
let id = randomUUID().toUpperCase();
|
|
35
|
+
let persisted = false;
|
|
36
|
+
try {
|
|
37
|
+
if (existsSync(envPath)) {
|
|
38
|
+
const lines = readFileSync(envPath, "utf8").split("\n");
|
|
39
|
+
if (!lines.some((l) => l.startsWith("WHOOP_INSTALLATION_ID="))) {
|
|
40
|
+
lines.push(`WHOOP_INSTALLATION_ID=${id}`);
|
|
41
|
+
writeFileSync(envPath, lines.join("\n"), { mode: 0o600 });
|
|
42
|
+
try { chmodSync(envPath, 0o600); } catch { /* best-effort */ }
|
|
43
|
+
}
|
|
44
|
+
persisted = true;
|
|
45
|
+
}
|
|
46
|
+
} catch {
|
|
47
|
+
persisted = false;
|
|
48
|
+
}
|
|
49
|
+
// Couldn't persist (read-only host / no .env): use a deterministic,
|
|
50
|
+
// restart-stable id from the account email rather than a fresh random one
|
|
51
|
+
// every boot. Serverless deployers should still set WHOOP_INSTALLATION_ID.
|
|
52
|
+
if (!persisted) {
|
|
53
|
+
const stable = deterministicId(process.env.WHOOP_EMAIL);
|
|
54
|
+
if (stable) id = stable;
|
|
55
|
+
}
|
|
56
|
+
process.env.WHOOP_INSTALLATION_ID = id;
|
|
57
|
+
return id;
|
|
58
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { localizeTimestamps } from "../lib/timezone.js";
|
|
2
|
+
|
|
3
|
+
// Compact JSON for MCP tool responses. v2 tools produce already-projected
|
|
4
|
+
// data, so no stripping is needed — just rewrite UTC timestamps as local ISO
|
|
5
|
+
// (with explicit offset, e.g. "2026-05-25T15:30:00-07:00") and stringify.
|
|
6
|
+
// Driven by the WHOOP_TIMEZONE env var; falls back to the server's system TZ.
|
|
7
|
+
export function jsonOut(data: unknown): string {
|
|
8
|
+
return JSON.stringify(localizeTimestamps(data));
|
|
9
|
+
}
|