@thebriangao/totem 1.4.4 → 2.0.0
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/.dev.vars.example +5 -0
- package/.dockerignore +5 -0
- package/.env.example +29 -20
- package/CHANGELOG.md +99 -1
- package/CONTRIBUTING.md +48 -116
- package/Dockerfile +46 -12
- package/README.md +172 -498
- package/SECURITY.md +36 -59
- package/TOOLS.md +448 -311
- package/WHOOP.md +497 -2659
- package/assets/brand/SOURCES.md +38 -0
- package/assets/brand/totem.png +0 -0
- package/assets/brand/totem.svg +13 -0
- package/assets/fonts/Manrope-OFL.txt +93 -0
- package/assets/fonts/manrope-latin.woff2 +0 -0
- package/dist/build_info.js +5 -0
- package/dist/build_info.js.map +1 -0
- package/dist/cli/app.js +675 -0
- package/dist/cli/app.js.map +1 -0
- package/dist/cli/auth.js +297 -0
- package/dist/cli/auth.js.map +1 -0
- package/dist/cli/auth_flow.js +268 -0
- package/dist/cli/auth_flow.js.map +1 -0
- package/dist/cli/browser_login.js +368 -0
- package/dist/cli/browser_login.js.map +1 -0
- package/dist/cli/clients.js +403 -0
- package/dist/cli/clients.js.map +1 -0
- package/dist/cli/deploy_record.js +96 -0
- package/dist/cli/deploy_record.js.map +1 -0
- package/dist/cli/index.js +39 -575
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/links.js +28 -0
- package/dist/cli/links.js.map +1 -0
- package/dist/cli/logo.js +63 -0
- package/dist/cli/logo.js.map +1 -0
- package/dist/cli/setup.js +1157 -1017
- package/dist/cli/setup.js.map +1 -1
- package/dist/cli/spawn.js +80 -0
- package/dist/cli/spawn.js.map +1 -0
- package/dist/cli/sys.js +219 -0
- package/dist/cli/sys.js.map +1 -0
- package/dist/cli/ui.js +712 -463
- package/dist/cli/ui.js.map +1 -1
- package/dist/cli/update.js +425 -282
- package/dist/cli/update.js.map +1 -1
- package/dist/cloudflare/token_store.js +48 -0
- package/dist/cloudflare/token_store.js.map +1 -0
- package/dist/cloudflare/worker.js +155 -0
- package/dist/cloudflare/worker.js.map +1 -0
- package/dist/data/behaviors.js +2733 -617
- package/dist/data/behaviors.js.map +1 -1
- package/dist/data/endpoint_catalog.js +2681 -0
- package/dist/data/endpoint_catalog.js.map +1 -0
- package/dist/data/exercises.js +373 -4859
- package/dist/data/exercises.js.map +1 -1
- package/dist/data/garments.js +19 -0
- package/dist/data/garments.js.map +1 -0
- package/dist/data/sports.js +219 -208
- package/dist/data/sports.js.map +1 -1
- package/dist/lib/activity_list.js +123 -0
- package/dist/lib/activity_list.js.map +1 -0
- package/dist/lib/activity_records.js +195 -0
- package/dist/lib/activity_records.js.map +1 -0
- package/dist/lib/activity_results.js +44 -0
- package/dist/lib/activity_results.js.map +1 -0
- package/dist/lib/activity_types.js +164 -0
- package/dist/lib/activity_types.js.map +1 -0
- package/dist/lib/brand.js +63 -0
- package/dist/lib/brand.js.map +1 -0
- package/dist/lib/clock.js +24 -0
- package/dist/lib/clock.js.map +1 -0
- package/dist/lib/coach_session.js +345 -0
- package/dist/lib/coach_session.js.map +1 -0
- package/dist/lib/concurrency.js.map +1 -1
- package/dist/lib/dates.js +19 -0
- package/dist/lib/dates.js.map +1 -1
- package/dist/lib/env_file.js +195 -0
- package/dist/lib/env_file.js.map +1 -0
- package/dist/lib/health_plans_write.js +44 -0
- package/dist/lib/health_plans_write.js.map +1 -0
- package/dist/lib/heart_rate.js +34 -0
- package/dist/lib/heart_rate.js.map +1 -0
- package/dist/lib/highlight.js +81 -0
- package/dist/lib/highlight.js.map +1 -0
- package/dist/lib/install_links.js +47 -0
- package/dist/lib/install_links.js.map +1 -0
- package/dist/lib/instant.js +50 -0
- package/dist/lib/instant.js.map +1 -0
- package/dist/lib/journal_behaviors.js +382 -0
- package/dist/lib/journal_behaviors.js.map +1 -0
- package/dist/lib/lift_catalog.js +218 -0
- package/dist/lib/lift_catalog.js.map +1 -0
- package/dist/lib/lift_history.js +66 -0
- package/dist/lib/lift_history.js.map +1 -0
- package/dist/lib/lift_sets.js +146 -0
- package/dist/lib/lift_sets.js.map +1 -0
- package/dist/lib/lift_tool.js +20 -0
- package/dist/lib/lift_tool.js.map +1 -0
- package/dist/lib/profile_settings.js +101 -0
- package/dist/lib/profile_settings.js.map +1 -0
- package/dist/lib/screen_content.js +44 -0
- package/dist/lib/screen_content.js.map +1 -0
- package/dist/lib/timezone.js +48 -6
- package/dist/lib/timezone.js.map +1 -1
- package/dist/lib/walk.js +6 -1
- package/dist/lib/walk.js.map +1 -1
- package/dist/lib/weight_readings.js +61 -0
- package/dist/lib/weight_readings.js.map +1 -0
- package/dist/projections/activities.js +193 -0
- package/dist/projections/activities.js.map +1 -0
- package/dist/projections/alarm_schedule.js +102 -0
- package/dist/projections/alarm_schedule.js.map +1 -0
- package/dist/projections/coach.js +203 -0
- package/dist/projections/coach.js.map +1 -0
- package/dist/projections/community.js +165 -0
- package/dist/projections/community.js.map +1 -0
- package/dist/projections/health_features.js +167 -0
- package/dist/projections/health_features.js.map +1 -0
- package/dist/projections/hormonal_insights.js +239 -0
- package/dist/projections/hormonal_insights.js.map +1 -0
- package/dist/projections/journal_v2.js +157 -0
- package/dist/projections/journal_v2.js.map +1 -0
- package/dist/projections/lift_cards.js +115 -0
- package/dist/projections/lift_cards.js.map +1 -0
- package/dist/projections/lift_exercise_v2.js +131 -0
- package/dist/projections/lift_exercise_v2.js.map +1 -0
- package/dist/projections/lift_library_v2.js +67 -0
- package/dist/projections/lift_library_v2.js.map +1 -0
- package/dist/projections/lift_sessions.js +211 -0
- package/dist/projections/lift_sessions.js.map +1 -0
- package/dist/projections/memory.js +95 -0
- package/dist/projections/memory.js.map +1 -0
- package/dist/projections/milestones.js +119 -0
- package/dist/projections/milestones.js.map +1 -0
- package/dist/projections/profile_v2.js +150 -0
- package/dist/projections/profile_v2.js.map +1 -0
- package/dist/projections/settings_v2.js +153 -0
- package/dist/projections/settings_v2.js.map +1 -0
- package/dist/projections/sleep.js +4 -21
- package/dist/projections/sleep.js.map +1 -1
- package/dist/projections/v2/calendar.js +43 -0
- package/dist/projections/v2/calendar.js.map +1 -0
- package/dist/projections/v2/core_common.js +86 -0
- package/dist/projections/v2/core_common.js.map +1 -0
- package/dist/projections/v2/core_home.js +136 -0
- package/dist/projections/v2/core_home.js.map +1 -0
- package/dist/projections/v2/core_sleep_need.js +23 -0
- package/dist/projections/v2/core_sleep_need.js.map +1 -0
- package/dist/projections/v2/day.js +92 -0
- package/dist/projections/v2/day.js.map +1 -0
- package/dist/projections/v2/heart_rate.js +54 -0
- package/dist/projections/v2/heart_rate.js.map +1 -0
- package/dist/projections/v2/history.js +140 -0
- package/dist/projections/v2/history.js.map +1 -0
- package/dist/projections/v2/now.js +39 -0
- package/dist/projections/v2/now.js.map +1 -0
- package/dist/projections/v2/recovery.js +77 -0
- package/dist/projections/v2/recovery.js.map +1 -0
- package/dist/projections/v2/sleep.js +218 -0
- package/dist/projections/v2/sleep.js.map +1 -0
- package/dist/projections/v2/strain.js +39 -0
- package/dist/projections/v2/strain.js.map +1 -0
- package/dist/projections/v2/stress.js +92 -0
- package/dist/projections/v2/stress.js.map +1 -0
- package/dist/projections/v2/trend.js +205 -0
- package/dist/projections/v2/trend.js.map +1 -0
- package/dist/projections/weekly_plan.js +66 -0
- package/dist/projections/weekly_plan.js.map +1 -0
- package/dist/projections/weight_readings.js +57 -0
- package/dist/projections/weight_readings.js.map +1 -0
- package/dist/projections/workout.js +37 -15
- package/dist/projections/workout.js.map +1 -1
- package/dist/schemas/activities.js +123 -0
- package/dist/schemas/activities.js.map +1 -0
- package/dist/schemas/alarm_schedule.js +62 -0
- package/dist/schemas/alarm_schedule.js.map +1 -0
- package/dist/schemas/coach.js +76 -8
- package/dist/schemas/coach.js.map +1 -1
- package/dist/schemas/community.js +70 -0
- package/dist/schemas/community.js.map +1 -0
- package/dist/schemas/health.js +36 -0
- package/dist/schemas/health.js.map +1 -0
- package/dist/schemas/hormonal_insights.js +90 -0
- package/dist/schemas/hormonal_insights.js.map +1 -0
- package/dist/schemas/journal.js +4 -0
- package/dist/schemas/journal.js.map +1 -1
- package/dist/schemas/journal_v2.js +106 -0
- package/dist/schemas/journal_v2.js.map +1 -0
- package/dist/schemas/memory.js +42 -0
- package/dist/schemas/memory.js.map +1 -0
- package/dist/schemas/milestones.js +39 -0
- package/dist/schemas/milestones.js.map +1 -0
- package/dist/schemas/profile_v2.js +60 -0
- package/dist/schemas/profile_v2.js.map +1 -0
- package/dist/schemas/settings_v2.js +56 -0
- package/dist/schemas/settings_v2.js.map +1 -0
- package/dist/schemas/sleep.js +8 -1
- package/dist/schemas/sleep.js.map +1 -1
- package/dist/schemas/strength.js +10 -1
- package/dist/schemas/strength.js.map +1 -1
- package/dist/schemas/strength_v2.js +190 -0
- package/dist/schemas/strength_v2.js.map +1 -0
- package/dist/schemas/v2/calendar.js +8 -0
- package/dist/schemas/v2/calendar.js.map +1 -0
- package/dist/schemas/v2/core_common.js +42 -0
- package/dist/schemas/v2/core_common.js.map +1 -0
- package/dist/schemas/v2/day.js +73 -0
- package/dist/schemas/v2/day.js.map +1 -0
- package/dist/schemas/v2/now.js +25 -0
- package/dist/schemas/v2/now.js.map +1 -0
- package/dist/schemas/v2/recovery.js +35 -0
- package/dist/schemas/v2/recovery.js.map +1 -0
- package/dist/schemas/v2/sleep.js +44 -0
- package/dist/schemas/v2/sleep.js.map +1 -0
- package/dist/schemas/v2/strain.js +16 -0
- package/dist/schemas/v2/strain.js.map +1 -0
- package/dist/schemas/v2/stress.js +20 -0
- package/dist/schemas/v2/stress.js.map +1 -0
- package/dist/schemas/v2/trend.js +42 -0
- package/dist/schemas/v2/trend.js.map +1 -0
- package/dist/schemas/weekly_plan.js +31 -0
- package/dist/schemas/weekly_plan.js.map +1 -0
- package/dist/schemas/weight.js +28 -0
- package/dist/schemas/weight.js.map +1 -0
- package/dist/scripts/build_behaviors.js +114 -0
- package/dist/scripts/build_behaviors.js.map +1 -0
- package/dist/scripts/cognito_bootstrap.js +9 -277
- package/dist/scripts/cognito_bootstrap.js.map +1 -1
- package/dist/scripts/gen_activity_catalogs.js +104 -0
- package/dist/scripts/gen_activity_catalogs.js.map +1 -0
- package/dist/server-admin.js +156 -0
- package/dist/server-admin.js.map +1 -0
- package/dist/server-http.js +270 -48
- package/dist/server-http.js.map +1 -1
- package/dist/server.js +136 -23
- package/dist/server.js.map +1 -1
- package/dist/tools/annotations.js +15 -0
- package/dist/tools/annotations.js.map +1 -0
- package/dist/tools/define.js +31 -0
- package/dist/tools/define.js.map +1 -0
- package/dist/tools/register.js +59 -94
- package/dist/tools/register.js.map +1 -1
- package/dist/tools/resources.js +70 -0
- package/dist/tools/resources.js.map +1 -0
- package/dist/tools/slim_schema.js +90 -0
- package/dist/tools/slim_schema.js.map +1 -0
- package/dist/tools/v2/activity_delete.js +63 -17
- package/dist/tools/v2/activity_delete.js.map +1 -1
- package/dist/tools/v2/activity_edit.js +396 -0
- package/dist/tools/v2/activity_edit.js.map +1 -0
- package/dist/tools/v2/activity_log.js +152 -0
- package/dist/tools/v2/activity_log.js.map +1 -0
- package/dist/tools/v2/calendar.js +19 -21
- package/dist/tools/v2/calendar.js.map +1 -1
- package/dist/tools/v2/coach_ask.js +74 -110
- package/dist/tools/v2/coach_ask.js.map +1 -1
- package/dist/tools/v2/coach_history.js +120 -0
- package/dist/tools/v2/coach_history.js.map +1 -0
- package/dist/tools/v2/community.js +124 -0
- package/dist/tools/v2/community.js.map +1 -0
- package/dist/tools/v2/cycle.js +63 -15
- package/dist/tools/v2/cycle.js.map +1 -1
- package/dist/tools/v2/cycle_log.js +289 -32
- package/dist/tools/v2/cycle_log.js.map +1 -1
- package/dist/tools/v2/day.js +126 -24
- package/dist/tools/v2/day.js.map +1 -1
- package/dist/tools/v2/health.js +116 -0
- package/dist/tools/v2/health.js.map +1 -0
- package/dist/tools/v2/hr_zones_set.js +134 -34
- package/dist/tools/v2/hr_zones_set.js.map +1 -1
- package/dist/tools/v2/journal.js +75 -17
- package/dist/tools/v2/journal.js.map +1 -1
- package/dist/tools/v2/journal_log.js +306 -65
- package/dist/tools/v2/journal_log.js.map +1 -1
- package/dist/tools/v2/lift_exercise.js +125 -22
- package/dist/tools/v2/lift_exercise.js.map +1 -1
- package/dist/tools/v2/lift_exercise_set.js +291 -0
- package/dist/tools/v2/lift_exercise_set.js.map +1 -0
- package/dist/tools/v2/lift_library.js +51 -12
- package/dist/tools/v2/lift_library.js.map +1 -1
- package/dist/tools/v2/lift_log.js +309 -72
- package/dist/tools/v2/lift_log.js.map +1 -1
- package/dist/tools/v2/lift_sessions.js +248 -0
- package/dist/tools/v2/lift_sessions.js.map +1 -0
- package/dist/tools/v2/lift_template.js +232 -0
- package/dist/tools/v2/lift_template.js.map +1 -0
- package/dist/tools/v2/memory.js +45 -0
- package/dist/tools/v2/memory.js.map +1 -0
- package/dist/tools/v2/memory_set.js +107 -0
- package/dist/tools/v2/memory_set.js.map +1 -0
- package/dist/tools/v2/milestones.js +50 -0
- package/dist/tools/v2/milestones.js.map +1 -0
- package/dist/tools/v2/now.js +49 -0
- package/dist/tools/v2/now.js.map +1 -0
- package/dist/tools/v2/preferences.js +51 -0
- package/dist/tools/v2/preferences.js.map +1 -0
- package/dist/tools/v2/preferences_set.js +388 -0
- package/dist/tools/v2/preferences_set.js.map +1 -0
- package/dist/tools/v2/profile.js +54 -22
- package/dist/tools/v2/profile.js.map +1 -1
- package/dist/tools/v2/profile_update.js +167 -55
- package/dist/tools/v2/profile_update.js.map +1 -1
- package/dist/tools/v2/raw.js +91 -34
- package/dist/tools/v2/raw.js.map +1 -1
- package/dist/tools/v2/recovery.js +37 -23
- package/dist/tools/v2/recovery.js.map +1 -1
- package/dist/tools/v2/sleep.js +52 -16
- package/dist/tools/v2/sleep.js.map +1 -1
- package/dist/tools/v2/smart_alarm.js +54 -20
- package/dist/tools/v2/smart_alarm.js.map +1 -1
- package/dist/tools/v2/smart_alarm_set.js +264 -86
- package/dist/tools/v2/smart_alarm_set.js.map +1 -1
- package/dist/tools/v2/strain.js +15 -15
- package/dist/tools/v2/strain.js.map +1 -1
- package/dist/tools/v2/stress.js +17 -15
- package/dist/tools/v2/stress.js.map +1 -1
- package/dist/tools/v2/trend.js +56 -20
- package/dist/tools/v2/trend.js.map +1 -1
- package/dist/tools/v2/weekly_plan.js +30 -0
- package/dist/tools/v2/weekly_plan.js.map +1 -0
- package/dist/tools/v2/weekly_plan_set.js +134 -0
- package/dist/tools/v2/weekly_plan_set.js.map +1 -0
- package/dist/tools/v2/weight.js +56 -0
- package/dist/tools/v2/weight.js.map +1 -0
- package/dist/tools/v2/weight_log.js +188 -0
- package/dist/tools/v2/weight_log.js.map +1 -0
- package/dist/tools/v2/workouts.js +159 -25
- package/dist/tools/v2/workouts.js.map +1 -1
- package/dist/version.js +6 -0
- package/dist/version.js.map +1 -0
- package/dist/whoop/bff.js +94 -0
- package/dist/whoop/bff.js.map +1 -0
- package/dist/whoop/client.js +392 -18
- package/dist/whoop/client.js.map +1 -1
- package/dist/whoop/cognito.js +106 -79
- package/dist/whoop/cognito.js.map +1 -1
- package/dist/whoop/connect_page.js +165 -0
- package/dist/whoop/connect_page.js.map +1 -0
- package/dist/whoop/consent_font.js +287 -0
- package/dist/whoop/consent_font.js.map +1 -0
- package/dist/whoop/consent_logos.js +22 -0
- package/dist/whoop/consent_logos.js.map +1 -0
- package/dist/whoop/consent_page.js +291 -0
- package/dist/whoop/consent_page.js.map +1 -0
- package/dist/whoop/constants.js +5 -1
- package/dist/whoop/constants.js.map +1 -1
- package/dist/whoop/device.js +4 -4
- package/dist/whoop/device.js.map +1 -1
- package/dist/whoop/errors.js +85 -4
- package/dist/whoop/errors.js.map +1 -1
- package/dist/whoop/init_timezone.js +57 -17
- package/dist/whoop/init_timezone.js.map +1 -1
- package/dist/whoop/installation.js +15 -10
- package/dist/whoop/installation.js.map +1 -1
- package/dist/whoop/json_out.js +52 -6
- package/dist/whoop/json_out.js.map +1 -1
- package/dist/whoop/oauth_provider.js +81 -78
- package/dist/whoop/oauth_provider.js.map +1 -1
- package/dist/whoop/token_lock.js +331 -0
- package/dist/whoop/token_lock.js.map +1 -0
- package/dist/whoop/token_manager.js +536 -42
- package/dist/whoop/token_manager.js.map +1 -1
- package/dist/whoop/token_store.js +303 -36
- package/dist/whoop/token_store.js.map +1 -1
- package/dist/whoop/units.js +28 -0
- package/dist/whoop/units.js.map +1 -0
- package/package.json +29 -13
- package/scripts/build-mcpb.mjs +72 -0
- package/scripts/embed-consent-font.mjs +34 -0
- package/scripts/readme-media.ts +195 -0
- package/scripts/tools-md.ts +89 -0
- package/scripts/whoop-md.ts +119 -0
- package/src/build_info.ts +4 -0
- package/src/cli/app.ts +696 -0
- package/src/cli/auth.ts +350 -0
- package/src/cli/auth_flow.ts +356 -0
- package/src/cli/browser_login.ts +402 -0
- package/src/cli/clients.ts +467 -0
- package/src/cli/deploy_record.ts +100 -0
- package/src/cli/index.ts +41 -583
- package/src/cli/links.ts +43 -0
- package/src/cli/logo.ts +64 -0
- package/src/cli/setup.ts +1147 -979
- package/src/cli/spawn.ts +88 -0
- package/src/cli/sys.ts +267 -0
- package/src/cli/ui.ts +778 -436
- package/src/cli/update.ts +436 -274
- package/src/cloudflare/runtime.d.ts +27 -0
- package/src/cloudflare/token_store.ts +57 -0
- package/src/cloudflare/worker.ts +174 -0
- package/src/data/behaviors.ts +2760 -622
- package/src/data/endpoint_catalog.ts +2695 -0
- package/src/data/exercises.ts +379 -4861
- package/src/data/garments.ts +28 -0
- package/src/data/sports.ts +239 -211
- package/src/lib/activity_list.ts +150 -0
- package/src/lib/activity_records.ts +213 -0
- package/src/lib/activity_results.ts +51 -0
- package/src/lib/activity_types.ts +176 -0
- package/src/lib/brand.ts +71 -0
- package/src/lib/clock.ts +16 -0
- package/src/lib/coach_session.ts +434 -0
- package/src/lib/dates.ts +18 -0
- package/src/lib/env_file.ts +191 -0
- package/src/lib/health_plans_write.ts +53 -0
- package/src/lib/heart_rate.ts +42 -0
- package/src/lib/highlight.ts +71 -0
- package/src/lib/install_links.ts +61 -0
- package/src/lib/instant.ts +54 -0
- package/src/lib/journal_behaviors.ts +453 -0
- package/src/lib/lift_catalog.ts +258 -0
- package/src/lib/lift_history.ts +75 -0
- package/src/lib/lift_sets.ts +164 -0
- package/src/lib/lift_tool.ts +25 -0
- package/src/lib/profile_settings.ts +102 -0
- package/src/lib/screen_content.ts +40 -0
- package/src/lib/timezone.ts +44 -8
- package/src/lib/walk.ts +4 -1
- package/src/lib/weight_readings.ts +82 -0
- package/src/projections/activities.ts +199 -0
- package/src/projections/alarm_schedule.ts +98 -0
- package/src/projections/coach.ts +218 -0
- package/src/projections/community.ts +187 -0
- package/src/projections/health_features.ts +191 -0
- package/src/projections/hormonal_insights.ts +277 -0
- package/src/projections/journal_v2.ts +173 -0
- package/src/projections/lift_cards.ts +131 -0
- package/src/projections/lift_exercise_v2.ts +147 -0
- package/src/projections/lift_library_v2.ts +77 -0
- package/src/projections/lift_sessions.ts +250 -0
- package/src/projections/memory.ts +100 -0
- package/src/projections/milestones.ts +133 -0
- package/src/projections/profile_v2.ts +166 -0
- package/src/projections/settings_v2.ts +179 -0
- package/src/projections/sleep.ts +7 -21
- package/src/projections/v2/calendar.ts +48 -0
- package/src/projections/v2/core_common.ts +95 -0
- package/src/projections/v2/core_home.ts +177 -0
- package/src/projections/v2/core_sleep_need.ts +37 -0
- package/src/projections/v2/day.ts +162 -0
- package/src/projections/v2/heart_rate.ts +73 -0
- package/src/projections/v2/history.ts +153 -0
- package/src/projections/v2/now.ts +59 -0
- package/src/projections/v2/recovery.ts +120 -0
- package/src/projections/v2/sleep.ts +281 -0
- package/src/projections/v2/strain.ts +63 -0
- package/src/projections/v2/stress.ts +111 -0
- package/src/projections/v2/trend.ts +242 -0
- package/src/projections/weekly_plan.ts +79 -0
- package/src/projections/weight_readings.ts +57 -0
- package/src/projections/workout.ts +36 -17
- package/src/schemas/activities.ts +136 -0
- package/src/schemas/alarm_schedule.ts +70 -0
- package/src/schemas/coach.ts +98 -8
- package/src/schemas/community.ts +77 -0
- package/src/schemas/health.ts +36 -0
- package/src/schemas/hormonal_insights.ts +108 -0
- package/src/schemas/journal.ts +4 -0
- package/src/schemas/journal_v2.ts +112 -0
- package/src/schemas/memory.ts +48 -0
- package/src/schemas/milestones.ts +48 -0
- package/src/schemas/profile_v2.ts +63 -0
- package/src/schemas/settings_v2.ts +63 -0
- package/src/schemas/sleep.ts +9 -1
- package/src/schemas/strength.ts +10 -1
- package/src/schemas/strength_v2.ts +210 -0
- package/src/schemas/v2/calendar.ts +8 -0
- package/src/schemas/v2/core_common.ts +50 -0
- package/src/schemas/v2/day.ts +79 -0
- package/src/schemas/v2/now.ts +25 -0
- package/src/schemas/v2/recovery.ts +38 -0
- package/src/schemas/v2/sleep.ts +46 -0
- package/src/schemas/v2/strain.ts +16 -0
- package/src/schemas/v2/stress.ts +20 -0
- package/src/schemas/v2/trend.ts +45 -0
- package/src/schemas/weekly_plan.ts +36 -0
- package/src/schemas/weight.ts +53 -0
- package/src/scripts/build_behaviors.ts +116 -0
- package/src/scripts/cognito_bootstrap.ts +10 -249
- package/src/scripts/gen_activity_catalogs.ts +121 -0
- package/src/server-admin.ts +171 -0
- package/src/server-http.ts +290 -53
- package/src/server.ts +130 -26
- package/src/tools/annotations.ts +25 -0
- package/src/tools/define.ts +53 -0
- package/src/tools/register.ts +64 -94
- package/src/tools/resources.ts +92 -0
- package/src/tools/slim_schema.ts +102 -0
- package/src/tools/v2/activity_delete.ts +61 -23
- package/src/tools/v2/activity_edit.ts +378 -0
- package/src/tools/v2/activity_log.ts +154 -0
- package/src/tools/v2/calendar.ts +22 -21
- package/src/tools/v2/coach_ask.ts +83 -119
- package/src/tools/v2/coach_history.ts +140 -0
- package/src/tools/v2/community.ts +137 -0
- package/src/tools/v2/cycle.ts +78 -20
- package/src/tools/v2/cycle_log.ts +291 -40
- package/src/tools/v2/day.ts +126 -25
- package/src/tools/v2/health.ts +114 -0
- package/src/tools/v2/hr_zones_set.ts +132 -45
- package/src/tools/v2/journal.ts +78 -23
- package/src/tools/v2/journal_log.ts +321 -69
- package/src/tools/v2/lift_exercise.ts +135 -27
- package/src/tools/v2/lift_exercise_set.ts +272 -0
- package/src/tools/v2/lift_library.ts +57 -21
- package/src/tools/v2/lift_log.ts +325 -83
- package/src/tools/v2/lift_sessions.ts +255 -0
- package/src/tools/v2/lift_template.ts +229 -0
- package/src/tools/v2/memory.ts +54 -0
- package/src/tools/v2/memory_set.ts +110 -0
- package/src/tools/v2/milestones.ts +59 -0
- package/src/tools/v2/now.ts +61 -0
- package/src/tools/v2/preferences.ts +61 -0
- package/src/tools/v2/preferences_set.ts +403 -0
- package/src/tools/v2/profile.ts +56 -26
- package/src/tools/v2/profile_update.ts +151 -60
- package/src/tools/v2/raw.ts +89 -36
- package/src/tools/v2/recovery.ts +44 -25
- package/src/tools/v2/sleep.ts +57 -18
- package/src/tools/v2/smart_alarm.ts +62 -24
- package/src/tools/v2/smart_alarm_set.ts +240 -90
- package/src/tools/v2/strain.ts +19 -16
- package/src/tools/v2/stress.ts +22 -17
- package/src/tools/v2/trend.ts +58 -20
- package/src/tools/v2/weekly_plan.ts +38 -0
- package/src/tools/v2/weekly_plan_set.ts +132 -0
- package/src/tools/v2/weight.ts +61 -0
- package/src/tools/v2/weight_log.ts +193 -0
- package/src/tools/v2/workouts.ts +156 -26
- package/src/version.ts +5 -0
- package/src/whoop/bff.ts +84 -0
- package/src/whoop/client.ts +448 -18
- package/src/whoop/cognito.ts +110 -99
- package/src/whoop/connect_page.ts +183 -0
- package/src/whoop/consent_font.ts +289 -0
- package/src/whoop/consent_logos.ts +24 -0
- package/src/whoop/consent_page.ts +326 -0
- package/src/whoop/constants.ts +5 -1
- package/src/whoop/device.ts +4 -4
- package/src/whoop/errors.ts +89 -4
- package/src/whoop/init_timezone.ts +57 -16
- package/src/whoop/installation.ts +16 -7
- package/src/whoop/json_out.ts +51 -6
- package/src/whoop/oauth_provider.ts +84 -91
- package/src/whoop/token_lock.ts +345 -0
- package/src/whoop/token_manager.ts +580 -53
- package/src/whoop/token_store.ts +341 -32
- package/src/whoop/units.ts +35 -0
- package/wrangler.jsonc +17 -0
- package/assets/banner.svg +0 -38
- package/dist/data/endpoints.js +0 -320
- package/dist/data/endpoints.js.map +0 -1
- package/dist/lib/format.js +0 -22
- package/dist/lib/format.js.map +0 -1
- package/dist/lib/stats.js +0 -32
- package/dist/lib/stats.js.map +0 -1
- package/dist/projections/calendar.js +0 -33
- package/dist/projections/calendar.js.map +0 -1
- package/dist/projections/communities.js +0 -105
- package/dist/projections/communities.js.map +0 -1
- package/dist/projections/cycle.js +0 -81
- package/dist/projections/cycle.js.map +0 -1
- package/dist/projections/hr_zones.js +0 -35
- package/dist/projections/hr_zones.js.map +0 -1
- package/dist/projections/journal.js +0 -56
- package/dist/projections/journal.js.map +0 -1
- package/dist/projections/leaderboard.js +0 -37
- package/dist/projections/leaderboard.js.map +0 -1
- package/dist/projections/lift_exercise.js +0 -22
- package/dist/projections/lift_exercise.js.map +0 -1
- package/dist/projections/lift_history.js +0 -133
- package/dist/projections/lift_history.js.map +0 -1
- package/dist/projections/lift_library.js +0 -71
- package/dist/projections/lift_library.js.map +0 -1
- package/dist/projections/lift_progression.js +0 -138
- package/dist/projections/lift_progression.js.map +0 -1
- package/dist/projections/lift_prs.js +0 -20
- package/dist/projections/lift_prs.js.map +0 -1
- package/dist/projections/live_hr.js +0 -19
- package/dist/projections/live_hr.js.map +0 -1
- package/dist/projections/live_state.js +0 -23
- package/dist/projections/live_state.js.map +0 -1
- package/dist/projections/live_stress.js +0 -11
- package/dist/projections/live_stress.js.map +0 -1
- package/dist/projections/performance_assessment.js +0 -15
- package/dist/projections/performance_assessment.js.map +0 -1
- package/dist/projections/profile.js +0 -59
- package/dist/projections/profile.js.map +0 -1
- package/dist/projections/recovery.js +0 -131
- package/dist/projections/recovery.js.map +0 -1
- package/dist/projections/sleep_need.js +0 -32
- package/dist/projections/sleep_need.js.map +0 -1
- package/dist/projections/smart_alarm.js +0 -45
- package/dist/projections/smart_alarm.js.map +0 -1
- package/dist/projections/strain.js +0 -128
- package/dist/projections/strain.js.map +0 -1
- package/dist/projections/stress.js +0 -86
- package/dist/projections/stress.js.map +0 -1
- package/dist/projections/today.js +0 -129
- package/dist/projections/today.js.map +0 -1
- package/dist/projections/trend.js +0 -149
- package/dist/projections/trend.js.map +0 -1
- package/dist/projections/workouts.js +0 -37
- package/dist/projections/workouts.js.map +0 -1
- package/dist/schemas/calendar.js +0 -12
- package/dist/schemas/calendar.js.map +0 -1
- package/dist/schemas/communities.js +0 -51
- package/dist/schemas/communities.js.map +0 -1
- package/dist/schemas/compare.js +0 -15
- package/dist/schemas/compare.js.map +0 -1
- package/dist/schemas/leaderboard.js +0 -25
- package/dist/schemas/leaderboard.js.map +0 -1
- package/dist/schemas/live.js +0 -26
- package/dist/schemas/live.js.map +0 -1
- package/dist/schemas/performance.js +0 -12
- package/dist/schemas/performance.js.map +0 -1
- package/dist/schemas/profile.js +0 -39
- package/dist/schemas/profile.js.map +0 -1
- package/dist/schemas/recovery.js +0 -27
- package/dist/schemas/recovery.js.map +0 -1
- package/dist/schemas/settings.js +0 -26
- package/dist/schemas/settings.js.map +0 -1
- package/dist/schemas/sleep_need.js +0 -15
- package/dist/schemas/sleep_need.js.map +0 -1
- package/dist/schemas/smart_alarm.js +0 -36
- package/dist/schemas/smart_alarm.js.map +0 -1
- package/dist/schemas/strain.js +0 -24
- package/dist/schemas/strain.js.map +0 -1
- package/dist/schemas/stress.js +0 -16
- package/dist/schemas/stress.js.map +0 -1
- package/dist/schemas/today.js +0 -38
- package/dist/schemas/today.js.map +0 -1
- package/dist/schemas/trend.js +0 -50
- package/dist/schemas/trend.js.map +0 -1
- package/dist/schemas/womens_health.js +0 -23
- package/dist/schemas/womens_health.js.map +0 -1
- package/dist/tools/v2/activity_create.js +0 -64
- package/dist/tools/v2/activity_create.js.map +0 -1
- package/dist/tools/v2/behavior_impact.js +0 -36
- package/dist/tools/v2/behavior_impact.js.map +0 -1
- package/dist/tools/v2/communities.js +0 -60
- package/dist/tools/v2/communities.js.map +0 -1
- package/dist/tools/v2/compare.js +0 -67
- package/dist/tools/v2/compare.js.map +0 -1
- package/dist/tools/v2/endpoints.js +0 -28
- package/dist/tools/v2/endpoints.js.map +0 -1
- package/dist/tools/v2/hidden_metric.js +0 -28
- package/dist/tools/v2/hidden_metric.js.map +0 -1
- package/dist/tools/v2/hr_zones.js +0 -24
- package/dist/tools/v2/hr_zones.js.map +0 -1
- package/dist/tools/v2/journal_autopop.js +0 -19
- package/dist/tools/v2/journal_autopop.js.map +0 -1
- package/dist/tools/v2/journal_catalog.js +0 -44
- package/dist/tools/v2/journal_catalog.js.map +0 -1
- package/dist/tools/v2/leaderboard.js +0 -79
- package/dist/tools/v2/leaderboard.js.map +0 -1
- package/dist/tools/v2/lift_catalog.js +0 -47
- package/dist/tools/v2/lift_catalog.js.map +0 -1
- package/dist/tools/v2/lift_custom_exercise.js +0 -108
- package/dist/tools/v2/lift_custom_exercise.js.map +0 -1
- package/dist/tools/v2/lift_history.js +0 -39
- package/dist/tools/v2/lift_history.js.map +0 -1
- package/dist/tools/v2/lift_progression.js +0 -30
- package/dist/tools/v2/lift_progression.js.map +0 -1
- package/dist/tools/v2/lift_prs.js +0 -21
- package/dist/tools/v2/lift_prs.js.map +0 -1
- package/dist/tools/v2/lift_template_save.js +0 -83
- package/dist/tools/v2/lift_template_save.js.map +0 -1
- package/dist/tools/v2/live_hr.js +0 -21
- package/dist/tools/v2/live_hr.js.map +0 -1
- package/dist/tools/v2/live_state.js +0 -21
- package/dist/tools/v2/live_state.js.map +0 -1
- package/dist/tools/v2/live_stress.js +0 -22
- package/dist/tools/v2/live_stress.js.map +0 -1
- package/dist/tools/v2/performance_assessment.js +0 -38
- package/dist/tools/v2/performance_assessment.js.map +0 -1
- package/dist/tools/v2/sleep_need.js +0 -21
- package/dist/tools/v2/sleep_need.js.map +0 -1
- package/dist/tools/v2/sports_catalog.js +0 -26
- package/dist/tools/v2/sports_catalog.js.map +0 -1
- package/dist/tools/v2/symptom_log.js +0 -72
- package/dist/tools/v2/symptom_log.js.map +0 -1
- package/dist/tools/v2/today.js +0 -30
- package/dist/tools/v2/today.js.map +0 -1
- package/dist/tools/v2/workout.js +0 -23
- package/dist/tools/v2/workout.js.map +0 -1
- package/dist/whoop/build_lift_body.js +0 -67
- package/dist/whoop/build_lift_body.js.map +0 -1
- package/dist/whoop/session_state.js +0 -34
- package/dist/whoop/session_state.js.map +0 -1
- package/dist/whoop/types.js +0 -82
- package/dist/whoop/types.js.map +0 -1
- package/src/data/endpoints.ts +0 -319
- package/src/lib/format.ts +0 -27
- package/src/lib/stats.ts +0 -35
- package/src/projections/calendar.ts +0 -46
- package/src/projections/communities.ts +0 -135
- package/src/projections/cycle.ts +0 -85
- package/src/projections/hr_zones.ts +0 -43
- package/src/projections/journal.ts +0 -55
- package/src/projections/leaderboard.ts +0 -49
- package/src/projections/lift_exercise.ts +0 -29
- package/src/projections/lift_history.ts +0 -140
- package/src/projections/lift_library.ts +0 -70
- package/src/projections/lift_progression.ts +0 -138
- package/src/projections/lift_prs.ts +0 -23
- package/src/projections/live_hr.ts +0 -21
- package/src/projections/live_state.ts +0 -28
- package/src/projections/live_stress.ts +0 -13
- package/src/projections/performance_assessment.ts +0 -19
- package/src/projections/profile.ts +0 -71
- package/src/projections/recovery.ts +0 -133
- package/src/projections/sleep_need.ts +0 -36
- package/src/projections/smart_alarm.ts +0 -70
- package/src/projections/strain.ts +0 -131
- package/src/projections/stress.ts +0 -95
- package/src/projections/today.ts +0 -166
- package/src/projections/trend.ts +0 -149
- package/src/projections/workouts.ts +0 -36
- package/src/schemas/calendar.ts +0 -13
- package/src/schemas/communities.ts +0 -56
- package/src/schemas/compare.ts +0 -17
- package/src/schemas/leaderboard.ts +0 -26
- package/src/schemas/live.ts +0 -31
- package/src/schemas/performance.ts +0 -13
- package/src/schemas/profile.ts +0 -40
- package/src/schemas/recovery.ts +0 -28
- package/src/schemas/settings.ts +0 -30
- package/src/schemas/sleep_need.ts +0 -16
- package/src/schemas/smart_alarm.ts +0 -40
- package/src/schemas/strain.ts +0 -25
- package/src/schemas/stress.ts +0 -17
- package/src/schemas/today.ts +0 -39
- package/src/schemas/trend.ts +0 -53
- package/src/schemas/womens_health.ts +0 -26
- package/src/tools/v2/activity_create.ts +0 -74
- package/src/tools/v2/behavior_impact.ts +0 -39
- package/src/tools/v2/communities.ts +0 -65
- package/src/tools/v2/compare.ts +0 -83
- package/src/tools/v2/endpoints.ts +0 -32
- package/src/tools/v2/hidden_metric.ts +0 -33
- package/src/tools/v2/hr_zones.ts +0 -29
- package/src/tools/v2/journal_autopop.ts +0 -26
- package/src/tools/v2/journal_catalog.ts +0 -48
- package/src/tools/v2/leaderboard.ts +0 -92
- package/src/tools/v2/lift_catalog.ts +0 -48
- package/src/tools/v2/lift_custom_exercise.ts +0 -117
- package/src/tools/v2/lift_history.ts +0 -52
- package/src/tools/v2/lift_progression.ts +0 -34
- package/src/tools/v2/lift_prs.ts +0 -26
- package/src/tools/v2/lift_template_save.ts +0 -89
- package/src/tools/v2/live_hr.ts +0 -26
- package/src/tools/v2/live_state.ts +0 -26
- package/src/tools/v2/live_stress.ts +0 -27
- package/src/tools/v2/performance_assessment.ts +0 -44
- package/src/tools/v2/sleep_need.ts +0 -26
- package/src/tools/v2/sports_catalog.ts +0 -32
- package/src/tools/v2/symptom_log.ts +0 -78
- package/src/tools/v2/today.ts +0 -35
- package/src/tools/v2/workout.ts +0 -28
- package/src/whoop/build_lift_body.ts +0 -84
- package/src/whoop/session_state.ts +0 -41
- package/src/whoop/types.ts +0 -89
package/src/whoop/json_out.ts
CHANGED
|
@@ -1,9 +1,54 @@
|
|
|
1
1
|
import { localizeTimestamps } from "../lib/timezone.js";
|
|
2
2
|
|
|
3
|
-
// Compact JSON for MCP tool responses.
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
|
|
8
|
-
|
|
3
|
+
// Compact JSON for MCP tool responses. Tool output is read by a model, not a
|
|
4
|
+
// person, so it is optimised for tokens:
|
|
5
|
+
// - no whitespace
|
|
6
|
+
// - null / undefined / [] / {} object properties are dropped ("absent" means
|
|
7
|
+
// "not available"); array elements are never dropped (position can matter)
|
|
8
|
+
// - floats are rounded to 3 decimals (WHOOP sends float32 noise such as
|
|
9
|
+
// 0.8726999759674072)
|
|
10
|
+
// - UTC timestamps are rewritten as local ISO with an explicit offset, and a
|
|
11
|
+
// zero milliseconds part (".000") is dropped
|
|
12
|
+
// Zod validation runs on the full shape BEFORE this (see tools/define.ts), so
|
|
13
|
+
// schemas stay strict while the wire stays small.
|
|
14
|
+
//
|
|
15
|
+
// Not compacted: anything under a `will_execute` key (a write preview must show
|
|
16
|
+
// exactly what would be sent, nulls included) and callers that pass
|
|
17
|
+
// { compact: false } (whoop_raw returns WHOOP's response faithfully).
|
|
18
|
+
|
|
19
|
+
const KEEP_SUBTREE_KEYS = new Set(["will_execute"]);
|
|
20
|
+
|
|
21
|
+
function isEmpty(v: unknown): boolean {
|
|
22
|
+
if (v === null || v === undefined) return true;
|
|
23
|
+
if (Array.isArray(v)) return v.length === 0;
|
|
24
|
+
if (typeof v === "object") return Object.keys(v as object).length === 0;
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const ZERO_MS_ISO = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\.000(Z|[+-]\d{2}:\d{2})$/;
|
|
29
|
+
|
|
30
|
+
export function compact(value: unknown): unknown {
|
|
31
|
+
if (typeof value === "string") return value.length <= 29 ? value.replace(ZERO_MS_ISO, "$1$2") : value;
|
|
32
|
+
if (typeof value === "number") {
|
|
33
|
+
return Number.isInteger(value) || !Number.isFinite(value) ? value : Math.round(value * 1000) / 1000;
|
|
34
|
+
}
|
|
35
|
+
if (Array.isArray(value)) return value.map(compact);
|
|
36
|
+
if (value !== null && typeof value === "object") {
|
|
37
|
+
const out: Record<string, unknown> = {};
|
|
38
|
+
for (const [k, v] of Object.entries(value)) {
|
|
39
|
+
if (KEEP_SUBTREE_KEYS.has(k)) {
|
|
40
|
+
out[k] = v;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
const c = compact(v);
|
|
44
|
+
if (!isEmpty(c)) out[k] = c;
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function jsonOut(data: unknown, options: { compact?: boolean } = {}): string {
|
|
52
|
+
const localized = localizeTimestamps(data);
|
|
53
|
+
return JSON.stringify(options.compact === false ? localized : compact(localized));
|
|
9
54
|
}
|
|
@@ -29,7 +29,12 @@ import type {
|
|
|
29
29
|
OAuthTokens,
|
|
30
30
|
} from "@modelcontextprotocol/sdk/shared/auth.js";
|
|
31
31
|
import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
|
|
32
|
-
import { InvalidTokenError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
|
|
32
|
+
import { InvalidGrantError, InvalidScopeError, InvalidTokenError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
|
|
33
|
+
import { redirectUriMatches } from "@modelcontextprotocol/sdk/server/auth/handlers/authorize.js";
|
|
34
|
+
import { cleanClientName, redirectDestination, renderConsentForm, setConsentSecurityHeaders } from "./consent_page.js";
|
|
35
|
+
|
|
36
|
+
// The consent page moved to consent_page.ts; these stay importable from here.
|
|
37
|
+
export { CONSENT_CSP, redirectDestination, renderConsentForm, setConsentSecurityHeaders } from "./consent_page.js";
|
|
33
38
|
|
|
34
39
|
const ACCESS_TTL_S = 3600; // 1 hour
|
|
35
40
|
const REFRESH_TTL_S = 30 * 24 * 3600; // 30 days
|
|
@@ -113,8 +118,10 @@ export class WhoopOAuthProvider implements OAuthServerProvider {
|
|
|
113
118
|
if (!clientId.startsWith("c.")) return undefined;
|
|
114
119
|
const payload = verifyToken(clientId.slice(2), this.signingSecret);
|
|
115
120
|
if (!payload || payload.t !== "client") return undefined;
|
|
121
|
+
const name = cleanClientName(payload.n);
|
|
116
122
|
return {
|
|
117
123
|
client_id: clientId,
|
|
124
|
+
...(name ? { client_name: name } : {}),
|
|
118
125
|
redirect_uris: (payload.ru as string[]) ?? [],
|
|
119
126
|
token_endpoint_auth_method: "none",
|
|
120
127
|
grant_types: ["authorization_code", "refresh_token"],
|
|
@@ -132,12 +139,17 @@ export class WhoopOAuthProvider implements OAuthServerProvider {
|
|
|
132
139
|
client: Omit<OAuthClientInformationFull, "client_id" | "client_id_issued_at">,
|
|
133
140
|
): OAuthClientInformationFull => {
|
|
134
141
|
// Encode the client's redirect_uris into a signed client_id so the
|
|
135
|
-
// registration survives server restarts with no storage.
|
|
142
|
+
// registration survives server restarts with no storage. The name it
|
|
143
|
+
// gave rides along (cleaned and capped): the consent page shows it for
|
|
144
|
+
// a client on the owner's own device, and never for one on the internet.
|
|
145
|
+
const name = cleanClientName(client.client_name);
|
|
136
146
|
const signed = signToken(
|
|
137
|
-
{ t: "client", ru: client.redirect_uris ?? [], sc: client.scope ?? "", jti: randomUUID() },
|
|
147
|
+
{ t: "client", ru: client.redirect_uris ?? [], sc: client.scope ?? "", ...(name ? { n: name } : {}), jti: randomUUID() },
|
|
138
148
|
this.signingSecret,
|
|
139
149
|
);
|
|
140
150
|
const clientId = `c.${signed}`;
|
|
151
|
+
// Registration is open to anyone, so say who came by. Names and addresses only.
|
|
152
|
+
console.error(`[totem] client registered: ${JSON.stringify(name ?? "(no name)")} -> ${(client.redirect_uris ?? []).map(redirectDestination).join(", ") || "(no redirect)"}`);
|
|
141
153
|
return {
|
|
142
154
|
...client,
|
|
143
155
|
client_id: clientId,
|
|
@@ -167,9 +179,31 @@ export class WhoopOAuthProvider implements OAuthServerProvider {
|
|
|
167
179
|
scopes: (params.scopes ?? []).join(" "),
|
|
168
180
|
resource: params.resource?.toString() ?? "",
|
|
169
181
|
error: false,
|
|
182
|
+
clientName: client.client_name,
|
|
170
183
|
}));
|
|
171
184
|
}
|
|
172
185
|
|
|
186
|
+
/** The name a client registered with, for re-rendering the page after a wrong password. */
|
|
187
|
+
registeredName(clientId: string): string | undefined {
|
|
188
|
+
return this.decodeClient(clientId)?.client_name;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ─── consent POST, Deny ──────────────────────────────────────────────────
|
|
192
|
+
// The owner said no: send the client back with `access_denied` (RFC 6749
|
|
193
|
+
// §4.1.2.1) so it can say so instead of waiting. Only ever to a redirect URI
|
|
194
|
+
// this client registered; null means there is nowhere safe to send it.
|
|
195
|
+
deny(input: { clientId: string; redirectUri: string; state: string }): string | null {
|
|
196
|
+
const client = this.decodeClient(input.clientId);
|
|
197
|
+
if (!client || !URL.canParse(input.redirectUri)) return null;
|
|
198
|
+
if (!client.redirect_uris.some((registered) => redirectUriMatches(input.redirectUri, registered))) return null;
|
|
199
|
+
const url = new URL(input.redirectUri);
|
|
200
|
+
url.searchParams.set("error", "access_denied");
|
|
201
|
+
url.searchParams.set("error_description", "The owner denied the request.");
|
|
202
|
+
if (input.state) url.searchParams.set("state", input.state);
|
|
203
|
+
console.error(`[totem] consent denied by the owner: ${redirectDestination(input.redirectUri)}`);
|
|
204
|
+
return url.toString();
|
|
205
|
+
}
|
|
206
|
+
|
|
173
207
|
// ─── consent POST: validate password, issue an auth code ─────────────────
|
|
174
208
|
// Returns the redirect URL to send the browser to, or null if the password
|
|
175
209
|
// was wrong (caller re-renders the form with an error).
|
|
@@ -182,7 +216,7 @@ export class WhoopOAuthProvider implements OAuthServerProvider {
|
|
|
182
216
|
resource: string;
|
|
183
217
|
password: string;
|
|
184
218
|
}): string | null {
|
|
185
|
-
if (!
|
|
219
|
+
if (!this.checkPassword(input.password)) {
|
|
186
220
|
console.error("[totem] consent REJECTED: password mismatch");
|
|
187
221
|
return null;
|
|
188
222
|
}
|
|
@@ -192,19 +226,27 @@ export class WhoopOAuthProvider implements OAuthServerProvider {
|
|
|
192
226
|
console.error("[totem] consent REJECTED: client_id failed to decode (stale registration / signing-key mismatch) — password was correct");
|
|
193
227
|
return null;
|
|
194
228
|
}
|
|
195
|
-
|
|
229
|
+
// Same rule as the SDK's /authorize (RFC 8252: any port on a loopback host),
|
|
230
|
+
// so a redirect /authorize accepted isn't rejected here.
|
|
231
|
+
if (!client.redirect_uris.some((registered) => redirectUriMatches(input.redirectUri, registered))) {
|
|
196
232
|
console.error(`[totem] consent REJECTED: redirect_uri not registered: ${input.redirectUri} — password was correct`);
|
|
197
233
|
return null;
|
|
198
234
|
}
|
|
199
235
|
|
|
236
|
+
// Codes are otherwise only removed when redeemed; drop the ones nobody came back for.
|
|
237
|
+
const now = Date.now();
|
|
238
|
+
for (const [stale, entry] of this.codes) if (entry.expiresAt < now) this.codes.delete(stale);
|
|
239
|
+
|
|
200
240
|
const code = b64url(randomBytes(32));
|
|
201
241
|
this.codes.set(code, {
|
|
202
242
|
challenge: input.codeChallenge,
|
|
203
243
|
redirectUri: input.redirectUri,
|
|
204
244
|
clientId: input.clientId,
|
|
205
245
|
scopes: input.scopes ? input.scopes.split(" ").filter(Boolean) : [],
|
|
206
|
-
|
|
207
|
-
|
|
246
|
+
// The form posts this field back unchecked. A value that isn't a URL
|
|
247
|
+
// would be signed into the tokens and then throw in verifyAccessToken.
|
|
248
|
+
resource: URL.canParse(input.resource) ? input.resource : undefined,
|
|
249
|
+
expiresAt: now + CODE_TTL_MS,
|
|
208
250
|
});
|
|
209
251
|
|
|
210
252
|
const url = new URL(input.redirectUri);
|
|
@@ -213,25 +255,38 @@ export class WhoopOAuthProvider implements OAuthServerProvider {
|
|
|
213
255
|
return url.toString();
|
|
214
256
|
}
|
|
215
257
|
|
|
258
|
+
checkPassword(password: string): boolean {
|
|
259
|
+
// No password configured means the OAuth path is off, not that the empty
|
|
260
|
+
// password is correct ("" equals "" under the comparison below). The HTTP
|
|
261
|
+
// route also refuses, but the gate shouldn't rest on one caller's `if`.
|
|
262
|
+
return this.password.length > 0 && constantTimeEqual(password, this.password);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// A bad grant must be the SDK's InvalidGrantError: the token endpoint maps it
|
|
266
|
+
// to 400 `invalid_grant`, the client's cue to send the user back through
|
|
267
|
+
// /authorize. A plain Error became 500 `server_error`, which reads as an
|
|
268
|
+
// outage, so an expired 30-day refresh token (or a rotated MCP_AUTH_TOKEN)
|
|
269
|
+
// left the connector failing instead of asking to reconnect.
|
|
270
|
+
private liveCode(client: OAuthClientInformationFull, authorizationCode: string): AuthCodeEntry {
|
|
271
|
+
const entry = this.codes.get(authorizationCode);
|
|
272
|
+
if (!entry || entry.expiresAt < Date.now() || entry.clientId !== client.client_id) {
|
|
273
|
+
throw new InvalidGrantError("invalid or expired authorization code");
|
|
274
|
+
}
|
|
275
|
+
return entry;
|
|
276
|
+
}
|
|
277
|
+
|
|
216
278
|
async challengeForAuthorizationCode(
|
|
217
279
|
client: OAuthClientInformationFull,
|
|
218
280
|
authorizationCode: string,
|
|
219
281
|
): Promise<string> {
|
|
220
|
-
|
|
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;
|
|
282
|
+
return this.liveCode(client, authorizationCode).challenge;
|
|
225
283
|
}
|
|
226
284
|
|
|
227
285
|
async exchangeAuthorizationCode(
|
|
228
286
|
client: OAuthClientInformationFull,
|
|
229
287
|
authorizationCode: string,
|
|
230
288
|
): Promise<OAuthTokens> {
|
|
231
|
-
const entry = this.
|
|
232
|
-
if (!entry || entry.expiresAt < Date.now() || entry.clientId !== client.client_id) {
|
|
233
|
-
throw new Error("invalid or expired authorization code");
|
|
234
|
-
}
|
|
289
|
+
const entry = this.liveCode(client, authorizationCode);
|
|
235
290
|
this.codes.delete(authorizationCode); // one-time use
|
|
236
291
|
return this.issueTokens(client.client_id, entry.scopes, entry.resource);
|
|
237
292
|
}
|
|
@@ -243,10 +298,17 @@ export class WhoopOAuthProvider implements OAuthServerProvider {
|
|
|
243
298
|
): Promise<OAuthTokens> {
|
|
244
299
|
const payload = verifyToken(refreshToken, this.signingSecret);
|
|
245
300
|
if (!payload || payload.typ !== "refresh" || payload.cid !== client.client_id) {
|
|
246
|
-
throw new
|
|
301
|
+
throw new InvalidGrantError("invalid or expired refresh token");
|
|
247
302
|
}
|
|
248
|
-
|
|
249
|
-
|
|
303
|
+
// RFC 6749 §6: a refresh may narrow the scope, never widen it. Taking the
|
|
304
|
+
// requested list as given let any refresh mint a token claiming scopes the
|
|
305
|
+
// user never approved.
|
|
306
|
+
const granted = Array.isArray(payload.scopes) ? (payload.scopes as string[]) : [];
|
|
307
|
+
const requested = scopes?.filter(Boolean);
|
|
308
|
+
if (requested?.some((scope) => !granted.includes(scope))) {
|
|
309
|
+
throw new InvalidScopeError("requested scope exceeds the scope originally granted");
|
|
310
|
+
}
|
|
311
|
+
return this.issueTokens(client.client_id, requested ?? granted, payload.resource as string | undefined);
|
|
250
312
|
}
|
|
251
313
|
|
|
252
314
|
private issueTokens(clientId: string, scopes: string[], resource: string | undefined): OAuthTokens {
|
|
@@ -296,7 +358,9 @@ export class WhoopOAuthProvider implements OAuthServerProvider {
|
|
|
296
358
|
scopes: (payload.scopes as string[]) ?? [],
|
|
297
359
|
expiresAt: payload.exp as number,
|
|
298
360
|
};
|
|
299
|
-
|
|
361
|
+
// canParse: a token must never fail verification with a TypeError (the
|
|
362
|
+
// bearer middleware answers anything but InvalidTokenError with a 500).
|
|
363
|
+
if (typeof payload.resource === "string" && URL.canParse(payload.resource)) info.resource = new URL(payload.resource);
|
|
300
364
|
return info;
|
|
301
365
|
}
|
|
302
366
|
// Throw the SDK's typed error so the bearer middleware returns 401 (a
|
|
@@ -304,74 +368,3 @@ export class WhoopOAuthProvider implements OAuthServerProvider {
|
|
|
304
368
|
throw new InvalidTokenError("invalid or expired access token");
|
|
305
369
|
}
|
|
306
370
|
}
|
|
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,345 @@
|
|
|
1
|
+
// One owner per refresh token (SPEC G8).
|
|
2
|
+
//
|
|
3
|
+
// WHOOP rotates the refresh token on every refresh. If two processes refresh the
|
|
4
|
+
// same login, the second presents a token the first already spent, and the
|
|
5
|
+
// login dies (or WHOOP revokes the whole token family). So exactly one process
|
|
6
|
+
// may refresh: the one holding `<token file>.lock`.
|
|
7
|
+
//
|
|
8
|
+
// The lock is created with O_EXCL and holds { pid, host, nonce, started_at,
|
|
9
|
+
// heartbeat_at }. The owner rewrites heartbeat_at every 30 s. A lock is stale,
|
|
10
|
+
// and may be taken over, when its process is gone (same host) or its heartbeat
|
|
11
|
+
// is older than 90 s.
|
|
12
|
+
//
|
|
13
|
+
// Creating a lock that doesn't exist is atomic (O_EXCL). Every change to an
|
|
14
|
+
// existing lock (replacing a stale one, the owner's heartbeat, the owner's
|
|
15
|
+
// release) is made while holding `<lock>.guard`, a second O_EXCL file held for
|
|
16
|
+
// microseconds. Without it, two processes that both judged a lock stale each
|
|
17
|
+
// delete "the stale lock" (the second deletes the first's brand-new one) and
|
|
18
|
+
// both become the owner. Before each refresh the owner confirms its lock under
|
|
19
|
+
// the guard and stamps a fresh heartbeat (confirm()), so nobody can judge it
|
|
20
|
+
// stale while it spends the refresh token.
|
|
21
|
+
//
|
|
22
|
+
// This only sees processes sharing the file system. A laptop and a Fly machine
|
|
23
|
+
// each have their own file, which is why `totem auth` never leaves a refreshing
|
|
24
|
+
// copy behind when it pushes a login to a deployment.
|
|
25
|
+
|
|
26
|
+
import { closeSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeSync } from "node:fs";
|
|
27
|
+
import { dirname } from "node:path";
|
|
28
|
+
import { hostname } from "node:os";
|
|
29
|
+
import { randomUUID } from "node:crypto";
|
|
30
|
+
import { writeFileAtomic } from "./token_store.js";
|
|
31
|
+
|
|
32
|
+
export interface LockHolder {
|
|
33
|
+
pid: number;
|
|
34
|
+
host: string;
|
|
35
|
+
nonce: string;
|
|
36
|
+
started_at: string;
|
|
37
|
+
heartbeat_at: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface TokenLockOptions {
|
|
41
|
+
path: string;
|
|
42
|
+
/** A heartbeat older than this marks the lock stale. Default 90 s. */
|
|
43
|
+
staleMs?: number;
|
|
44
|
+
/** How often the owner refreshes its heartbeat. Default 30 s. */
|
|
45
|
+
heartbeatMs?: number;
|
|
46
|
+
now?: () => number;
|
|
47
|
+
pid?: number;
|
|
48
|
+
host?: string;
|
|
49
|
+
/** Whether a pid on this host is alive. Default: `process.kill(pid, 0)`. */
|
|
50
|
+
isAlive?: (pid: number) => boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type AcquireResult = { acquired: true } | { acquired: false; holder: LockHolder | null };
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* confirm()'s answer: "held" (ours, heartbeat just stamped), "lost" (another
|
|
57
|
+
* process owns it now), or "busy" (another process is changing the lock this
|
|
58
|
+
* instant, so ownership can't be proven right now).
|
|
59
|
+
*/
|
|
60
|
+
export type LockState = "held" | "lost" | "busy";
|
|
61
|
+
|
|
62
|
+
/** A guard older than this was left by a process that died inside its critical section. */
|
|
63
|
+
const GUARD_STALE_MS = 10_000;
|
|
64
|
+
const GUARD_ATTEMPTS = 6;
|
|
65
|
+
|
|
66
|
+
/** Block this thread for a moment. Guard sections last microseconds, so a few ms is plenty. */
|
|
67
|
+
function sleepSync(ms: number): void {
|
|
68
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function defaultIsAlive(pid: number): boolean {
|
|
72
|
+
try {
|
|
73
|
+
process.kill(pid, 0);
|
|
74
|
+
return true;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
return (error as NodeJS.ErrnoException).code === "EPERM"; // alive, owned by another user
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* An O_EXCL create failed because the file exists. On Windows a file that is
|
|
82
|
+
* being deleted while another process still has it open answers EPERM/EACCES
|
|
83
|
+
* until that handle closes; that is the same "someone else has it" case.
|
|
84
|
+
*/
|
|
85
|
+
function alreadyThere(error: unknown): boolean {
|
|
86
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
87
|
+
if (code === "EEXIST") return true;
|
|
88
|
+
return process.platform === "win32" && (code === "EPERM" || code === "EACCES" || code === "EBUSY");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function parseHolder(text: string): LockHolder | null {
|
|
92
|
+
try {
|
|
93
|
+
const raw = JSON.parse(text) as Partial<LockHolder>;
|
|
94
|
+
if (typeof raw.pid !== "number" || typeof raw.nonce !== "string") return null;
|
|
95
|
+
return {
|
|
96
|
+
pid: raw.pid,
|
|
97
|
+
host: typeof raw.host === "string" ? raw.host : "",
|
|
98
|
+
nonce: raw.nonce,
|
|
99
|
+
started_at: typeof raw.started_at === "string" ? raw.started_at : "",
|
|
100
|
+
heartbeat_at: typeof raw.heartbeat_at === "string" ? raw.heartbeat_at : "",
|
|
101
|
+
};
|
|
102
|
+
} catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export class TokenLock {
|
|
108
|
+
readonly path: string;
|
|
109
|
+
private readonly staleMs: number;
|
|
110
|
+
private readonly heartbeatMs: number;
|
|
111
|
+
private readonly now: () => number;
|
|
112
|
+
private readonly pid: number;
|
|
113
|
+
private readonly host: string;
|
|
114
|
+
private readonly isAlive: (pid: number) => boolean;
|
|
115
|
+
private readonly nonce = randomUUID();
|
|
116
|
+
private startedAt = "";
|
|
117
|
+
private isHeld = false;
|
|
118
|
+
private timer: ReturnType<typeof setInterval> | null = null;
|
|
119
|
+
|
|
120
|
+
constructor(opts: TokenLockOptions) {
|
|
121
|
+
this.path = opts.path;
|
|
122
|
+
this.staleMs = opts.staleMs ?? 90_000;
|
|
123
|
+
this.heartbeatMs = opts.heartbeatMs ?? 30_000;
|
|
124
|
+
this.now = opts.now ?? Date.now;
|
|
125
|
+
this.pid = opts.pid ?? process.pid;
|
|
126
|
+
this.host = opts.host ?? hostname();
|
|
127
|
+
this.isAlive = opts.isAlive ?? defaultIsAlive;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Whether this process believes it owns the lock (see verify()). */
|
|
131
|
+
get held(): boolean {
|
|
132
|
+
return this.isHeld;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Take the lock, or take over a stale one. Never waits for a live owner. */
|
|
136
|
+
tryAcquire(): AcquireResult {
|
|
137
|
+
if (this.isHeld && this.verify()) return { acquired: true };
|
|
138
|
+
mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
139
|
+
// No lock file: O_EXCL makes creating one atomic on its own.
|
|
140
|
+
if (this.create()) return { acquired: true };
|
|
141
|
+
const holder = this.readHolder();
|
|
142
|
+
if (!this.isStale(holder)) return { acquired: false, holder };
|
|
143
|
+
// Stale. Judge it again and replace it while holding the guard, so only one
|
|
144
|
+
// of several processes that saw the same stale lock takes it over.
|
|
145
|
+
const result = this.exclusive((): AcquireResult => {
|
|
146
|
+
const current = this.readHolder();
|
|
147
|
+
if (!this.isStale(current)) return { acquired: false, holder: current };
|
|
148
|
+
try {
|
|
149
|
+
rmSync(this.path);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
152
|
+
}
|
|
153
|
+
return this.create() ? { acquired: true } : { acquired: false, holder: this.readHolder() };
|
|
154
|
+
});
|
|
155
|
+
return result.ran ? result.value : { acquired: false, holder: this.readHolder() };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Re-read the lock file: do we still own it? Updates `held`. */
|
|
159
|
+
verify(): boolean {
|
|
160
|
+
const holder = this.readHolder();
|
|
161
|
+
this.isHeld = holder !== null && holder.nonce === this.nonce;
|
|
162
|
+
return this.isHeld;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Prove we still own the lock and stamp a fresh heartbeat, in one step under
|
|
167
|
+
* the guard. Call it right before spending the refresh token: "held" means no
|
|
168
|
+
* other process has taken the lock over, and none will judge it stale for the
|
|
169
|
+
* next `staleMs`. Throws when the lock can't be written (a disk that would
|
|
170
|
+
* also refuse the rotated token).
|
|
171
|
+
*/
|
|
172
|
+
confirm(): LockState {
|
|
173
|
+
const result = this.exclusive((): LockState => {
|
|
174
|
+
if (!this.verify()) return "lost";
|
|
175
|
+
// No fsync: a heartbeat needn't survive a power cut, and the guard should
|
|
176
|
+
// be held for microseconds, not for two disk flushes.
|
|
177
|
+
writeFileAtomic(this.path, JSON.stringify(this.info()), 0o600, false);
|
|
178
|
+
return "held";
|
|
179
|
+
});
|
|
180
|
+
return result.ran ? result.value : "busy";
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Refresh the heartbeat if we still own the lock. Returns whether we do. */
|
|
184
|
+
heartbeat(): boolean {
|
|
185
|
+
let state: LockState;
|
|
186
|
+
try {
|
|
187
|
+
state = this.confirm();
|
|
188
|
+
} catch {
|
|
189
|
+
// A missed beat is survivable; three in a row make the lock stale.
|
|
190
|
+
return this.isHeld;
|
|
191
|
+
}
|
|
192
|
+
// "busy": another process holds the guard this instant. Skip the beat.
|
|
193
|
+
return state === "busy" ? this.isHeld : state === "held";
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Heartbeat on an unref'd interval while we hold the lock. */
|
|
197
|
+
startHeartbeat(onLost?: () => void): void {
|
|
198
|
+
this.stopHeartbeat();
|
|
199
|
+
this.timer = setInterval(() => {
|
|
200
|
+
if (!this.heartbeat()) {
|
|
201
|
+
this.stopHeartbeat();
|
|
202
|
+
onLost?.();
|
|
203
|
+
}
|
|
204
|
+
}, this.heartbeatMs);
|
|
205
|
+
this.timer.unref?.();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
stopHeartbeat(): void {
|
|
209
|
+
if (this.timer) clearInterval(this.timer);
|
|
210
|
+
this.timer = null;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Stop heartbeating and delete the lock if it is ours. Safe to call twice. */
|
|
214
|
+
release(): void {
|
|
215
|
+
this.stopHeartbeat();
|
|
216
|
+
try {
|
|
217
|
+
// Under the guard, so we can't delete a lock another process is taking
|
|
218
|
+
// over at this instant. If the guard is busy the lock stays behind and
|
|
219
|
+
// goes stale with our pid.
|
|
220
|
+
this.exclusive(() => {
|
|
221
|
+
if (this.verify()) rmSync(this.path, { force: true });
|
|
222
|
+
});
|
|
223
|
+
} catch {
|
|
224
|
+
// best-effort
|
|
225
|
+
}
|
|
226
|
+
this.isHeld = false;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** The current holder as written in the lock file, or null (missing or unreadable). */
|
|
230
|
+
readHolder(): LockHolder | null {
|
|
231
|
+
try {
|
|
232
|
+
return parseHolder(readFileSync(this.path, "utf8"));
|
|
233
|
+
} catch {
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
private isStale(holder: LockHolder | null): boolean {
|
|
239
|
+
const now = this.now();
|
|
240
|
+
if (!holder) {
|
|
241
|
+
// Missing, half-written or garbage: stale once its mtime is old.
|
|
242
|
+
try {
|
|
243
|
+
return now - statSync(this.path).mtimeMs > this.staleMs;
|
|
244
|
+
} catch {
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (holder.host === this.host) {
|
|
249
|
+
// Our own pid with someone else's nonce is a previous incarnation of this
|
|
250
|
+
// process slot (a container's pid 1 after a restart): it can't be alive.
|
|
251
|
+
if (holder.pid === this.pid) return holder.nonce !== this.nonce;
|
|
252
|
+
if (!this.isAlive(holder.pid)) return true;
|
|
253
|
+
}
|
|
254
|
+
const beat = Date.parse(holder.heartbeat_at);
|
|
255
|
+
return !Number.isFinite(beat) || now - beat > this.staleMs;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Create the lock file if there is none (O_EXCL). False when one exists. */
|
|
259
|
+
private create(): boolean {
|
|
260
|
+
let fd: number;
|
|
261
|
+
try {
|
|
262
|
+
fd = openSync(this.path, "wx", 0o600);
|
|
263
|
+
} catch (error) {
|
|
264
|
+
if (alreadyThere(error)) return false;
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
this.startedAt = new Date(this.now()).toISOString();
|
|
269
|
+
writeSync(fd, JSON.stringify(this.info()));
|
|
270
|
+
} finally {
|
|
271
|
+
closeSync(fd);
|
|
272
|
+
}
|
|
273
|
+
this.isHeld = true;
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Run `fn` while holding `<lock>.guard`. `ran: false` when another process
|
|
279
|
+
* kept the guard for the whole (short) wait.
|
|
280
|
+
*
|
|
281
|
+
* A guard can be left behind only by a process that died inside these few
|
|
282
|
+
* microseconds; one older than 10 s is removed. (Two processes racing to
|
|
283
|
+
* remove such a guard could both get in. That takes a crash inside the
|
|
284
|
+
* section and a simultaneous race, and the owner's confirm() before each
|
|
285
|
+
* refresh still catches a lost lock.)
|
|
286
|
+
*/
|
|
287
|
+
private exclusive<T>(fn: () => T): { ran: true; value: T } | { ran: false } {
|
|
288
|
+
const guard = `${this.path}.guard`;
|
|
289
|
+
for (let attempt = 0; attempt < GUARD_ATTEMPTS; attempt++) {
|
|
290
|
+
let fd: number;
|
|
291
|
+
try {
|
|
292
|
+
fd = openSync(guard, "wx", 0o600);
|
|
293
|
+
} catch (error) {
|
|
294
|
+
if (!alreadyThere(error)) throw error;
|
|
295
|
+
let age: number;
|
|
296
|
+
try {
|
|
297
|
+
age = Date.now() - statSync(guard).mtimeMs; // the file's clock, not the injected one
|
|
298
|
+
} catch {
|
|
299
|
+
continue; // released between our open and our stat
|
|
300
|
+
}
|
|
301
|
+
if (age > GUARD_STALE_MS) {
|
|
302
|
+
try { rmSync(guard); } catch { /* another process cleared it */ }
|
|
303
|
+
} else {
|
|
304
|
+
sleepSync(2 + attempt * 2);
|
|
305
|
+
}
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
try {
|
|
309
|
+
try { writeSync(fd, this.nonce); } finally { closeSync(fd); }
|
|
310
|
+
return { ran: true, value: fn() };
|
|
311
|
+
} finally {
|
|
312
|
+
// Remove the guard if it is still ours (it isn't if we stalled past
|
|
313
|
+
// GUARD_STALE_MS and another process cleared it).
|
|
314
|
+
try {
|
|
315
|
+
if (readFileSync(guard, "utf8") === this.nonce) rmSync(guard);
|
|
316
|
+
} catch { /* already gone */ }
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return { ran: false };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
private info(): LockHolder {
|
|
323
|
+
return {
|
|
324
|
+
pid: this.pid,
|
|
325
|
+
host: this.host,
|
|
326
|
+
nonce: this.nonce,
|
|
327
|
+
started_at: this.startedAt || new Date(this.now()).toISOString(),
|
|
328
|
+
heartbeat_at: new Date(this.now()).toISOString(),
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** A second process tried to refresh a login another process owns. */
|
|
334
|
+
export class WhoopTokenOwnedError extends Error {
|
|
335
|
+
constructor(public readonly holder: LockHolder | null, lockPath: string) {
|
|
336
|
+
const who = holder
|
|
337
|
+
? `pid ${holder.pid}${holder.host && holder.host !== hostname() ? ` on ${holder.host}` : ""}`
|
|
338
|
+
: "another process";
|
|
339
|
+
super(
|
|
340
|
+
`WHOOP token owned by ${who} (${lockPath}); this process won't refresh it. ` +
|
|
341
|
+
"Don't run local and remote on one login: give each its own `totem auth`.",
|
|
342
|
+
);
|
|
343
|
+
this.name = "WhoopTokenOwnedError";
|
|
344
|
+
}
|
|
345
|
+
}
|