@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
package/src/cli/setup.ts
ADDED
|
@@ -0,0 +1,1106 @@
|
|
|
1
|
+
// Guided setup flows: `totem cloud` (server-hosted, OAuth, recommended) and
|
|
2
|
+
// `totem local` (stdio on this machine). These are the headline commands.
|
|
3
|
+
//
|
|
4
|
+
// Fly, Railway, and Cloud Run are all fully CLI-automated and tested end-to-end:
|
|
5
|
+
// the flow installs the host CLI if missing, logs you in, deploys, auto-detects
|
|
6
|
+
// the resulting URL, sets PUBLIC_URL, and verifies /health + OAuth are live — no
|
|
7
|
+
// copy-paste. Custom is a printed Docker guide for any other host or your own
|
|
8
|
+
// server. Either way it's one command to a working, Claude-connected deployment.
|
|
9
|
+
import { existsSync, readFileSync, writeFileSync, rmSync, mkdirSync, chmodSync } from "node:fs";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
12
|
+
import { resolve, dirname } from "node:path";
|
|
13
|
+
import {
|
|
14
|
+
c, run, capture, captureAsync, commandExists, genToken, genPassword, copyToClipboard, httpGet,
|
|
15
|
+
prompt, promptHidden, promptYesNo, select, confirmStep, step, closePrompts,
|
|
16
|
+
withSpinner, spin, pause, maskArgs,
|
|
17
|
+
runScript, ensureCli, openUrl,
|
|
18
|
+
} from "./ui.js";
|
|
19
|
+
|
|
20
|
+
// ── .env helpers ────────────────────────────────────────────────────────────
|
|
21
|
+
function envPath(root: string): string {
|
|
22
|
+
return resolve(root, ".env");
|
|
23
|
+
}
|
|
24
|
+
function readEnv(root: string): Record<string, string> {
|
|
25
|
+
const p = envPath(root);
|
|
26
|
+
if (!existsSync(p)) return {};
|
|
27
|
+
const out: Record<string, string> = {};
|
|
28
|
+
for (const line of readFileSync(p, "utf8").split("\n")) {
|
|
29
|
+
const m = line.match(/^([A-Z0-9_]+)=(.*)$/);
|
|
30
|
+
if (m && m[1]) out[m[1]] = m[2] ?? "";
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
function upsertEnv(root: string, updates: Record<string, string>): void {
|
|
35
|
+
const p = envPath(root);
|
|
36
|
+
const lines = existsSync(p) ? readFileSync(p, "utf8").split("\n") : [];
|
|
37
|
+
for (const [k, v] of Object.entries(updates)) {
|
|
38
|
+
const idx = lines.findIndex((l) => l.startsWith(`${k}=`));
|
|
39
|
+
if (idx >= 0) lines[idx] = `${k}=${v}`;
|
|
40
|
+
else lines.push(`${k}=${v}`);
|
|
41
|
+
}
|
|
42
|
+
// 0600 — this file holds the refresh token (and, transiently, the password).
|
|
43
|
+
writeFileSync(p, lines.join("\n"), { mode: 0o600 });
|
|
44
|
+
try { chmodSync(p, 0o600); } catch { /* best-effort */ }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// A user-chosen connector password gates public web/mobile access to the
|
|
48
|
+
// account. Require length + ≥2 character classes and reject obvious choices.
|
|
49
|
+
// (Pressing Enter for the auto-generated 18-char option is always strong.)
|
|
50
|
+
function weakPassword(pw: string): string | null {
|
|
51
|
+
if (pw.length < 16) return "Use at least 16 characters (or press Enter to auto-generate).";
|
|
52
|
+
const classes = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((re) => re.test(pw)).length;
|
|
53
|
+
if (classes < 2) return "Mix at least two of: lower, upper, digits, symbols (or press Enter to auto-generate).";
|
|
54
|
+
if (/^(.)\1+$/.test(pw)) return "That's a single repeated character — pick something stronger.";
|
|
55
|
+
if (/^(password|whoop|123456|qwerty|letmein)/i.test(pw)) return "That's too guessable — pick something stronger.";
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Record of where we deployed, so `auth` can push rotated tokens to the right
|
|
60
|
+
// place later (or know it's a local install with nothing remote to update).
|
|
61
|
+
interface DeployRecord {
|
|
62
|
+
platform: string; // fly | railway | cloudrun | custom | local
|
|
63
|
+
app?: string; // app/project/service name (none for local)
|
|
64
|
+
url?: string;
|
|
65
|
+
region?: string; // Cloud Run needs this to target the service
|
|
66
|
+
project?: string; // Cloud Run GCP project (for logs/status/refresh)
|
|
67
|
+
}
|
|
68
|
+
function writeDeployRecord(root: string, rec: DeployRecord): void {
|
|
69
|
+
writeFileSync(resolve(root, ".totem-deploy.json"), JSON.stringify(rec, null, 2));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ── shared: ensure dependencies are installed (offer to run npm install) ─────
|
|
73
|
+
// A published `npm install -g` already has node_modules; a fresh git checkout
|
|
74
|
+
// that never ran `npm install` does not — without it the build + auth steps
|
|
75
|
+
// would just error out. This keeps the flow zero-setup.
|
|
76
|
+
async function ensureDeps(root: string): Promise<boolean> {
|
|
77
|
+
if (existsSync(resolve(root, "node_modules"))) return true;
|
|
78
|
+
console.log(c.yellow(" Dependencies aren't installed yet."));
|
|
79
|
+
if (!(await promptYesNo("Run `npm install` now?", true))) {
|
|
80
|
+
console.log(c.red(" Can't continue without dependencies."));
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
return (await run("npm", ["install"], { cwd: root })) === 0;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ── shared: ensure we have Whoop tokens (run auth if not) ────────────────────
|
|
87
|
+
async function ensureAuth(root: string): Promise<boolean> {
|
|
88
|
+
const env = readEnv(root);
|
|
89
|
+
if (env.WHOOP_IOS_BEARER_TOKEN && env.WHOOP_COGNITO_REFRESH_TOKEN) {
|
|
90
|
+
const reuse = await promptYesNo("Found existing Whoop tokens in .env. Reuse them?", true);
|
|
91
|
+
if (reuse) return true;
|
|
92
|
+
}
|
|
93
|
+
// Need email + password in .env for the auth (cognito_bootstrap) script.
|
|
94
|
+
if (!env.WHOOP_EMAIL) {
|
|
95
|
+
const email = await promptRequired("Your Whoop account email", {
|
|
96
|
+
validate: (v) => (/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) ? null : "That doesn't look like an email address — try again."),
|
|
97
|
+
});
|
|
98
|
+
upsertEnv(root, { WHOOP_EMAIL: email });
|
|
99
|
+
}
|
|
100
|
+
if (!readEnv(root).WHOOP_PASSWORD) {
|
|
101
|
+
const pw = await promptRequired("Your Whoop account password (stored only in local .env, used once)", { hidden: true });
|
|
102
|
+
upsertEnv(root, { WHOOP_PASSWORD: pw });
|
|
103
|
+
}
|
|
104
|
+
console.log(c.gray("Authenticating with Whoop (you'll get an SMS code if your account has MFA)…"));
|
|
105
|
+
// closePrompts so the auth script owns stdin for its own SMS prompt.
|
|
106
|
+
closePrompts();
|
|
107
|
+
// runScript prefers the compiled dist/ (works in a published install with no
|
|
108
|
+
// tsx), falling back to tsx on source for a dev checkout. TOKENS_ONLY: the
|
|
109
|
+
// guided flow handles the deploy itself, so the auth script must NOT push.
|
|
110
|
+
const code = await runScript(root, "scripts/cognito_bootstrap", [], {
|
|
111
|
+
env: { ...process.env, WHOOP_AUTH_TOKENS_ONLY: "1" },
|
|
112
|
+
});
|
|
113
|
+
if (code !== 0) { console.log(c.red("Auth failed.")); return false; }
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ── prerequisites (guided preflight, consistent across every path) ────────────
|
|
118
|
+
// Each prerequisite is shown: already-satisfied ones are ✓'d and skipped; the
|
|
119
|
+
// rest are guided to completion. The whole list always runs, so you see exactly
|
|
120
|
+
// what was already set up vs. what we just did, then it returns to the flow.
|
|
121
|
+
interface Prereq {
|
|
122
|
+
label: string;
|
|
123
|
+
check: () => boolean | Promise<boolean>;
|
|
124
|
+
ensure: () => Promise<boolean>;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function preflight(prereqs: Prereq[]): Promise<boolean> {
|
|
128
|
+
for (const p of prereqs) {
|
|
129
|
+
if (await p.check()) { console.log(c.green(` ✓ ${p.label}`)); continue; }
|
|
130
|
+
console.log(c.yellow(` • ${p.label} — setting it up`));
|
|
131
|
+
if (!(await p.ensure())) { console.log(c.red(` ✗ ${p.label} — couldn't complete; fix the above + re-run.`)); return false; }
|
|
132
|
+
console.log(c.green(` ✓ ${p.label}`));
|
|
133
|
+
}
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// shared prerequisites ────────────────────────────────────────────────────────
|
|
138
|
+
const nodePrereq: Prereq = {
|
|
139
|
+
label: `Node.js ≥ 24 (have ${process.version})`,
|
|
140
|
+
check: () => Number(process.versions.node.split(".")[0] || "0") >= 24,
|
|
141
|
+
ensure: async () => {
|
|
142
|
+
console.log(c.gray(" Needs Node 24+. Upgrade (https://nodejs.org or `brew upgrade node`) and re-run."));
|
|
143
|
+
return false;
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
function depsPrereq(root: string): Prereq {
|
|
147
|
+
return { label: "npm dependencies", check: () => existsSync(resolve(root, "node_modules")), ensure: () => ensureDeps(root) };
|
|
148
|
+
}
|
|
149
|
+
function buildPrereq(root: string): Prereq {
|
|
150
|
+
return {
|
|
151
|
+
label: "server built (dist/)",
|
|
152
|
+
check: () => existsSync(resolve(root, "dist", "server.js")),
|
|
153
|
+
ensure: async () => {
|
|
154
|
+
const tsc = resolve(root, "node_modules", ".bin", "tsc");
|
|
155
|
+
if (!existsSync(tsc)) { console.log(c.gray(" No TypeScript compiler — run `npm install`, then re-run.")); return false; }
|
|
156
|
+
return (await run(process.execPath, [tsc], { cwd: root })) === 0;
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// host-CLI prerequisite (install on demand via ensureCli) ──────────────────────
|
|
162
|
+
function cliPrereq(label: string, name: string, install: { brewPkg?: string; npmPkg?: string; scriptUrl?: string; manualHint: string }): Prereq {
|
|
163
|
+
return { label, check: () => commandExists(name), ensure: () => ensureCli(name, install) };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const flyPrereqs: Prereq[] = [
|
|
167
|
+
{
|
|
168
|
+
label: "Fly CLI (flyctl)",
|
|
169
|
+
check: () => commandExists("fly") || commandExists("flyctl"),
|
|
170
|
+
ensure: () => ensureCli("flyctl", { brewPkg: "flyctl", scriptUrl: "https://fly.io/install.sh", manualHint: "brew install flyctl (or: curl -L https://fly.io/install.sh | sh)" }),
|
|
171
|
+
},
|
|
172
|
+
{
|
|
173
|
+
label: "logged into Fly",
|
|
174
|
+
check: () => capture(commandExists("fly") ? "fly" : "flyctl", ["auth", "whoami"]).code === 0,
|
|
175
|
+
ensure: async () => (await run(commandExists("fly") ? "fly" : "flyctl", ["auth", "login"])) === 0,
|
|
176
|
+
},
|
|
177
|
+
];
|
|
178
|
+
|
|
179
|
+
const railwayPrereqs: Prereq[] = [
|
|
180
|
+
cliPrereq("Railway CLI", "railway", { npmPkg: "@railway/cli", brewPkg: "railway", manualHint: "npm i -g @railway/cli (or: brew install railway)" }),
|
|
181
|
+
{
|
|
182
|
+
label: "logged into Railway",
|
|
183
|
+
check: () => capture("railway", ["whoami"]).code === 0,
|
|
184
|
+
ensure: async () => (await run("railway", ["login"])) === 0,
|
|
185
|
+
},
|
|
186
|
+
];
|
|
187
|
+
|
|
188
|
+
// gcloud needs more than a CLI: install → auth → account → project → billing.
|
|
189
|
+
// The CLI install + "at least one account" are pure prerequisites (below). The
|
|
190
|
+
// *which account / which project* decisions are choices the user must own, so
|
|
191
|
+
// they live in chooseGcloudTarget() and are offered on every run — never silently
|
|
192
|
+
// inheriting whatever happens to be active.
|
|
193
|
+
const gcloudPrereqs: Prereq[] = [
|
|
194
|
+
{
|
|
195
|
+
label: "gcloud SDK installed",
|
|
196
|
+
check: () => commandExists("gcloud"),
|
|
197
|
+
ensure: async () => {
|
|
198
|
+
if (commandExists("brew") && await confirmStep("Install the gcloud SDK via Homebrew?", { cmd: "brew install --cask google-cloud-sdk", detail: "downloads + installs Google's CLI (~hundreds of MB)", defaultYes: true })) {
|
|
199
|
+
await run("brew", ["install", "--cask", "google-cloud-sdk"]);
|
|
200
|
+
}
|
|
201
|
+
if (!commandExists("gcloud")) {
|
|
202
|
+
if (await confirmStep("Install gcloud with Google's official script instead?", { cmd: "curl https://sdk.cloud.google.com | bash", detail: "runs a remote install script (follow its prompts)", defaultYes: true })) {
|
|
203
|
+
await run("sh", ["-c", "curl https://sdk.cloud.google.com | bash"]);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (!commandExists("gcloud")) {
|
|
207
|
+
console.log(c.yellow(" gcloud still isn't on PATH — open a new terminal and re-run `totem cloud`."));
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
return true;
|
|
211
|
+
},
|
|
212
|
+
},
|
|
213
|
+
{
|
|
214
|
+
label: "authenticated with Google",
|
|
215
|
+
check: () => capture("gcloud", ["auth", "list", "--filter=status:ACTIVE", "--format=value(account)"]).stdout.trim().length > 0,
|
|
216
|
+
ensure: async () => {
|
|
217
|
+
if (!(await confirmStep("Sign into Google in your browser?", { cmd: "gcloud auth login", defaultYes: true }))) return false;
|
|
218
|
+
return (await run("gcloud", ["auth", "login"])) === 0;
|
|
219
|
+
},
|
|
220
|
+
},
|
|
221
|
+
];
|
|
222
|
+
|
|
223
|
+
// Pick the Google account to deploy under (every run). gcloud can hold several
|
|
224
|
+
// authenticated accounts at once, so switching between EXISTING ones needs no
|
|
225
|
+
// logout — just `gcloud config set account`. Adding a new one runs `gcloud auth
|
|
226
|
+
// login` (the browser opens right here in the flow). Loops so a decline returns
|
|
227
|
+
// to the menu; verifies the active account before returning.
|
|
228
|
+
async function chooseGcloudAccount(): Promise<boolean> {
|
|
229
|
+
for (;;) {
|
|
230
|
+
const all = (await withSpinner("listing Google accounts", () => captureAsync("gcloud", ["auth", "list", "--format=value(account)"]))).stdout.trim().split("\n").filter(Boolean);
|
|
231
|
+
const active = (await captureAsync("gcloud", ["auth", "list", "--filter=status:ACTIVE", "--format=value(account)"])).stdout.trim();
|
|
232
|
+
const choices = all.map((a) => ({ label: a, hint: a === active ? "active" : undefined }));
|
|
233
|
+
choices.push({ label: "Sign into a different Google account…", hint: undefined });
|
|
234
|
+
const idx = await select("Which Google account should own this deployment?", choices, { defaultIndex: Math.max(0, all.indexOf(active)) });
|
|
235
|
+
if (idx === all.length) {
|
|
236
|
+
// Add an account — the browser sign-in happens right here, in-process.
|
|
237
|
+
if (!(await confirmStep("Open a browser to sign into another Google account?", { cmd: "gcloud auth login", detail: "the browser sign-in happens right here in this flow", defaultYes: true }))) continue;
|
|
238
|
+
if ((await run("gcloud", ["auth", "login"])) !== 0) {
|
|
239
|
+
console.log(c.red(" ✗ Google sign-in didn't complete."));
|
|
240
|
+
if (!(await promptYesNo(" Try again?", true))) return false;
|
|
241
|
+
}
|
|
242
|
+
continue; // re-list — the new account is now active; confirm it on the next pass
|
|
243
|
+
}
|
|
244
|
+
const picked = all[idx]!;
|
|
245
|
+
if (picked !== active) {
|
|
246
|
+
const set = await withSpinner(`switching to ${picked}`, () => captureAsync("gcloud", ["config", "set", "account", picked]));
|
|
247
|
+
if (set.code !== 0) { console.log(c.red(` ✗ couldn't switch to ${picked}: ${lastLine(set)}`)); continue; }
|
|
248
|
+
}
|
|
249
|
+
console.log(c.green(` ✓ deploying as ${picked}`));
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Pick (or create) the GCP project. Marks the current one; creating a brand-new
|
|
255
|
+
// project is gated behind an explicit confirm (it's a real, billable resource).
|
|
256
|
+
async function chooseGcloudProject(): Promise<boolean> {
|
|
257
|
+
const current = (await captureAsync("gcloud", ["config", "get-value", "project"])).stdout.trim().replace(/^\(unset\)$/, "");
|
|
258
|
+
const projects = (await withSpinner("listing GCP projects", () => captureAsync("gcloud", ["projects", "list", "--format=value(projectId)"]))).stdout.trim().split("\n").filter(Boolean);
|
|
259
|
+
const choices = projects.map((p) => ({ label: p, hint: p === current ? "current" : undefined }));
|
|
260
|
+
choices.push({ label: "Create a new project…", hint: undefined });
|
|
261
|
+
const idx = await select("Which GCP project should host the deployment?", choices, { defaultIndex: Math.max(0, projects.indexOf(current)) });
|
|
262
|
+
let project: string;
|
|
263
|
+
if (idx === projects.length) {
|
|
264
|
+
let fresh = `totem-${genToken().slice(0, 6)}`;
|
|
265
|
+
project = (await prompt("New project ID (lowercase, 6-30 chars, globally unique)", fresh)).trim() || fresh;
|
|
266
|
+
// Retry with a new ID if creation fails (taken/invalid ID), surfacing the error.
|
|
267
|
+
for (;;) {
|
|
268
|
+
if (!(await confirmStep(`Create a new Google Cloud project '${project}'?`, { cmd: `gcloud projects create ${project}`, detail: "creates a real GCP project on your account", defaultYes: true }))) return false;
|
|
269
|
+
if ((await run("gcloud", ["projects", "create", project])) === 0) break;
|
|
270
|
+
console.log(c.red(" ✗ project creation failed — the error is shown above (usually the ID is taken or malformed)."));
|
|
271
|
+
if (!(await promptYesNo(" Try a different project ID?", true))) return false;
|
|
272
|
+
fresh = `totem-${genToken().slice(0, 6)}`;
|
|
273
|
+
project = (await prompt("New project ID (lowercase, 6-30 chars, globally unique)", fresh)).trim() || fresh;
|
|
274
|
+
}
|
|
275
|
+
} else {
|
|
276
|
+
project = projects[idx]!;
|
|
277
|
+
}
|
|
278
|
+
return (await withSpinner(`selecting ${project}`, () => captureAsync("gcloud", ["config", "set", "project", project]))).code === 0;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Cloud Run requires billing on the chosen project. If you already have a billing
|
|
282
|
+
// account, we LINK it from the CLI right here, in-process. Only *creating* a
|
|
283
|
+
// billing account (adding a payment method) needs the web console — gcloud has no
|
|
284
|
+
// CLI for that anywhere — so that single step is handed off, with the page auto-opened.
|
|
285
|
+
async function ensureGcloudBilling(): Promise<boolean> {
|
|
286
|
+
const p = (await captureAsync("gcloud", ["config", "get-value", "project"])).stdout.trim();
|
|
287
|
+
const b = await withSpinner("checking billing", () => captureAsync("gcloud", ["billing", "projects", "describe", p, "--format=value(billingEnabled)"]));
|
|
288
|
+
if (b.code === 0 && /true/i.test(b.stdout)) { console.log(c.green(" ✓ billing enabled")); return true; }
|
|
289
|
+
|
|
290
|
+
// Link an existing OPEN billing account directly via the CLI (in-process).
|
|
291
|
+
const accts = (await withSpinner("listing your billing accounts", () => captureAsync("gcloud", ["billing", "accounts", "list", "--filter=open=true", "--format=value(name)"]))).stdout.trim().split("\n").filter(Boolean);
|
|
292
|
+
if (accts.length > 0) {
|
|
293
|
+
const choices = accts.map((a) => ({ label: a }));
|
|
294
|
+
choices.push({ label: "None of these — set one up in the console" });
|
|
295
|
+
const idx = await select("Link which billing account to this project?", choices);
|
|
296
|
+
if (idx < accts.length) {
|
|
297
|
+
const acct = accts[idx]!;
|
|
298
|
+
if (await confirmStep(`Link billing account ${acct} to ${p}?`, { cmd: `gcloud billing projects link ${p} --billing-account=${acct}`, detail: "enables billing on the project — done right here, no console", defaultYes: true })) {
|
|
299
|
+
const link = await withSpinner("linking billing", () => captureAsync("gcloud", ["billing", "projects", "link", p, "--billing-account", acct]));
|
|
300
|
+
if (link.code === 0) { console.log(c.green(" ✓ billing linked")); return true; }
|
|
301
|
+
console.log(c.red(` ✗ couldn't link billing: ${lastLine(link)}`));
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// No usable billing account → the console is the only place to add a payment method.
|
|
307
|
+
const url = `https://console.cloud.google.com/billing/linkedaccount?project=${p}`;
|
|
308
|
+
console.log(c.yellow(" Add a payment method in the console (creating a billing account has no CLI)."));
|
|
309
|
+
console.log(c.gray(` Opening: ${url}`));
|
|
310
|
+
openUrl(url);
|
|
311
|
+
await promptYesNo(" Press Enter once billing is enabled", true);
|
|
312
|
+
return true;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// The full Cloud Run target picker: account → project → billing. Always offered.
|
|
316
|
+
async function chooseGcloudTarget(): Promise<boolean> {
|
|
317
|
+
console.log(c.gray(" Choose the account + project to deploy into:"));
|
|
318
|
+
if (!(await chooseGcloudAccount())) return false;
|
|
319
|
+
if (!(await chooseGcloudProject())) return false;
|
|
320
|
+
return ensureGcloudBilling();
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Fly target picker: confirm the logged-in account or switch to another. The
|
|
324
|
+
// switch (logout + login) runs entirely in-process — `fly auth login` opens the
|
|
325
|
+
// browser right here. Loops on decline; verifies + shows the account afterward.
|
|
326
|
+
async function chooseFlyAccount(): Promise<boolean> {
|
|
327
|
+
const fly = commandExists("fly") ? "fly" : "flyctl";
|
|
328
|
+
for (;;) {
|
|
329
|
+
const who = (await withSpinner("checking Fly account", () => captureAsync(fly, ["auth", "whoami"]))).stdout.trim();
|
|
330
|
+
const idx = await select("Deploy under which Fly account?", [
|
|
331
|
+
{ label: who || "(current account)", hint: "current" },
|
|
332
|
+
{ label: "Switch to a different account…" },
|
|
333
|
+
]);
|
|
334
|
+
if (idx === 0) { console.log(c.green(` ✓ deploying as ${who || "(current account)"}`)); return true; }
|
|
335
|
+
if (!(await confirmStep("Log out of Fly and sign in as a different account?", { cmd: `${fly} auth logout && ${fly} auth login`, detail: "the browser login happens right here in this flow", defaultYes: true }))) continue;
|
|
336
|
+
await run(fly, ["auth", "logout"]);
|
|
337
|
+
if ((await run(fly, ["auth", "login"])) !== 0) {
|
|
338
|
+
console.log(c.red(" ✗ Fly login didn't complete."));
|
|
339
|
+
if (!(await promptYesNo(" Try again?", true))) return false;
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
const now = (await withSpinner("confirming Fly account", () => captureAsync(fly, ["auth", "whoami"]))).stdout.trim();
|
|
343
|
+
console.log(c.green(` ✓ now signed in to Fly as ${now || "(unknown)"}`));
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// Railway target picker: confirm the logged-in account or switch to another.
|
|
349
|
+
// `railway login` runs in-process (browser / pairing happens right here). Loops
|
|
350
|
+
// on decline; verifies + shows the account afterward.
|
|
351
|
+
async function chooseRailwayAccount(): Promise<boolean> {
|
|
352
|
+
for (;;) {
|
|
353
|
+
const who = (await withSpinner("checking Railway account", () => captureAsync("railway", ["whoami"]))).stdout.trim().replace(/\s+/g, " ");
|
|
354
|
+
const idx = await select("Deploy under which Railway account?", [
|
|
355
|
+
{ label: who || "(current account)", hint: "current" },
|
|
356
|
+
{ label: "Switch to a different account…" },
|
|
357
|
+
]);
|
|
358
|
+
if (idx === 0) { console.log(c.green(` ✓ deploying as ${who || "(current account)"}`)); return true; }
|
|
359
|
+
if (!(await confirmStep("Log out of Railway and log in as a different account?", { cmd: "railway logout && railway login", detail: "the login happens right here in this flow", defaultYes: true }))) continue;
|
|
360
|
+
await run("railway", ["logout"]);
|
|
361
|
+
if ((await run("railway", ["login"])) !== 0) {
|
|
362
|
+
console.log(c.red(" ✗ Railway login didn't complete."));
|
|
363
|
+
if (!(await promptYesNo(" Try again?", true))) return false;
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
const now = (await withSpinner("confirming Railway account", () => captureAsync("railway", ["whoami"]))).stdout.trim().replace(/\s+/g, " ");
|
|
367
|
+
console.log(c.green(` ✓ now signed in to Railway as ${now || "(unknown)"}`));
|
|
368
|
+
return true;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// ── LOCAL flow ───────────────────────────────────────────────────────────────
|
|
373
|
+
// ── local AI-client wiring (registry-driven) ────────────────────────────────
|
|
374
|
+
// Every stdio client takes the SAME launch entry — `{ command: <node>, args:
|
|
375
|
+
// [dist/server.js] }` — because the server self-loads the repo's .env. So adding
|
|
376
|
+
// a client is just a config path + a JSON key (or its own CLI); the entry never
|
|
377
|
+
// changes, only WHERE it's written.
|
|
378
|
+
interface LocalClient {
|
|
379
|
+
label: string;
|
|
380
|
+
hint: string;
|
|
381
|
+
/** Wire this client; true if we wrote/ran it, false if the user must finish it. */
|
|
382
|
+
wire: (node: string, serverJs: string) => Promise<boolean>;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// Merge { [key]: { [name]: entry } } into a JSON config without clobbering the
|
|
386
|
+
// user's other servers/settings. Idempotent.
|
|
387
|
+
function mergeJsonConfig(cfgPath: string, key: string, name: string, entry: Record<string, unknown>): void {
|
|
388
|
+
let merged: Record<string, unknown> = {};
|
|
389
|
+
if (existsSync(cfgPath)) {
|
|
390
|
+
try { merged = JSON.parse(readFileSync(cfgPath, "utf8")) as Record<string, unknown>; } catch { merged = {}; }
|
|
391
|
+
}
|
|
392
|
+
const bucket = (merged[key] as Record<string, unknown> | undefined) ?? {};
|
|
393
|
+
merged[key] = { ...bucket, [name]: entry };
|
|
394
|
+
mkdirSync(dirname(cfgPath), { recursive: true });
|
|
395
|
+
writeFileSync(cfgPath, JSON.stringify(merged, null, 2));
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// A client wired by merging a JSON config file (most of them). `key` is the
|
|
399
|
+
// top-level object: "mcpServers" for Claude Desktop/Cursor/Gemini/Windsurf,
|
|
400
|
+
// "servers" (with a "type":"stdio" field) for VS Code.
|
|
401
|
+
function jsonClient(label: string, hint: string, relPath: string, key: "mcpServers" | "servers", restart: string): LocalClient {
|
|
402
|
+
return {
|
|
403
|
+
label, hint,
|
|
404
|
+
wire: async (node, serverJs) => {
|
|
405
|
+
const home = process.env.HOME ?? "~";
|
|
406
|
+
const cfgPath = resolve(home, relPath);
|
|
407
|
+
const entry: Record<string, unknown> = key === "servers"
|
|
408
|
+
? { type: "stdio", command: node, args: [serverJs] }
|
|
409
|
+
: { command: node, args: [serverJs] };
|
|
410
|
+
if (!(await promptYesNo(`Write the 'whoop' server into ${cfgPath}?`, true))) {
|
|
411
|
+
console.log(c.gray(" Skipped — paste this into that file yourself:"));
|
|
412
|
+
console.log(JSON.stringify({ [key]: { whoop: entry } }, null, 2));
|
|
413
|
+
return false;
|
|
414
|
+
}
|
|
415
|
+
mergeJsonConfig(cfgPath, key, "whoop", entry);
|
|
416
|
+
console.log(c.green(` ✓ ${label} updated`) + c.gray(` ${cfgPath}`));
|
|
417
|
+
console.log(c.yellow(` → ${restart}`));
|
|
418
|
+
return true;
|
|
419
|
+
},
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// Claude Code: wired by its own CLI.
|
|
424
|
+
const claudeCodeClient: LocalClient = {
|
|
425
|
+
label: "Claude Code", hint: "run the one-line `claude mcp add`",
|
|
426
|
+
wire: async (node, serverJs) => {
|
|
427
|
+
const manual = `claude mcp add whoop ${node} ${serverJs}`;
|
|
428
|
+
if (commandExists("claude")) {
|
|
429
|
+
if (await promptYesNo("Run `claude mcp add whoop …` now?", true)) {
|
|
430
|
+
if ((await run("claude", ["mcp", "add", "whoop", node, serverJs])) === 0) {
|
|
431
|
+
console.log(c.green(" ✓ added to Claude Code"));
|
|
432
|
+
return true;
|
|
433
|
+
}
|
|
434
|
+
console.log(c.yellow(" That didn't work — run it yourself:"));
|
|
435
|
+
console.log(` ${manual}`);
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
console.log(c.gray(" Run it when ready:"));
|
|
439
|
+
console.log(` ${manual}`);
|
|
440
|
+
return false;
|
|
441
|
+
}
|
|
442
|
+
console.log(c.gray(" The `claude` CLI isn't on PATH. Install Claude Code, then run:"));
|
|
443
|
+
console.log(` ${manual}`);
|
|
444
|
+
return false;
|
|
445
|
+
},
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
// Codex uses TOML — print the exact block (no fragile TOML merge/parse).
|
|
449
|
+
const codexClient: LocalClient = {
|
|
450
|
+
label: "Codex CLI", hint: "show the config.toml block to add",
|
|
451
|
+
wire: async (node, serverJs) => {
|
|
452
|
+
const home = process.env.HOME ?? "~";
|
|
453
|
+
console.log("");
|
|
454
|
+
console.log(c.gray(` Add this to ${resolve(home, ".codex/config.toml")} and restart Codex:`));
|
|
455
|
+
console.log("");
|
|
456
|
+
console.log(` [mcp_servers.whoop]`);
|
|
457
|
+
console.log(` command = ${JSON.stringify(node)}`);
|
|
458
|
+
console.log(` args = ${JSON.stringify([serverJs])}`);
|
|
459
|
+
console.log("");
|
|
460
|
+
return false;
|
|
461
|
+
},
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
// Catch-all: print the universal stdio block for any other MCP client.
|
|
465
|
+
const showConfigClient: LocalClient = {
|
|
466
|
+
label: "Other / show the config", hint: "any MCP client — print the block",
|
|
467
|
+
wire: async (node, serverJs) => {
|
|
468
|
+
console.log("");
|
|
469
|
+
console.log(c.gray(' Most MCP clients accept this (key is usually "mcpServers"; VS Code uses "servers" + "type":"stdio"):'));
|
|
470
|
+
console.log(JSON.stringify({ mcpServers: { whoop: { command: node, args: [serverJs] } } }, null, 2));
|
|
471
|
+
return false;
|
|
472
|
+
},
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
const LOCAL_CLIENTS: LocalClient[] = [
|
|
476
|
+
jsonClient("Claude Desktop", "write the config automatically", "Library/Application Support/Claude/claude_desktop_config.json", "mcpServers", "Quit and reopen Claude Desktop."),
|
|
477
|
+
claudeCodeClient,
|
|
478
|
+
jsonClient("Cursor", "write ~/.cursor/mcp.json", ".cursor/mcp.json", "mcpServers", "Reload Cursor (Settings → Tools & MCP)."),
|
|
479
|
+
jsonClient("VS Code (Copilot)", "write the user mcp.json", "Library/Application Support/Code/User/mcp.json", "servers", "Reload VS Code; start the server in the MCP view."),
|
|
480
|
+
jsonClient("Gemini CLI", "write ~/.gemini/settings.json", ".gemini/settings.json", "mcpServers", "Restart the gemini CLI."),
|
|
481
|
+
codexClient,
|
|
482
|
+
jsonClient("Windsurf", "write ~/.codeium/windsurf/mcp_config.json", ".codeium/windsurf/mcp_config.json", "mcpServers", "Reload Windsurf (Cascade → refresh MCP)."),
|
|
483
|
+
showConfigClient,
|
|
484
|
+
];
|
|
485
|
+
|
|
486
|
+
export async function runLocalSetup(root: string): Promise<number> {
|
|
487
|
+
console.log(c.bold("\ntotem · local setup") + c.gray(" — run the MCP on this machine over stdio\n"));
|
|
488
|
+
const TOTAL = 3;
|
|
489
|
+
const serverJs = resolve(root, "dist", "server.js");
|
|
490
|
+
|
|
491
|
+
step(1, TOTAL, "Prerequisites");
|
|
492
|
+
if (!(await preflight([nodePrereq, depsPrereq(root), buildPrereq(root)]))) return 1;
|
|
493
|
+
|
|
494
|
+
step(2, TOTAL, "Whoop authentication");
|
|
495
|
+
if (!(await ensureAuth(root))) return 1;
|
|
496
|
+
console.log(c.green(" ✓ tokens in .env"));
|
|
497
|
+
// Record this as a local install (overriding any stale cloud record) so
|
|
498
|
+
// `auth` knows the tokens just go to .env — no remote to push to.
|
|
499
|
+
writeDeployRecord(root, { platform: "local" });
|
|
500
|
+
|
|
501
|
+
step(3, TOTAL, "Wire into your AI client");
|
|
502
|
+
const idx = await select("Which client?", LOCAL_CLIENTS.map((cl) => ({ label: cl.label, hint: cl.hint })));
|
|
503
|
+
const wired = await LOCAL_CLIENTS[idx]!.wire(process.execPath, serverJs);
|
|
504
|
+
|
|
505
|
+
if (wired) {
|
|
506
|
+
console.log(c.green("\n✓ Local setup complete.") + c.gray(" Restart the client, then ask: \"how am I doing today on whoop?\"\n"));
|
|
507
|
+
} else {
|
|
508
|
+
console.log(c.yellow("\n→ Almost done.") + c.gray(" Finish the step above + restart your client, then ask: \"how am I doing today on whoop?\"\n"));
|
|
509
|
+
}
|
|
510
|
+
closePrompts();
|
|
511
|
+
return 0;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// ── CLOUD flow ─────────────────────────────────────────────────────────────
|
|
515
|
+
interface DeployCtx {
|
|
516
|
+
root: string;
|
|
517
|
+
env: Record<string, string>; // everything except PUBLIC_URL
|
|
518
|
+
appName: string;
|
|
519
|
+
password: string;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
export async function runCloudSetup(root: string): Promise<number> {
|
|
523
|
+
console.log(c.bold("\ntotem · cloud setup") + c.gray(" — deploy a server + connect it to Claude (web, desktop, mobile)\n"));
|
|
524
|
+
const TOTAL = 6;
|
|
525
|
+
if (!(await preflight([nodePrereq, depsPrereq(root)]))) return 1;
|
|
526
|
+
|
|
527
|
+
step(1, TOTAL, "Whoop authentication");
|
|
528
|
+
if (!(await ensureAuth(root))) return 1;
|
|
529
|
+
const env = readEnv(root);
|
|
530
|
+
console.log(c.green(" ✓ tokens ready"));
|
|
531
|
+
|
|
532
|
+
step(2, TOTAL, "Choose a host");
|
|
533
|
+
const platformIdx = await select("Where should the server run?", [
|
|
534
|
+
{ label: "Fly.io", hint: "fast-booting micro-VMs on a global edge network" },
|
|
535
|
+
{ label: "Railway", hint: "polished PaaS, instant deploys + a clean dashboard" },
|
|
536
|
+
{ label: "Google Cloud Run", hint: "Google Cloud's serverless containers, one instance kept warm" },
|
|
537
|
+
{ label: "Custom / own server", hint: "bring your own Docker host — a VPS, Render, a home server" },
|
|
538
|
+
]);
|
|
539
|
+
const platforms = ["fly", "railway", "cloudrun", "custom"] as const;
|
|
540
|
+
const platform = platforms[platformIdx]!;
|
|
541
|
+
|
|
542
|
+
// Per-host prerequisites (install the CLI, log in) — guided, auto-skipping
|
|
543
|
+
// whatever you already have, BEFORE we generate secrets or deploy.
|
|
544
|
+
const hostPrereqs = platform === "fly" ? flyPrereqs
|
|
545
|
+
: platform === "railway" ? railwayPrereqs
|
|
546
|
+
: platform === "cloudrun" ? gcloudPrereqs
|
|
547
|
+
: [];
|
|
548
|
+
if (hostPrereqs.length && !(await preflight(hostPrereqs))) return 1;
|
|
549
|
+
|
|
550
|
+
// Account / project selection — always offered, never silently inheriting
|
|
551
|
+
// whatever account or GCP project happens to be active. (Custom self-host has
|
|
552
|
+
// no account concept.)
|
|
553
|
+
const targetOk = platform === "fly" ? await chooseFlyAccount()
|
|
554
|
+
: platform === "railway" ? await chooseRailwayAccount()
|
|
555
|
+
: platform === "cloudrun" ? await chooseGcloudTarget()
|
|
556
|
+
: true;
|
|
557
|
+
if (!targetOk) { console.log(c.red(" Couldn't set the deploy target.")); closePrompts(); return 1; }
|
|
558
|
+
|
|
559
|
+
step(3, TOTAL, "Generate secrets");
|
|
560
|
+
const mcpToken = genToken();
|
|
561
|
+
console.log(` MCP_AUTH_TOKEN: ${c.gray(mcpToken.slice(0, 12) + "… (generated)")}`);
|
|
562
|
+
console.log(c.gray(" Connector password — you'll paste this into Claude once when adding the server."));
|
|
563
|
+
console.log(c.gray(" Press Enter to auto-generate a secure 18-char one, or type your own (min 16)."));
|
|
564
|
+
const useGenerated = (pw: string): string => {
|
|
565
|
+
const copied = copyToClipboard(pw);
|
|
566
|
+
console.log(` ${c.green("✓")} generated: ${c.bold(pw)}${copied ? c.green(" ✓ copied to clipboard") : c.gray(" (copy it now)")}`);
|
|
567
|
+
if (copied) console.log(c.gray(" (clear your clipboard after pasting — clipboard-history apps retain it)"));
|
|
568
|
+
return pw;
|
|
569
|
+
};
|
|
570
|
+
let password = await prompt("Password (Enter = auto-generate)");
|
|
571
|
+
if (password === "") {
|
|
572
|
+
password = useGenerated(genPassword(18));
|
|
573
|
+
} else {
|
|
574
|
+
let why = weakPassword(password);
|
|
575
|
+
while (why) {
|
|
576
|
+
console.log(c.red(` ${why}`));
|
|
577
|
+
password = await prompt("Password (Enter = auto-generate)");
|
|
578
|
+
if (password === "") { password = useGenerated(genPassword(18)); break; }
|
|
579
|
+
why = weakPassword(password);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
const baseEnv: Record<string, string> = {
|
|
584
|
+
WHOOP_EMAIL: env.WHOOP_EMAIL ?? "",
|
|
585
|
+
WHOOP_IOS_BEARER_TOKEN: env.WHOOP_IOS_BEARER_TOKEN ?? "",
|
|
586
|
+
WHOOP_COGNITO_REFRESH_TOKEN: env.WHOOP_COGNITO_REFRESH_TOKEN ?? "",
|
|
587
|
+
MCP_TRANSPORT: "http",
|
|
588
|
+
MCP_AUTH_TOKEN: mcpToken,
|
|
589
|
+
AUTH_PASSWORD: password,
|
|
590
|
+
WHOOP_TOKEN_STORE: "memory",
|
|
591
|
+
};
|
|
592
|
+
if (env.WHOOP_USER_ID) baseEnv.WHOOP_USER_ID = env.WHOOP_USER_ID;
|
|
593
|
+
|
|
594
|
+
step(4, TOTAL, `Deploy to ${platform}`);
|
|
595
|
+
const defaultName = `totem-${genToken().slice(0, 6)}`;
|
|
596
|
+
let appName = "totem";
|
|
597
|
+
if (platform !== "custom") {
|
|
598
|
+
console.log(c.gray(" App name is optional — press Enter to use the suggested one in [brackets],"));
|
|
599
|
+
console.log(c.gray(" or type your own (must be globally unique on the host)."));
|
|
600
|
+
appName = await prompt("App name (Enter = use suggested)", defaultName);
|
|
601
|
+
}
|
|
602
|
+
const ctx: DeployCtx = { root, env: baseEnv, appName, password };
|
|
603
|
+
|
|
604
|
+
let url: string | null = null;
|
|
605
|
+
if (platform === "fly") url = await deployFly(ctx);
|
|
606
|
+
else if (platform === "railway") url = await deployRailway(ctx);
|
|
607
|
+
else if (platform === "cloudrun") url = await deployCloudRun(ctx);
|
|
608
|
+
else url = await deployCustom(ctx);
|
|
609
|
+
|
|
610
|
+
if (!url) {
|
|
611
|
+
console.log(c.yellow("\nDeploy didn't complete automatically. Follow the steps above, then re-run `totem cloud` or set PUBLIC_URL + redeploy manually."));
|
|
612
|
+
closePrompts();
|
|
613
|
+
return 1;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
step(5, TOTAL, "Verify the server + OAuth are live");
|
|
617
|
+
const ok = await verifyDeployment(url);
|
|
618
|
+
if (!ok) {
|
|
619
|
+
console.log(c.yellow(" Couldn't confirm the OAuth endpoints yet (the host may still be starting). Give it a minute, then run `totem ping`."));
|
|
620
|
+
}
|
|
621
|
+
// Use ctx.appName, not the local appName: a Fly name conflict may have changed
|
|
622
|
+
// it during deploy, and `auth` must push to the app that was actually used.
|
|
623
|
+
const extra: Partial<DeployRecord> = {};
|
|
624
|
+
if (platform === "cloudrun") {
|
|
625
|
+
extra.region = "us-west1";
|
|
626
|
+
const proj = capture("gcloud", ["config", "get-value", "project"]).stdout.trim();
|
|
627
|
+
if (proj) extra.project = proj;
|
|
628
|
+
}
|
|
629
|
+
writeDeployRecord(root, { platform, app: ctx.appName, url, ...extra });
|
|
630
|
+
|
|
631
|
+
step(6, TOTAL, "Connect your AI");
|
|
632
|
+
printConnectInstructions(url, password, mcpToken);
|
|
633
|
+
closePrompts();
|
|
634
|
+
return 0;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// ── verification ─────────────────────────────────────────────────────────────
|
|
638
|
+
async function verifyDeployment(baseUrl: string): Promise<boolean> {
|
|
639
|
+
const root = baseUrl.replace(/\/(mcp)?$/, "");
|
|
640
|
+
// Poll fast: a short per-attempt timeout means a not-yet-propagated DNS / cold
|
|
641
|
+
// start fails in ~3s instead of hanging the full 12s default, and a tight 1.5s
|
|
642
|
+
// interval detects readiness within ~1.5s of the host coming up. (Previously a
|
|
643
|
+
// 12s timeout × 3s sleep × 10 made this feel like ~3 minutes.)
|
|
644
|
+
const start = Date.now();
|
|
645
|
+
const deadline = start + 90_000;
|
|
646
|
+
let healthy = false;
|
|
647
|
+
// Live elapsed counter so a slow DNS-propagation / cold-start wait visibly ticks.
|
|
648
|
+
const s = spin(() => `waiting for ${root} (DNS + first boot) — ${Math.floor((Date.now() - start) / 1000)}s`);
|
|
649
|
+
while (Date.now() < deadline) {
|
|
650
|
+
const health = await httpGet(`${root}/health`, 3000);
|
|
651
|
+
if (health.status === 200) { healthy = true; break; }
|
|
652
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
653
|
+
}
|
|
654
|
+
s.stop();
|
|
655
|
+
console.log(` /health: ${healthy ? c.green("200 ✓") : c.red("timeout")}`);
|
|
656
|
+
const prm = await withSpinner("checking OAuth metadata", () => httpGet(`${root}/.well-known/oauth-protected-resource/mcp`, 5000));
|
|
657
|
+
const prmOk = prm.status === 200 && prm.body.includes("/mcp");
|
|
658
|
+
console.log(` OAuth metadata: ${prmOk ? c.green("✓") : c.red("not found")}`);
|
|
659
|
+
// Prove the auth gate is live: an unauthenticated /mcp must be REJECTED (401),
|
|
660
|
+
// not served. Catches a regression that left the endpoint open to the public.
|
|
661
|
+
const gate = await withSpinner("checking /mcp is auth-gated", () => httpGet(`${root}/mcp`, 5000));
|
|
662
|
+
const gated = gate.status === 401;
|
|
663
|
+
console.log(` /mcp auth gate: ${gated ? c.green("401 ✓ (rejects unauthenticated)") : c.red(`${gate.status || "no response"} — expected 401`)}`);
|
|
664
|
+
return healthy && prmOk && gated;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
function printConnectInstructions(url: string, password: string, mcpToken: string): void {
|
|
668
|
+
const mcpUrl = url.replace(/\/$/, "") + "/mcp";
|
|
669
|
+
// Header-auth clients (CLIs / editors) hit the server directly with the static
|
|
670
|
+
// bearer token; OAuth clients (claude.ai, ChatGPT) use the password gate.
|
|
671
|
+
const headerBlock = JSON.stringify(
|
|
672
|
+
{ mcpServers: { whoop: { url: mcpUrl, headers: { Authorization: `Bearer ${mcpToken}` } } } },
|
|
673
|
+
null, 2,
|
|
674
|
+
).split("\n").map((l) => " " + l).join("\n");
|
|
675
|
+
console.log("");
|
|
676
|
+
console.log(c.bold(" ── Connect your AI ──────────────────────────────────────────"));
|
|
677
|
+
console.log("");
|
|
678
|
+
console.log(c.bold(" claude.ai") + c.gray(" (web · desktop · mobile — syncs across your devices)"));
|
|
679
|
+
console.log(` Settings → Connectors → ${c.bold("Add custom connector")}`);
|
|
680
|
+
console.log(` URL: ${c.brand(mcpUrl)} Password: ${c.brand(password)}`);
|
|
681
|
+
console.log("");
|
|
682
|
+
console.log(c.bold(" ChatGPT") + c.gray(" (desktop)"));
|
|
683
|
+
console.log(` Settings → Connectors → ${c.bold("Add")} · URL: ${c.brand(mcpUrl)} Password: ${c.brand(password)}`);
|
|
684
|
+
console.log("");
|
|
685
|
+
console.log(c.bold(" Claude Code") + c.gray(" (remote)"));
|
|
686
|
+
console.log(` ${c.gray("$")} claude mcp add --transport http whoop ${mcpUrl} --header "Authorization: Bearer ${mcpToken}"`);
|
|
687
|
+
console.log("");
|
|
688
|
+
console.log(c.bold(" Cursor · Windsurf · any HTTP MCP client") + c.gray(" — config block:"));
|
|
689
|
+
console.log(headerBlock);
|
|
690
|
+
console.log("");
|
|
691
|
+
// Best-effort: open the connectors page in the browser (cross-platform).
|
|
692
|
+
openUrl("https://claude.ai/settings/connectors");
|
|
693
|
+
console.log(c.gray(" (opened the claude.ai connectors page in your browser)"));
|
|
694
|
+
console.log(c.green("\n✓ Cloud setup complete.\n"));
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// ── platform adapters ────────────────────────────────────────────────────────
|
|
698
|
+
|
|
699
|
+
function setSummary(env: Record<string, string>): void {
|
|
700
|
+
console.log(c.gray(" env to set: " + Object.keys(env).join(", ")));
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
// ── shared failure handling ──────────────────────────────────────────────────
|
|
704
|
+
// The last meaningful line of a captured (spinner-wrapped) command's output —
|
|
705
|
+
// so when a step that DIDN'T stream live fails, we can still show WHY.
|
|
706
|
+
function lastLine(r: { stdout: string; stderr: string }): string {
|
|
707
|
+
const lines = (r.stderr + "\n" + r.stdout).split("\n").map((l) => l.trim()).filter(Boolean);
|
|
708
|
+
return lines.length ? lines[lines.length - 1]! : "unknown error";
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// Run an inherited-stdio action (its error is already printed on screen by the
|
|
712
|
+
// tool) and, on failure, let the user retry it or give up. Loops until success
|
|
713
|
+
// or the user declines. Returns true once it succeeds.
|
|
714
|
+
async function runWithRetry(desc: string, action: () => Promise<number>): Promise<boolean> {
|
|
715
|
+
for (;;) {
|
|
716
|
+
console.log(c.gray(` ${desc}…`));
|
|
717
|
+
if ((await action()) === 0) return true;
|
|
718
|
+
console.log(c.red(" ✗ that failed — the error is shown above."));
|
|
719
|
+
if (!(await promptYesNo(" Retry it?", true))) return false;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// Ask for a public URL, re-asking (with a clear reason) on empty or malformed
|
|
724
|
+
// input instead of bailing the whole flow. Accepts a bare domain (prepends
|
|
725
|
+
// https://) and strips trailing slashes. Ctrl-C is the only way out.
|
|
726
|
+
async function promptUrl(message: string): Promise<string> {
|
|
727
|
+
const tty = Boolean(process.stdin.isTTY);
|
|
728
|
+
for (;;) {
|
|
729
|
+
let url = (await prompt(message)).trim();
|
|
730
|
+
if (url) {
|
|
731
|
+
if (!/^https?:\/\//i.test(url)) url = "https://" + url; // accept a bare domain
|
|
732
|
+
if (/^https?:\/\/[^/.\s]+\.[^/\s]+/.test(url)) return url.replace(/\/+$/, "");
|
|
733
|
+
console.log(c.red(` '${url}' isn't a valid URL (e.g. https://whoop.example.com) — try again.`));
|
|
734
|
+
} else {
|
|
735
|
+
console.log(c.red(" A URL is required — paste it, or press Ctrl-C to cancel."));
|
|
736
|
+
}
|
|
737
|
+
// No interactive terminal (piped/EOF) → "" forever; don't spin, just stop.
|
|
738
|
+
if (!tty) { console.log(c.red(" (no terminal to re-ask on — stopping.)")); process.exit(1); }
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// Ask for a required free-text value, re-asking (with a reason) on empty or
|
|
743
|
+
// invalid input instead of bailing the flow. Optional validator returns an error
|
|
744
|
+
// string to show + re-ask, or null when the value is good. Ctrl-C is the way out.
|
|
745
|
+
async function promptRequired(message: string, opts: { validate?: (v: string) => string | null; hidden?: boolean } = {}): Promise<string> {
|
|
746
|
+
const tty = Boolean(process.stdin.isTTY);
|
|
747
|
+
for (;;) {
|
|
748
|
+
const v = (await (opts.hidden ? promptHidden(message) : prompt(message))).trim();
|
|
749
|
+
if (v) {
|
|
750
|
+
const err = opts.validate ? opts.validate(v) : null;
|
|
751
|
+
if (!err) return v;
|
|
752
|
+
console.log(c.red(` ${err}`));
|
|
753
|
+
} else {
|
|
754
|
+
console.log(c.red(" Required — enter a value, or press Ctrl-C to cancel."));
|
|
755
|
+
}
|
|
756
|
+
if (!tty) { console.log(c.red(" (no terminal to re-ask on — stopping.)")); process.exit(1); }
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// FLY — deploys as fast-booting micro-VMs via flyctl.
|
|
761
|
+
|
|
762
|
+
// Create the Fly app, retrying with a new name when the chosen one is taken by
|
|
763
|
+
// ANOTHER account (Fly app names are globally unique). If you already own an app
|
|
764
|
+
// by that name, reuse it. Mutates ctx.appName to whatever name actually worked.
|
|
765
|
+
async function createFlyApp(fly: string, ctx: DeployCtx): Promise<boolean> {
|
|
766
|
+
if (!(await confirmStep(`Create Fly app '${ctx.appName}'?`, { cmd: `fly apps create ${ctx.appName}`, detail: "reserves the name + URL on your Fly account", defaultYes: true }))) return false;
|
|
767
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
768
|
+
const create = await withSpinner(`creating ${ctx.appName}`, () => captureAsync(fly, ["apps", "create", ctx.appName, "--json"]));
|
|
769
|
+
if (create.code === 0) { console.log(c.green(` ✓ created ${ctx.appName}`)); return true; }
|
|
770
|
+
// Already on YOUR account? (re-running cloud, or a half-finished prior attempt) → reuse it.
|
|
771
|
+
const mine = await withSpinner("checking your Fly apps", () => captureAsync(fly, ["apps", "list"]));
|
|
772
|
+
if (new RegExp(`(^|\\s)${ctx.appName}(\\s|$)`, "m").test(mine.stdout)) {
|
|
773
|
+
console.log(c.gray(` '${ctx.appName}' already exists on your account — reusing it.`));
|
|
774
|
+
return true;
|
|
775
|
+
}
|
|
776
|
+
// Taken by someone else (or another error): SHOW it, then retry with a new name.
|
|
777
|
+
console.log(c.red(` ✗ couldn't create '${ctx.appName}': ${lastLine(create)}`));
|
|
778
|
+
console.log(c.yellow(" Fly app names are globally unique, so that one's unavailable — pick another."));
|
|
779
|
+
const fresh = `totem-${genToken().slice(0, 6)}`;
|
|
780
|
+
ctx.appName = (await prompt("New app name (Enter = unique suggestion)", fresh)).trim() || fresh;
|
|
781
|
+
}
|
|
782
|
+
console.log(c.red(" Too many name attempts — aborting the Fly deploy."));
|
|
783
|
+
return false;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
async function deployFly(ctx: DeployCtx): Promise<string | null> {
|
|
787
|
+
const fly = commandExists("fly") ? "fly" : "flyctl";
|
|
788
|
+
|
|
789
|
+
if (!(await createFlyApp(fly, ctx))) return null;
|
|
790
|
+
const url = `https://${ctx.appName}.fly.dev`;
|
|
791
|
+
const env = { ...ctx.env, PUBLIC_URL: url };
|
|
792
|
+
|
|
793
|
+
// Minimal fly.toml so `fly deploy` is non-interactive (builds the Dockerfile).
|
|
794
|
+
writeFileSync(resolve(ctx.root, "fly.toml"), [
|
|
795
|
+
`app = "${ctx.appName}"`,
|
|
796
|
+
`primary_region = "sjc"`,
|
|
797
|
+
``,
|
|
798
|
+
`[build]`,
|
|
799
|
+
``,
|
|
800
|
+
`[http_service]`,
|
|
801
|
+
` internal_port = 3000`,
|
|
802
|
+
` force_https = true`,
|
|
803
|
+
` # Keep one machine warm so the connector never cold-starts — the first`,
|
|
804
|
+
` # request after an auto-stop would otherwise fail while the VM boots (~10s).`,
|
|
805
|
+
` auto_stop_machines = "suspend"`,
|
|
806
|
+
` auto_start_machines = true`,
|
|
807
|
+
` min_machines_running = 1`,
|
|
808
|
+
``,
|
|
809
|
+
].join("\n"));
|
|
810
|
+
// Set secrets (staged; applied on deploy) — surface the error if it fails.
|
|
811
|
+
// `secrets import` reads KEY=val from stdin, keeping the token + password
|
|
812
|
+
// values off the argv (which any local user could read via `ps`/`/proc`).
|
|
813
|
+
const secretLines = Object.entries(env).map(([k, v]) => `${k}=${v}`).join("\n") + "\n";
|
|
814
|
+
const stage = await withSpinner("staging secrets", () => captureAsync(fly, ["secrets", "import", "--stage", "--app", ctx.appName], { cwd: ctx.root, input: secretLines }));
|
|
815
|
+
if (stage.code !== 0) {
|
|
816
|
+
console.log(c.yellow(` staging secrets failed (${lastLine(stage)}) — applying directly`));
|
|
817
|
+
const direct = await withSpinner("setting secrets", () => captureAsync(fly, ["secrets", "import", "--app", ctx.appName], { cwd: ctx.root, input: secretLines }));
|
|
818
|
+
if (direct.code !== 0) console.log(c.red(` ✗ couldn't set secrets: ${lastLine(direct)}`));
|
|
819
|
+
}
|
|
820
|
+
// Build + deploy — error visible (inherited stdio) + retry-on-failure.
|
|
821
|
+
if (!(await confirmStep("Build + deploy to Fly now?", { cmd: `fly deploy --app ${ctx.appName}`, detail: "builds the Dockerfile and starts a billable machine (~1-2 min)", defaultYes: true }))) return null;
|
|
822
|
+
if (!(await runWithRetry(`deploying ${ctx.appName} (builds the Dockerfile, ~1-2 min)`, () => run(fly, ["deploy", "--app", ctx.appName, "--ha=false"], { cwd: ctx.root })))) return null;
|
|
823
|
+
return url;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// Shared "assisted" deploy used by Railway + Cloud Run: install/login the host
|
|
827
|
+
// CLI, run its deploy commands (each retryable), auto-detect the deployed URL
|
|
828
|
+
// (falling back to a paste only if detection fails), then set PUBLIC_URL for OAuth.
|
|
829
|
+
async function assistedDeploy(opts: {
|
|
830
|
+
cliName: string;
|
|
831
|
+
install: { brewPkg?: string; npmPkg?: string; scriptUrl?: string; manualHint: string };
|
|
832
|
+
loginCheck: () => boolean;
|
|
833
|
+
loginCmd: () => Promise<number>;
|
|
834
|
+
steps: Array<{
|
|
835
|
+
desc: string;
|
|
836
|
+
cmd?: [string, string[]];
|
|
837
|
+
run?: () => Promise<boolean>;
|
|
838
|
+
retries?: number;
|
|
839
|
+
// Sensitive steps (IAM, API enablement, billable deploys) gate behind a
|
|
840
|
+
// confirm. `skippable` steps continue when declined (e.g. an IAM grant that
|
|
841
|
+
// may already be in place); non-skippable ones abort the whole deploy.
|
|
842
|
+
confirm?: { summary: string; detail?: string; cmd?: string; defaultYes?: boolean; skippable?: boolean };
|
|
843
|
+
}>;
|
|
844
|
+
getUrl?: () => Promise<string | null>;
|
|
845
|
+
setPublicUrlCmds: (url: string) => Array<[string, string[]]>;
|
|
846
|
+
ctx: DeployCtx;
|
|
847
|
+
}): Promise<string | null> {
|
|
848
|
+
if (!commandExists(opts.cliName)) {
|
|
849
|
+
if (!(await ensureCli(opts.cliName, opts.install))) return null;
|
|
850
|
+
}
|
|
851
|
+
if (!opts.loginCheck()) {
|
|
852
|
+
console.log(c.gray(` Logging into ${opts.cliName}…`));
|
|
853
|
+
if (await opts.loginCmd() !== 0) return null;
|
|
854
|
+
}
|
|
855
|
+
setSummary(opts.ctx.env);
|
|
856
|
+
for (const s of opts.steps) {
|
|
857
|
+
if (s.confirm) {
|
|
858
|
+
const proceed = await confirmStep(s.confirm.summary, s.confirm);
|
|
859
|
+
if (!proceed) {
|
|
860
|
+
if (s.confirm.skippable) { console.log(c.gray(` ↷ skipped: ${s.desc}`)); continue; }
|
|
861
|
+
console.log(c.yellow(" Cancelled — this step is required, stopping here.")); return null;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
console.log(c.gray(` → ${s.desc}`));
|
|
865
|
+
const tries = (s.retries ?? 0) + 1;
|
|
866
|
+
let ok = false;
|
|
867
|
+
for (let i = 0; i < tries && !ok; i++) {
|
|
868
|
+
if (i > 0) { console.log(c.yellow(` API hiccup — retry ${i}/${s.retries}`)); await pause(2500, "backing off before retry"); }
|
|
869
|
+
if (s.run) ok = await s.run();
|
|
870
|
+
else { console.log(c.gray(` $ ${s.cmd![0]} ${maskArgs(s.cmd![1])}`)); ok = (await run(s.cmd![0], s.cmd![1], { cwd: opts.ctx.root })) === 0; }
|
|
871
|
+
}
|
|
872
|
+
// Auto-retries (above) exhausted and still failing: surface it + let the user
|
|
873
|
+
// retry as many times as they like, skip it, or abort. The error is already
|
|
874
|
+
// on screen (inherited stdio).
|
|
875
|
+
while (!ok) {
|
|
876
|
+
console.log(c.red(` ✗ step failed: ${s.desc} — the error is shown above.`));
|
|
877
|
+
const choice = await select("How do you want to handle it?", [
|
|
878
|
+
{ label: "Retry this step" },
|
|
879
|
+
{ label: "Skip it and continue", hint: "you'll fix it manually" },
|
|
880
|
+
{ label: "Abort the deploy" },
|
|
881
|
+
]);
|
|
882
|
+
if (choice === 0) {
|
|
883
|
+
if (s.run) ok = await s.run();
|
|
884
|
+
else { console.log(c.gray(` $ ${s.cmd![0]} ${maskArgs(s.cmd![1])}`)); ok = (await run(s.cmd![0], s.cmd![1], { cwd: opts.ctx.root })) === 0; }
|
|
885
|
+
} else if (choice === 1) { console.log(c.gray(` ↷ skipped: ${s.desc}`)); break; }
|
|
886
|
+
else { return null; }
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
// Auto-detect the deployed URL (the deploy just printed it); only fall back to
|
|
890
|
+
// asking the user to paste if detection failed.
|
|
891
|
+
const detected = opts.getUrl ? await opts.getUrl() : null;
|
|
892
|
+
let url: string;
|
|
893
|
+
if (detected) {
|
|
894
|
+
url = detected.replace(/\/+$/, "");
|
|
895
|
+
console.log(c.green(` ✓ detected URL: ${url}`));
|
|
896
|
+
} else {
|
|
897
|
+
url = await promptUrl("Paste your deployment's public URL (e.g. https://your-app.up.railway.app)");
|
|
898
|
+
}
|
|
899
|
+
// OAuth's issuer must equal the real URL, which we only know now — so set
|
|
900
|
+
// PUBLIC_URL and redeploy automatically (run() inherits stdio → the user sees
|
|
901
|
+
// progress) rather than asking them to run a command in a second terminal.
|
|
902
|
+
if (!(await confirmStep("Set PUBLIC_URL and redeploy so OAuth works?", { detail: `points the server's OAuth issuer at ${url} (required for web/mobile connectors)`, defaultYes: true }))) {
|
|
903
|
+
console.log(c.yellow(` Skipped. OAuth won't work until you set PUBLIC_URL=${url} and redeploy yourself.`));
|
|
904
|
+
return url;
|
|
905
|
+
}
|
|
906
|
+
console.log(c.gray(" Setting PUBLIC_URL + redeploying so OAuth works…"));
|
|
907
|
+
for (const [cmd, args] of opts.setPublicUrlCmds(url)) {
|
|
908
|
+
console.log(c.gray(` $ ${cmd} ${args.join(" ")}`));
|
|
909
|
+
let ok = false;
|
|
910
|
+
for (let i = 0; i < 4 && !ok; i++) {
|
|
911
|
+
if (i > 0) { console.log(c.yellow(` API hiccup — retry ${i}/3`)); await pause(2500, "backing off before retry"); }
|
|
912
|
+
ok = (await run(cmd, args, { cwd: opts.ctx.root })) === 0;
|
|
913
|
+
}
|
|
914
|
+
while (!ok) {
|
|
915
|
+
console.log(c.red(" ✗ that command failed — the error is shown above."));
|
|
916
|
+
const choice = await select("How do you want to handle it?", [
|
|
917
|
+
{ label: "Retry it" },
|
|
918
|
+
{ label: "Skip and continue", hint: "OAuth won't work until you set PUBLIC_URL yourself" },
|
|
919
|
+
{ label: "Abort" },
|
|
920
|
+
]);
|
|
921
|
+
if (choice === 0) ok = (await run(cmd, args, { cwd: opts.ctx.root })) === 0;
|
|
922
|
+
else if (choice === 1) break;
|
|
923
|
+
else return null;
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
return url;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
// Railway's GraphQL API (backboard.railway.com) intermittently times out, and a
|
|
930
|
+
// timed-out `init` can still create the project server-side. So: try init, and if
|
|
931
|
+
// it fails, check whether the project got created and LINK to it instead of
|
|
932
|
+
// re-running init (which would pile up duplicate projects). Retries the flaky API.
|
|
933
|
+
async function railwayHasProject(appName: string): Promise<boolean> {
|
|
934
|
+
for (let i = 0; i < 3; i++) {
|
|
935
|
+
const r = await withSpinner("checking Railway for the project", () => captureAsync("railway", ["list"]));
|
|
936
|
+
if (r.code === 0) return r.stdout.includes(appName);
|
|
937
|
+
}
|
|
938
|
+
return false;
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
async function railwayInitOrLink(appName: string, root: string): Promise<boolean> {
|
|
942
|
+
for (let attempt = 1; attempt <= 4; attempt++) {
|
|
943
|
+
if (attempt > 1) { console.log(c.yellow(` Railway API hiccup — retry ${attempt - 1}/3`)); await pause(2500, "backing off (Railway's API is flaky)"); }
|
|
944
|
+
console.log(c.gray(` $ railway init --name ${appName}`));
|
|
945
|
+
if ((await run("railway", ["init", "--name", appName], { cwd: root })) === 0) return true;
|
|
946
|
+
// init's response may have timed out AFTER creating the project — link to it.
|
|
947
|
+
if (await railwayHasProject(appName)) {
|
|
948
|
+
console.log(c.gray(" (init's response timed out, but the project exists — linking to it)"));
|
|
949
|
+
console.log(c.gray(` $ railway link --project ${appName}`));
|
|
950
|
+
if ((await run("railway", ["link", "--project", appName], { cwd: root })) === 0) return true;
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
console.log(c.red(" Railway's API (backboard.railway.com) kept timing out. Give it a minute and re-run."));
|
|
954
|
+
return false;
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
// RAILWAY — CLI-automatable; resilient to Railway's flaky GraphQL API.
|
|
958
|
+
async function deployRailway(ctx: DeployCtx): Promise<string | null> {
|
|
959
|
+
// Railway rejects `--set KEY=` (empty value), and PUBLIC_URL isn't known until
|
|
960
|
+
// `domain` runs — so set the non-empty vars now, PUBLIC_URL in the 2nd pass.
|
|
961
|
+
const varArgs: string[] = ["variables"];
|
|
962
|
+
for (const [k, v] of Object.entries(ctx.env)) {
|
|
963
|
+
if (v === "") continue;
|
|
964
|
+
varArgs.push("--set", `${k}=${v}`);
|
|
965
|
+
}
|
|
966
|
+
return assistedDeploy({
|
|
967
|
+
cliName: "railway",
|
|
968
|
+
install: { npmPkg: "@railway/cli", brewPkg: "railway", manualHint: "npm i -g @railway/cli (or: brew install railway)" },
|
|
969
|
+
loginCheck: () => capture("railway", ["whoami"]).code === 0,
|
|
970
|
+
loginCmd: () => run("railway", ["login"]),
|
|
971
|
+
steps: [
|
|
972
|
+
// init creates a PROJECT (not a service); `up` creates the service, so it
|
|
973
|
+
// runs first (deploys env-less + crashes once, then variables redeploys it
|
|
974
|
+
// healthy). init is special — a timeout may have still created it, so we
|
|
975
|
+
// link rather than re-init; the rest retry the flaky API.
|
|
976
|
+
{
|
|
977
|
+
desc: "create the project",
|
|
978
|
+
run: () => railwayInitOrLink(ctx.appName, ctx.root),
|
|
979
|
+
confirm: { summary: `Create a new Railway project '${ctx.appName}'?`, detail: "a new project on your Railway account", defaultYes: true },
|
|
980
|
+
},
|
|
981
|
+
{
|
|
982
|
+
desc: "deploy (creates the service + builds the Dockerfile)",
|
|
983
|
+
cmd: ["railway", ["up", "--detach"]],
|
|
984
|
+
retries: 3,
|
|
985
|
+
confirm: { summary: "Deploy to Railway now?", detail: "creates a service + starts a build on your Railway account", defaultYes: true },
|
|
986
|
+
},
|
|
987
|
+
{ desc: "set environment variables (redeploys with them)", cmd: ["railway", varArgs], retries: 3 },
|
|
988
|
+
],
|
|
989
|
+
getUrl: async () => {
|
|
990
|
+
// `railway domain` prints "🚀 https://…up.railway.app" — capture + parse it
|
|
991
|
+
// instead of asking the user to paste what we just printed.
|
|
992
|
+
for (let i = 0; i < 4; i++) {
|
|
993
|
+
if (i > 0) { console.log(c.yellow(` API hiccup — retry ${i}/3`)); await pause(2500, "backing off before retry"); }
|
|
994
|
+
const r = await withSpinner("fetching the public domain (railway domain)", () => captureAsync("railway", ["domain"], { cwd: ctx.root }));
|
|
995
|
+
const m = `${r.stdout}\n${r.stderr}`.match(/https?:\/\/[a-z0-9.-]+\.up\.railway\.app/i);
|
|
996
|
+
if (m) return m[0];
|
|
997
|
+
}
|
|
998
|
+
return null;
|
|
999
|
+
},
|
|
1000
|
+
setPublicUrlCmds: (url) => [
|
|
1001
|
+
["railway", ["variables", "--set", `PUBLIC_URL=${url}`]],
|
|
1002
|
+
["railway", ["up", "--detach"]],
|
|
1003
|
+
],
|
|
1004
|
+
ctx,
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
// GOOGLE CLOUD RUN — gcloud, builds from source. Best-effort.
|
|
1009
|
+
async function deployCloudRun(ctx: DeployCtx): Promise<string | null> {
|
|
1010
|
+
// Env vars go in a temp YAML file (--env-vars-file), NOT --set-env-vars: values
|
|
1011
|
+
// include an email (with `@`) and a random password, so any inline delimiter can
|
|
1012
|
+
// collide (the `^@^` form broke on the email's `@`). The file lives in the OS
|
|
1013
|
+
// temp dir — never the `--source` upload dir — and is deleted after. PUBLIC_URL
|
|
1014
|
+
// is set in the 2nd pass once the deployed URL is known.
|
|
1015
|
+
const envYaml = Object.entries(ctx.env)
|
|
1016
|
+
.filter(([, v]) => v !== "")
|
|
1017
|
+
.map(([k, v]) => `${k}: ${JSON.stringify(v)}`)
|
|
1018
|
+
.join("\n") + "\n";
|
|
1019
|
+
const envFile = resolve(tmpdir(), `totem-env-${randomUUID()}.yaml`);
|
|
1020
|
+
writeFileSync(envFile, envYaml, { mode: 0o600 });
|
|
1021
|
+
try {
|
|
1022
|
+
return await assistedDeploy({
|
|
1023
|
+
cliName: "gcloud",
|
|
1024
|
+
install: { manualHint: "install the gcloud SDK: https://cloud.google.com/sdk/docs/install" },
|
|
1025
|
+
loginCheck: () => capture("gcloud", ["config", "get-value", "project"]).stdout.trim().length > 0,
|
|
1026
|
+
loginCmd: async () => {
|
|
1027
|
+
const a = await run("gcloud", ["auth", "login"]);
|
|
1028
|
+
if (a !== 0) return a;
|
|
1029
|
+
console.log(c.gray(" Set your project: gcloud config set project <PROJECT_ID>"));
|
|
1030
|
+
await promptYesNo("Project set?", true);
|
|
1031
|
+
return 0;
|
|
1032
|
+
},
|
|
1033
|
+
steps: [
|
|
1034
|
+
{
|
|
1035
|
+
desc: "enable required APIs (run, cloudbuild, artifactregistry)",
|
|
1036
|
+
cmd: ["gcloud", ["services", "enable", "run.googleapis.com", "cloudbuild.googleapis.com", "artifactregistry.googleapis.com"]],
|
|
1037
|
+
confirm: { summary: "Enable the Cloud Run / Cloud Build / Artifact Registry APIs?", detail: "turns these APIs on for the selected project (one-time, idempotent)", cmd: "gcloud services enable run / cloudbuild / artifactregistry", defaultYes: true, skippable: true },
|
|
1038
|
+
},
|
|
1039
|
+
{
|
|
1040
|
+
// gcloud run deploy --source builds via the project's COMPUTE default
|
|
1041
|
+
// service account, which on new projects lacks build permissions
|
|
1042
|
+
// (PERMISSION_DENIED resolving the source). Grant the builder role.
|
|
1043
|
+
desc: "grant Cloud Build access to the default service account",
|
|
1044
|
+
cmd: ["sh", ["-c", 'P="$(gcloud config get-value project 2>/dev/null)"; N="$(gcloud projects describe "$P" --format=\'value(projectNumber)\' 2>/dev/null)"; gcloud projects add-iam-policy-binding "$P" --member="serviceAccount:${N}-compute@developer.gserviceaccount.com" --role=roles/cloudbuild.builds.builder --condition=None']],
|
|
1045
|
+
confirm: { summary: "Grant the Cloud Build builder role to the compute service account?", detail: "modifies project IAM — needed for `--source` builds. Skip if you've already granted it.", cmd: "gcloud projects add-iam-policy-binding … --role=roles/cloudbuild.builds.builder", defaultYes: true, skippable: true },
|
|
1046
|
+
},
|
|
1047
|
+
{
|
|
1048
|
+
desc: "deploy from source (Cloud Build builds the Dockerfile)",
|
|
1049
|
+
cmd: ["gcloud", [
|
|
1050
|
+
"run", "deploy", ctx.appName,
|
|
1051
|
+
"--source", ".",
|
|
1052
|
+
"--region", "us-west1",
|
|
1053
|
+
"--allow-unauthenticated",
|
|
1054
|
+
"--port", "3000",
|
|
1055
|
+
"--min-instances", "1",
|
|
1056
|
+
"--env-vars-file", envFile,
|
|
1057
|
+
"--quiet",
|
|
1058
|
+
]],
|
|
1059
|
+
confirm: { summary: `Build + deploy '${ctx.appName}' to Cloud Run (us-west1)?`, detail: "uploads source, runs Cloud Build, and creates a public service (may incur charges)", cmd: `gcloud run deploy ${ctx.appName} --source . --region us-west1`, defaultYes: true },
|
|
1060
|
+
},
|
|
1061
|
+
],
|
|
1062
|
+
getUrl: async () => {
|
|
1063
|
+
// gcloud knows the service URL — fetch it instead of asking the user.
|
|
1064
|
+
const r = await withSpinner("fetching the Cloud Run service URL", () => captureAsync("gcloud", ["run", "services", "describe", ctx.appName, "--region", "us-west1", "--format=value(status.url)"]));
|
|
1065
|
+
const url = r.stdout.trim();
|
|
1066
|
+
return /^https?:\/\//.test(url) ? url : null;
|
|
1067
|
+
},
|
|
1068
|
+
setPublicUrlCmds: (url) => [
|
|
1069
|
+
["gcloud", ["run", "services", "update", ctx.appName, "--region", "us-west1", "--update-env-vars", `PUBLIC_URL=${url}`, "--quiet"]],
|
|
1070
|
+
],
|
|
1071
|
+
ctx,
|
|
1072
|
+
});
|
|
1073
|
+
} finally {
|
|
1074
|
+
try { rmSync(envFile); } catch { /* best-effort */ }
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
// CUSTOM — run the container yourself on any Docker host. Writes a complete,
|
|
1079
|
+
// ready-to-run env file (so the real secret values are usable, not truncated on
|
|
1080
|
+
// screen) + prints the exact docker commands.
|
|
1081
|
+
async function deployCustom(ctx: DeployCtx): Promise<string | null> {
|
|
1082
|
+
// All settings — including the full tokens + generated password — go into an
|
|
1083
|
+
// env file (chmod 600) instead of being printed (truncated + leaked) on screen.
|
|
1084
|
+
const envFile = resolve(ctx.root, ".env.deploy");
|
|
1085
|
+
const body =
|
|
1086
|
+
Object.entries(ctx.env).map(([k, v]) => `${k}=${v}`).join("\n") +
|
|
1087
|
+
"\nPUBLIC_URL=https://CHANGE-ME-to-your-public-https-address\n";
|
|
1088
|
+
writeFileSync(envFile, body, { mode: 0o600 });
|
|
1089
|
+
|
|
1090
|
+
console.log("");
|
|
1091
|
+
console.log(` ${c.bold(c.white("Self-host it on any Docker host"))} ${c.gray("— a VPS, Render, your own box, whatever.")}`);
|
|
1092
|
+
console.log("");
|
|
1093
|
+
console.log(` ${c.violet("1")} ${c.white("Build the image")} ${c.gray("— the repo already has a Dockerfile:")}`);
|
|
1094
|
+
console.log(` ${c.cyan("docker build -t totem .")}`);
|
|
1095
|
+
console.log("");
|
|
1096
|
+
console.log(` ${c.violet("2")} ${c.white("Your full config")} ${c.gray("(tokens + the generated password) was written to:")}`);
|
|
1097
|
+
console.log(` ${c.brand(envFile)} ${c.gray("(chmod 600 — keep it private)")}`);
|
|
1098
|
+
console.log(` ${c.gray("Open it and set")} ${c.bold(c.white("PUBLIC_URL"))} ${c.gray("to the")} ${c.white("https:// address your server will live at")}`);
|
|
1099
|
+
console.log(` ${c.gray("— you need a public domain/hostname with HTTPS. That same URL is what you paste below.")}`);
|
|
1100
|
+
console.log("");
|
|
1101
|
+
console.log(` ${c.violet("3")} ${c.white("Run it")} ${c.gray("(serves on port 3000):")}`);
|
|
1102
|
+
console.log(` ${c.cyan(`docker run -d --restart unless-stopped -p 3000:3000 --env-file ${envFile} totem`)}`);
|
|
1103
|
+
console.log(` ${c.gray("then put it behind HTTPS at that domain (a reverse proxy, Cloudflare Tunnel, your host's TLS, …).")}`);
|
|
1104
|
+
console.log("");
|
|
1105
|
+
return promptUrl("Once it's reachable, paste that public URL (the PUBLIC_URL you set)");
|
|
1106
|
+
}
|