@builtbyfriends/bwf 0.0.0-stage → 1.9.1
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/AGENTS_TEMPLATE.md +4 -0
- package/LICENSE +22 -0
- package/README.md +48 -2
- package/dist/account-cmd-Cj0I2_bJ.mjs +45 -0
- package/dist/agents-BLiMq9E1.mjs +113 -0
- package/dist/application-analysis-C9Ck2Yeg.mjs +1498 -0
- package/dist/application-routing-DbR-W5lG.mjs +25 -0
- package/dist/atomic-write-DA6eD1Kp.mjs +17 -0
- package/dist/auth-BKsUmWbT.d.mts +77 -0
- package/dist/auth-DkvoW5hB.mjs +33 -0
- package/dist/auth-aKyIWkdS.mjs +1 -0
- package/dist/auth-client-6-Ft9i9T.d.mts +5 -0
- package/dist/auth-client-DwCdwKbw.mjs +5 -0
- package/dist/auth-client-react-CJdeErvM.mjs +5 -0
- package/dist/auth-client-react-DvQLe5Zb.d.mts +5 -0
- package/dist/auth-link-D-DddkCQ.mjs +26 -0
- package/dist/auth-migrations-DDeifS3v.mjs +206 -0
- package/dist/auth-router-tWzIwf8f.mjs +66 -0
- package/dist/auth-xnkmpZUl.mjs +311 -0
- package/dist/base64-ikl9yBy3.mjs +15 -0
- package/dist/better-auth-shared-Br6TNaYJ.mjs +473 -0
- package/dist/better-auth-shared-CsBNvPOU.d.mts +56 -0
- package/dist/build-cmd-BnZezraT.mjs +153 -0
- package/dist/build-output-dir-Clj_unKN.mjs +402 -0
- package/dist/cancel-deploy-DKAj5U1Z.mjs +57 -0
- package/dist/cf-access-Bhz9wX6p.mjs +131 -0
- package/dist/cf-access-CUP5L08W.mjs +67 -0
- package/dist/cf-build-output-DA6uJomQ.mjs +1 -0
- package/dist/cf-build-output-DNQTwMNU.mjs +438 -0
- package/dist/cf-command-values-2kOtxMo1.mjs +26 -0
- package/dist/cf-config-migrate-COOCi4Ge.mjs +330 -0
- package/dist/cf-worker-settings-CIh4t_yG.mjs +41 -0
- package/dist/cli/cli.d.mts +1 -0
- package/dist/cli/cli.mjs +88 -0
- package/dist/cli/cloudflare-operation-process.d.mts +1 -0
- package/dist/cli/cloudflare-operation-process.mjs +1284 -0
- package/dist/cli/env-schema-probe.d.mts +43 -0
- package/dist/cli/env-schema-probe.mjs +165 -0
- package/dist/cli-main-HeXRQml6.mjs +1846 -0
- package/dist/client-D3D5RM5h.mjs +940 -0
- package/dist/client-VF2Nzc7Z.mjs +1 -0
- package/dist/cloudflare-auth-jb-1e43r.mjs +152 -0
- package/dist/cloudflare-cmd-B62t8Fm-.mjs +59 -0
- package/dist/cloudflare-config-i8yanry0.mjs +186 -0
- package/dist/cloudflare-connect-x7IsYghw.mjs +55 -0
- package/dist/cloudflare-operations-BeK7bhnP.mjs +627 -0
- package/dist/cloudflare-operations-C3Uu0Emj.mjs +1 -0
- package/dist/cloudflare-process-Cc6oiJqk.mjs +309 -0
- package/dist/cloudflare-user-output-CqONaAbP.mjs +19 -0
- package/dist/collect-8i0wU63d.mjs +1 -0
- package/dist/collect-C6Blu9yw.mjs +48 -0
- package/dist/config-CN_RFRkS.mjs +86 -0
- package/dist/config-D5G-Tx6o.mjs +1 -0
- package/dist/config-DOaFIK3w.mjs +88 -0
- package/dist/config-entry.d.mts +202 -0
- package/dist/config-entry.mjs +6 -0
- package/dist/config-tNx0HlFv.mjs +516 -0
- package/dist/connect-hLPNppu3.mjs +84 -0
- package/dist/create-project-B35ux-LA.mjs +126 -0
- package/dist/create-project-tJ1KwNss.mjs +1 -0
- package/dist/database-provider-DkZo4VwN.mjs +5 -0
- package/dist/database-provider.d.mts +25 -0
- package/dist/database-provider.mjs +1 -0
- package/dist/db-BH_md90k.mjs +1735 -0
- package/dist/delete-BSKI7V23.mjs +65 -0
- package/dist/deploy-C8KHBNsh.mjs +6512 -0
- package/dist/deploy-DCZBr7Ey.mjs +2 -0
- package/dist/deploy.d.mts +31 -0
- package/dist/deploy.mjs +118 -0
- package/dist/dev-inbox-I0nqTCdf.mjs +216 -0
- package/dist/discover-DJPmQcL5.mjs +36 -0
- package/dist/discover-EVuydEoM.mjs +1 -0
- package/dist/dist-B6eN80gc.mjs +1612 -0
- package/dist/dist-Cp4b1_T9.mjs +1 -0
- package/dist/dist-DMYe8CZJ.mjs +48 -0
- package/dist/dist-STQXl8ck.mjs +1878 -0
- package/dist/domain-C4ZhEiFG.mjs +149 -0
- package/dist/dotenv-4NdUCXbB.mjs +156 -0
- package/dist/drizzle-DqVFXtlc.mjs +306 -0
- package/dist/drizzle-Ds5P0n-S.mjs +1 -0
- package/dist/edge.d.mts +2 -0
- package/dist/edge.mjs +1 -0
- package/dist/email-B3TWga7x.mjs +742 -0
- package/dist/email-C_ATvNIG.mjs +2865 -0
- package/dist/email-cloudflare-DuAc9zny.mjs +854 -0
- package/dist/email-protocol-CZ0bAkI8.mjs +81 -0
- package/dist/env-CTAo8ifZ.mjs +73 -0
- package/dist/env-DUyTzroe.mjs +88 -0
- package/dist/env-Dl4Wggec.mjs +71 -0
- package/dist/env-helpers-BX0APszT.mjs +135 -0
- package/dist/env-helpers-U56xuFgL.d.mts +20 -0
- package/dist/env-mask-BsHxq3R8.mjs +46 -0
- package/dist/env-public-Cw_xPi1D.d.mts +119 -0
- package/dist/env-raw-Bo6TtrHU.mjs +41 -0
- package/dist/env-types-Bg-dTh8u.mjs +56 -0
- package/dist/env-validation-BufZConV.mjs +488 -0
- package/dist/env-validation-DPqDo4DU.mjs +1 -0
- package/dist/fetch-CBgyyhzm.d.mts +87 -0
- package/dist/fetch-error-DmlRM6e4.mjs +264 -0
- package/dist/fetch-stream-2GUN3YN1.mjs +102 -0
- package/dist/fetch-stream-bUXynOyZ.d.mts +32 -0
- package/dist/fetch-tpPiSK10.mjs +25 -0
- package/dist/gen-dc13IRXh.mjs +509 -0
- package/dist/gen-kQqhFyOP.mjs +1 -0
- package/dist/generate-BgtlYpKg.mjs +1 -0
- package/dist/generate-Da9mWKzU.mjs +80 -0
- package/dist/generated-wrangler-config-CoDaaFsA.mjs +17 -0
- package/dist/git-metadata-Cukp5kV5.mjs +82 -0
- package/dist/github-cmd-DT5Onu6E.mjs +690 -0
- package/dist/handler-CJ7DiiRF.mjs +161 -0
- package/dist/handler-CVsIfRv7.d.mts +279 -0
- package/dist/help-Bpv6Qeqn.mjs +1946 -0
- package/dist/help-CfZ4Bsw5.mjs +1 -0
- package/dist/inbound-CqubE-9T.d.mts +311 -0
- package/dist/inbound-lHugZPuK.mjs +509 -0
- package/dist/index.d.mts +64 -0
- package/dist/index.mjs +4163 -0
- package/dist/info-CLQoCenb.mjs +109 -0
- package/dist/init-DRUR0j8C.mjs +2486 -0
- package/dist/limits-CMmYT2l8.d.mts +16 -0
- package/dist/limits-D27Lp6FP.mjs +46 -0
- package/dist/link-DinwJnon.mjs +52 -0
- package/dist/list-B84t4BhW.mjs +130 -0
- package/dist/live-Dui0-aj_.d.mts +105 -0
- package/dist/live-saC8barp.mjs +410 -0
- package/dist/load-user-env-g0ahkZcj.mjs +34 -0
- package/dist/local-d1-C3EeOV7-.mjs +103 -0
- package/dist/log-JDnPc0cF.mjs +23 -0
- package/dist/login-Bl5lH8nH.mjs +87 -0
- package/dist/login-DoI7AsbY.mjs +1 -0
- package/dist/logs-CaT2N2f7.mjs +129 -0
- package/dist/migrate-CbGscX-V.mjs +125 -0
- package/dist/migrate-Ce3JKLVs.mjs +1 -0
- package/dist/migration-handler-22qiuWPq.mjs +469 -0
- package/dist/migration-handler-Bb2BJh6g.d.mts +38 -0
- package/dist/mime-BMUN_QKG.mjs +1004 -0
- package/dist/mysql-migration-sql-CNuBSqdx.mjs +239 -0
- package/dist/neon-CJzQSycr.mjs +52 -0
- package/dist/node-tfv-3v0V.mjs +64 -0
- package/dist/operator-ai-logging-Ay7M4KWw.mjs +121 -0
- package/dist/operator-args-BFg32YyY.mjs +722 -0
- package/dist/operator-auth-DdYZYEkO.mjs +47 -0
- package/dist/operator-client-DBujdELO.mjs +82 -0
- package/dist/operator-cmd-C73WWJBl.mjs +443 -0
- package/dist/operator-cmd-CdZytuAF.mjs +1 -0
- package/dist/output-Bb34lF0w.mjs +173 -0
- package/dist/output-CVolXKC1.mjs +1 -0
- package/dist/package-DO4d3Qz5.mjs +1444 -0
- package/dist/package-json-DvS6IFRv.mjs +43 -0
- package/dist/pg-DoyPxa_X.mjs +15 -0
- package/dist/picocolors-D1NxSLw-.mjs +71 -0
- package/dist/plan-BHNt1QhK.mjs +1 -0
- package/dist/plan-DX4_-OM5.mjs +58 -0
- package/dist/platform-args-NI_vfWvD.mjs +538 -0
- package/dist/platform-args-ZC1-A1N9.mjs +1 -0
- package/dist/platform-auth-config-d-lY5-aY.mjs +371 -0
- package/dist/platform-auth-protection-Dhw7lUCk.mjs +231 -0
- package/dist/platform-auth-recovery-DaCc0tlx.mjs +309 -0
- package/dist/platform-cmd-5Ry-C9im.mjs +193 -0
- package/dist/platform-cmd-5oZq91lI.mjs +1 -0
- package/dist/platform-discovery-Bxg9aZXU.mjs +40 -0
- package/dist/platform-domain-DLVdGvGG.mjs +256 -0
- package/dist/platform-lifecycle-CUgjipXO.mjs +1 -0
- package/dist/platform-lifecycle-fRt5VMls.mjs +8928 -0
- package/dist/platform-management-5hEsRfR2.mjs +1 -0
- package/dist/platform-management-Djh1hzLP.mjs +1607 -0
- package/dist/platform-plans-config-CkbUKFpm.mjs +447 -0
- package/dist/platform-recovery-Cghx7FCR.mjs +96 -0
- package/dist/platform-registry-x1m9HBxf.mjs +450 -0
- package/dist/platform-runtime-logs-kkoiYFpF.mjs +72 -0
- package/dist/platform-setup-SfwCwnZg.mjs +306 -0
- package/dist/prepare-B9mB47T5.mjs +84 -0
- package/dist/prepare-DNIq07so.mjs +13 -0
- package/dist/prepare-LHkyJqxi.mjs +1 -0
- package/dist/project-CC7eN00D.mjs +141 -0
- package/dist/project-DcSd4BeI.mjs +1 -0
- package/dist/project-cmd-DTF19-fC.mjs +109 -0
- package/dist/project-paths-iXHKRTTQ.mjs +159 -0
- package/dist/project-slug-BUy0lmyR.mjs +1 -0
- package/dist/project-slug-CO6ci9XG.mjs +7 -0
- package/dist/project-team-CvdLhDF2.mjs +129 -0
- package/dist/project-token-CwZdUEGu.mjs +70 -0
- package/dist/project-tsconfig-P9X952KG.mjs +98 -0
- package/dist/project-zero-trust-CKDoPdN1.mjs +64 -0
- package/dist/providers-Cd3c7wi0.mjs +64 -0
- package/dist/providers-Df69hb_X.d.mts +5 -0
- package/dist/provision-DGlFJ3T9.mjs +1 -0
- package/dist/provision-mYVLuQiy.mjs +1814 -0
- package/dist/queues-Bc3FsBQT.d.mts +5 -0
- package/dist/r2-conditions-DSLmkiR5.mjs +60 -0
- package/dist/requests-DNhfyF3l.mjs +52 -0
- package/dist/resolve-project-BCsAMDRA.mjs +47 -0
- package/dist/resolve-project-DhU9_lIo.mjs +1 -0
- package/dist/resource-name-DlJ9QXzg.mjs +10 -0
- package/dist/response-HmNjB30w.mjs +29 -0
- package/dist/rollback-BvCHol52.mjs +150 -0
- package/dist/rolldown-runtime-uD8oG6U2.mjs +24 -0
- package/dist/route-types-CRWhr93D.mjs +592 -0
- package/dist/route-url-BIDZT78M.mjs +58 -0
- package/dist/route-url-Bla3Upsy.d.mts +42 -0
- package/dist/routes-stub.d.mts +24 -0
- package/dist/routes-stub.mjs +1 -0
- package/dist/routing-assets-CSheDWWM.mjs +54 -0
- package/dist/rpc-DcByS_q0.d.mts +39 -0
- package/dist/rpc-DtxIN9Tv.mjs +19 -0
- package/dist/runner-CPerdjIl.mjs +163 -0
- package/dist/runner-CUNtS5x7.mjs +1 -0
- package/dist/runner-mysql-7aA5hGoM.mjs +145 -0
- package/dist/runner-mysql-DrMKw203.mjs +1 -0
- package/dist/runner-pg-2pjltt0t.mjs +1 -0
- package/dist/runner-pg-mYc75KfH.mjs +61 -0
- package/dist/runtime/ai.d.mts +50 -0
- package/dist/runtime/ai.mjs +455 -0
- package/dist/runtime/auth-client-react.d.mts +2 -0
- package/dist/runtime/auth-client-react.mjs +1 -0
- package/dist/runtime/auth-client.d.mts +2 -0
- package/dist/runtime/auth-client.mjs +1 -0
- package/dist/runtime/auth.d.mts +2 -0
- package/dist/runtime/auth.mjs +1 -0
- package/dist/runtime/better-auth-mysql.d.mts +5 -0
- package/dist/runtime/better-auth-mysql.mjs +21 -0
- package/dist/runtime/better-auth-pg.d.mts +5 -0
- package/dist/runtime/better-auth-pg.mjs +21 -0
- package/dist/runtime/better-auth.d.mts +6 -0
- package/dist/runtime/better-auth.mjs +22 -0
- package/dist/runtime/client-react.d.mts +5 -0
- package/dist/runtime/client-react.mjs +5 -0
- package/dist/runtime/client.d.mts +5 -0
- package/dist/runtime/client.mjs +5 -0
- package/dist/runtime/db-mysql.d.mts +2 -0
- package/dist/runtime/db-mysql.mjs +1 -0
- package/dist/runtime/db-pg.d.mts +2 -0
- package/dist/runtime/db-pg.mjs +1 -0
- package/dist/runtime/db.d.mts +17 -0
- package/dist/runtime/db.mjs +36 -0
- package/dist/runtime/drizzle-arktype.d.mts +1 -0
- package/dist/runtime/drizzle-arktype.mjs +2 -0
- package/dist/runtime/drizzle-valibot.d.mts +1 -0
- package/dist/runtime/drizzle-valibot.mjs +2 -0
- package/dist/runtime/drizzle-zod.d.mts +1 -0
- package/dist/runtime/drizzle-zod.mjs +2 -0
- package/dist/runtime/durable.d.mts +64 -0
- package/dist/runtime/durable.mjs +165 -0
- package/dist/runtime/email/testing.d.mts +108 -0
- package/dist/runtime/email/testing.mjs +268 -0
- package/dist/runtime/email-protocol.d.mts +25 -0
- package/dist/runtime/email-protocol.mjs +1 -0
- package/dist/runtime/email.d.mts +26 -0
- package/dist/runtime/email.mjs +524 -0
- package/dist/runtime/env-public-client.d.mts +19 -0
- package/dist/runtime/env-public-client.mjs +55 -0
- package/dist/runtime/env-public.d.mts +4 -0
- package/dist/runtime/env-public.mjs +277 -0
- package/dist/runtime/env.d.mts +12 -0
- package/dist/runtime/env.mjs +1 -0
- package/dist/runtime/fetch-server.d.mts +6 -0
- package/dist/runtime/fetch-server.mjs +29 -0
- package/dist/runtime/fetch-stream.d.mts +3 -0
- package/dist/runtime/fetch-stream.mjs +3 -0
- package/dist/runtime/fetch.d.mts +2 -0
- package/dist/runtime/fetch.mjs +3 -0
- package/dist/runtime/handler.d.mts +3 -0
- package/dist/runtime/handler.mjs +1 -0
- package/dist/runtime/kv.d.mts +45 -0
- package/dist/runtime/kv.mjs +103 -0
- package/dist/runtime/limits.d.mts +2 -0
- package/dist/runtime/limits.mjs +1 -0
- package/dist/runtime/live-client.d.mts +40 -0
- package/dist/runtime/live-client.mjs +282 -0
- package/dist/runtime/live-server.d.mts +11 -0
- package/dist/runtime/live-server.mjs +419 -0
- package/dist/runtime/live.d.mts +3 -0
- package/dist/runtime/live.mjs +1 -0
- package/dist/runtime/log.d.mts +24 -0
- package/dist/runtime/log.mjs +57 -0
- package/dist/runtime/migration-handler-mysql.d.mts +2 -0
- package/dist/runtime/migration-handler-mysql.mjs +111 -0
- package/dist/runtime/migration-handler-pg.d.mts +2 -0
- package/dist/runtime/migration-handler-pg.mjs +94 -0
- package/dist/runtime/migration-handler.d.mts +2 -0
- package/dist/runtime/migration-handler.mjs +1 -0
- package/dist/runtime/procedure.d.mts +27 -0
- package/dist/runtime/procedure.mjs +36 -0
- package/dist/runtime/procedures.d.mts +24 -0
- package/dist/runtime/procedures.mjs +56 -0
- package/dist/runtime/queues.d.mts +2 -0
- package/dist/runtime/queues.mjs +8 -0
- package/dist/runtime/remote/binding-handler.d.mts +11 -0
- package/dist/runtime/remote/binding-handler.mjs +227 -0
- package/dist/runtime/remote/index.d.mts +12 -0
- package/dist/runtime/remote/index.mjs +467 -0
- package/dist/runtime/response.d.mts +11 -0
- package/dist/runtime/response.mjs +1 -0
- package/dist/runtime/route-url.d.mts +2 -0
- package/dist/runtime/route-url.mjs +1 -0
- package/dist/runtime/routing.d.mts +53 -0
- package/dist/runtime/routing.mjs +425 -0
- package/dist/runtime/rpc-react.d.mts +16 -0
- package/dist/runtime/rpc-react.mjs +50 -0
- package/dist/runtime/rpc.d.mts +2 -0
- package/dist/runtime/rpc.mjs +1 -0
- package/dist/runtime/sandbox-container.d.mts +3 -0
- package/dist/runtime/sandbox-container.mjs +1 -0
- package/dist/runtime/sandbox.d.mts +5 -0
- package/dist/runtime/sandbox.mjs +196 -0
- package/dist/runtime/schema-d1.d.mts +1 -0
- package/dist/runtime/schema-d1.mjs +2 -0
- package/dist/runtime/schema-mysql.d.mts +1 -0
- package/dist/runtime/schema-mysql.mjs +2 -0
- package/dist/runtime/schema-pg.d.mts +1 -0
- package/dist/runtime/schema-pg.mjs +2 -0
- package/dist/runtime/seed.d.mts +34 -0
- package/dist/runtime/seed.mjs +5 -0
- package/dist/runtime/sse-client.d.mts +31 -0
- package/dist/runtime/sse-client.mjs +42 -0
- package/dist/runtime/sse.d.mts +32 -0
- package/dist/runtime/sse.mjs +1 -0
- package/dist/runtime/storage.d.mts +4 -0
- package/dist/runtime/storage.mjs +13 -0
- package/dist/runtime/validator.d.mts +2 -0
- package/dist/runtime/validator.mjs +1 -0
- package/dist/runtime/ws-server.d.mts +26 -0
- package/dist/runtime/ws-server.mjs +297 -0
- package/dist/runtime/ws.d.mts +2 -0
- package/dist/runtime/ws.mjs +108 -0
- package/dist/sandbox-CWDjoEG2.d.mts +50 -0
- package/dist/sandbox-container-BqamdFCx.d.mts +73 -0
- package/dist/sandbox-container-d1AHLpgn.mjs +291 -0
- package/dist/secret-DCF9RXTc.mjs +146 -0
- package/dist/skills-Dr3AjuBF.mjs +63 -0
- package/dist/sqlite-validation-CLJXXN93.mjs +24 -0
- package/dist/sse-CxR30yMF.mjs +174 -0
- package/dist/standard-schema-CuDawHOC.d.mts +40 -0
- package/dist/static-asset-marker-mWMX2dLa.mjs +38 -0
- package/dist/subcommand-prompt-B9yUo--u.mjs +370 -0
- package/dist/terminal-log-text-DNsWJREL.mjs +31 -0
- package/dist/types-D7-4tBu7.d.mts +1 -0
- package/dist/untrusted-env-lL7RkYiC.mjs +50 -0
- package/dist/validate-B-zsjhiz.mjs +162 -0
- package/dist/validate-DbqGdPPY.mjs +1 -0
- package/dist/validator-8-NZs2Xr.mjs +168 -0
- package/dist/version-metadata-DsSoNsKJ.mjs +23 -0
- package/dist/wrangler-DU784Dkf.mjs +1452 -0
- package/dist/wrangler-Rr9_76DQ.mjs +1 -0
- package/dist/ws-Q_osq9VK.d.mts +137 -0
- package/dist/yarn-pnp-DgWbE7z5.mjs +91 -0
- package/docs/guide/ai.md +273 -0
- package/docs/guide/app-types.md +101 -0
- package/docs/guide/auth.md +255 -0
- package/docs/guide/database/d1.md +86 -0
- package/docs/guide/database/mysql.md +72 -0
- package/docs/guide/database/postgresql.md +94 -0
- package/docs/guide/database.md +454 -0
- package/docs/guide/deployment.md +124 -0
- package/docs/guide/durable-state.md +192 -0
- package/docs/guide/edge/headers.md +47 -0
- package/docs/guide/edge/redirects.md +85 -0
- package/docs/guide/edge/rewrites.md +119 -0
- package/docs/guide/edge/static-assets.md +94 -0
- package/docs/guide/email/domains.md +119 -0
- package/docs/guide/email/receiving.md +142 -0
- package/docs/guide/email/sending.md +262 -0
- package/docs/guide/email.md +23 -0
- package/docs/guide/env-vars.md +115 -0
- package/docs/guide/index.md +37 -0
- package/docs/guide/jobs.md +80 -0
- package/docs/guide/kv.md +100 -0
- package/docs/guide/live.md +181 -0
- package/docs/guide/platform/administration/access.md +165 -0
- package/docs/guide/platform/administration/connected-apps.md +84 -0
- package/docs/guide/platform/administration/email.md +169 -0
- package/docs/guide/platform/administration/operations.md +100 -0
- package/docs/guide/platform/administration/plans.md +156 -0
- package/docs/guide/platform/administration/projects.md +74 -0
- package/docs/guide/platform/administration/zero-trust.md +205 -0
- package/docs/guide/platform/development/local.md +122 -0
- package/docs/guide/platform/development/runtime.md +115 -0
- package/docs/guide/platform/development/schema-ci.md +44 -0
- package/docs/guide/platform/installation/ci.md +62 -0
- package/docs/guide/platform/installation/credentials.md +140 -0
- package/docs/guide/platform/installation/domains.md +120 -0
- package/docs/guide/platform/installation/first-deployment.md +95 -0
- package/docs/guide/platform/installation/maintenance.md +250 -0
- package/docs/guide/platform/installation/prerequisites.md +176 -0
- package/docs/guide/platform/installation/setup.md +300 -0
- package/docs/guide/platform/installation/uninstall.md +110 -0
- package/docs/guide/platform-administration.md +19 -0
- package/docs/guide/platform-development.md +16 -0
- package/docs/guide/procedures.md +48 -0
- package/docs/guide/project-collaboration.md +99 -0
- package/docs/guide/queues.md +149 -0
- package/docs/guide/quickstart.md +129 -0
- package/docs/guide/remote-dev.md +67 -0
- package/docs/guide/sandboxes.md +134 -0
- package/docs/guide/self-hosted-platform.md +45 -0
- package/docs/guide/server-routing.md +283 -0
- package/docs/guide/sse.md +174 -0
- package/docs/guide/storage.md +82 -0
- package/docs/guide/testing.md +64 -0
- package/docs/guide/type-safety.md +270 -0
- package/docs/guide/typed-fetch.md +98 -0
- package/docs/guide/websockets.md +230 -0
- package/docs/index.md +102 -0
- package/docs/integrations/agents.md +38 -0
- package/docs/integrations/cloudflare.md +241 -0
- package/docs/integrations/hono.md +127 -0
- package/docs/reference/api/auth.md +195 -0
- package/docs/reference/api/client.md +90 -0
- package/docs/reference/api/database.md +118 -0
- package/docs/reference/api/deploy.md +63 -0
- package/docs/reference/api/durable.md +47 -0
- package/docs/reference/api/env.md +51 -0
- package/docs/reference/api/handlers.md +189 -0
- package/docs/reference/api/plugin.md +40 -0
- package/docs/reference/api/resources.md +116 -0
- package/docs/reference/api/rewrites.md +111 -0
- package/docs/reference/api/types.md +126 -0
- package/docs/reference/api.md +71 -0
- package/docs/reference/cli/auth.md +87 -0
- package/docs/reference/cli/database.md +159 -0
- package/docs/reference/cli/deploy.md +117 -0
- package/docs/reference/cli/domains.md +42 -0
- package/docs/reference/cli/email.md +145 -0
- package/docs/reference/cli/generate.md +113 -0
- package/docs/reference/cli/github.md +181 -0
- package/docs/reference/cli/platform-config.md +93 -0
- package/docs/reference/cli/platform-email.md +81 -0
- package/docs/reference/cli/platform-installation.md +166 -0
- package/docs/reference/cli/platform-operations.md +90 -0
- package/docs/reference/cli/platform-users.md +159 -0
- package/docs/reference/cli/platform-zero-trust.md +60 -0
- package/docs/reference/cli/platform.md +78 -0
- package/docs/reference/cli/project.md +208 -0
- package/docs/reference/cli/secrets.md +79 -0
- package/docs/reference/cli/setup.md +88 -0
- package/docs/reference/cli.md +115 -0
- package/docs/reference/config.md +478 -0
- package/docs/reference/resource-inference.md +72 -0
- package/docs/reference/structure.md +138 -0
- package/package.json +389 -3
- package/sandbox.Dockerfile +4 -0
- package/schema.json +353 -0
- package/skills/bwf/SKILL.md +100 -0
- package/skills/migrate-vite-cloudflare-to-bwf/SKILL.md +53 -0
- package/templates/assets/bwf.svg +5 -0
- package/templates/assets/icons.svg +49 -0
- package/templates/assets/react.svg +1 -0
- package/templates/assets/stack.svg +35 -0
|
@@ -0,0 +1,1607 @@
|
|
|
1
|
+
import { A as confirm, H as outro, K as select, L as log, tt as isCancel } from "./dist-STQXl8ck.mjs";
|
|
2
|
+
import { t as ensurePlatformAccessToken } from "./cf-access-Bhz9wX6p.mjs";
|
|
3
|
+
import { f as import_picocolors, l as formatUrl, m as printSuccess, p as note } from "./output-Bb34lF0w.mjs";
|
|
4
|
+
import { $ as hyperdriveOriginConfigHash, B as revalidatePlatformInstallAction, C as readPlatformDatabase, D as resolveBootstrapGitHubId, E as createPlatformInstallationSecrets, F as legacyResourceConfigHash, G as verifyPlatformCloudflareCredential, H as turnOffInstalledProjectZeroTrust, I as matchesRecordedR2Fingerprint, K as activatePlatformAccessCredentials, L as platformAdoptionIntentHash, M as dnsRecordConfigHash, N as formatPlatformInstallPlan, P as hasProvisionIntentStep, Q as PlatformRuntimeTokenEmailPermissionError, R as r2BucketConfigHash, S as formatZeroTrustApplications, T as createPlatformHealthProbeToken, U as assertPlatformOperatorCredentialCanApplyPlan, V as platformDatabaseNameFromOwnerUrl, W as resolvePlatformCloudflareCredential, X as PlatformCloudflareApiError, Z as PlatformCloudflareClient, a as createPlatformProgress, b as readPlatformProjectZeroTrustState, c as formatPlatformWorkerOutsideChanges, d as authenticationSetupRequestHash, et as hyperdriveOriginFromConnectionString, f as readLoginReplacementFile, g as acquirePlatformDatabaseLifecycleLock, h as installPlatform, j as createPlatformInstallPlan, k as platformTrafficAttachmentWorker, l as reviewPlatformWorkerOutsideChanges, m as REMOTE_INSTALLATION_MANIFEST_KEY, n as resolvePlatformInstallDatabaseUrl, nt as verifyPlatformRuntimeTokenEmailPermissions, o as withPlatformProgress, p as replacePendingInstallationAuthentication, rt as verifyPlatformRuntimeTokenPermissions, s as findPlatformWorkerOutsideChanges, t as assertNoninteractivePlatformMutationAcknowledged, tt as hyperdriveOriginMatches, u as uploadPlatformWorkerOutsideChanges, w as loadPlatformRuntime, x as assertProjectZeroTrustAllowsUninstall, y as readPlatformProjectSlugs, z as resourceMarkerProblem } from "./platform-lifecycle-fRt5VMls.mjs";
|
|
5
|
+
import { S as writePendingInstallationSecrets, _ as removePlatformConnectionForInstallation, g as removeInstallationRecoverySecrets, h as readPendingInstallationSecrets, m as readInstallationRecoverySecrets, o as listInstallationManifests, t as acquirePlatformLifecycleLock, v as resolveInstallationManifest, x as writeInstallationManifest } from "./platform-registry-x1m9HBxf.mjs";
|
|
6
|
+
import { i as updateProjectWorkerRuntimeLogs, n as assertPlatformRuntimeLogsSupported, r as shouldUpdateProjectWorkerRuntimeLogs } from "./platform-runtime-logs-kkoiYFpF.mjs";
|
|
7
|
+
import { r as assertPlatformStorageSupported } from "./platform-args-NI_vfWvD.mjs";
|
|
8
|
+
import { PLATFORM_DISABLED_KEY, PLATFORM_DISABLED_VALUE, PLATFORM_R2_OWNERSHIP_MARKER_KEY, parsePlatformInstallationManifest, recordInstallationResource, recordInstallationStep, setInstallationDesiredState, transitionInstallation } from "@builtbyfriends/platform";
|
|
9
|
+
import { setTimeout } from "node:timers/promises";
|
|
10
|
+
// src/cli/platform-teardown.ts
|
|
11
|
+
/**
|
|
12
|
+
* `bwf platform uninstall --purge-resources` deletes every Cloudflare resource the
|
|
13
|
+
* installation created, in an order Cloudflare accepts:
|
|
14
|
+
*
|
|
15
|
+
* traffic (routes, custom domains, DNS) -> Access -> Email Routing rules
|
|
16
|
+
* -> queue consumers -> Workers except tail -> Queues -> dispatch namespace
|
|
17
|
+
* -> tail Worker -> Hyperdrive and KV -> R2 -> AI Gateway -> routing KV (last)
|
|
18
|
+
*
|
|
19
|
+
* Each resource is proven to belong to this installation right before its
|
|
20
|
+
* DELETE, and Cloudflare refuses a resource that something outside the
|
|
21
|
+
* installation still uses. The only forced DELETE is for a platform Worker
|
|
22
|
+
* that Cloudflare refused while every Worker it names as a dependent is one
|
|
23
|
+
* this installation created: the API and proxy Workers bind to each other, so
|
|
24
|
+
* neither can go first without it. A route, custom domain, DNS
|
|
25
|
+
* record, or Access resource that no longer matches what was recorded is kept
|
|
26
|
+
* and listed with the reason instead of stopping the run. Every finished
|
|
27
|
+
* deletion is checkpointed, so rerunning the command continues where it
|
|
28
|
+
* stopped. The routing KV namespace holds that checkpoint, so uninstall
|
|
29
|
+
* deletes it last.
|
|
30
|
+
*
|
|
31
|
+
* An uninstall without --purge-resources records what it leaves as retained. If it
|
|
32
|
+
* stopped before it finished, --purge-resources considers those resources again.
|
|
33
|
+
*/
|
|
34
|
+
const PURGE_RESOURCES_STEP_PREFIX = "uninstall:purge-resources:";
|
|
35
|
+
const WORKER_ORDER = [
|
|
36
|
+
"email-gateway-worker",
|
|
37
|
+
"proxy-worker",
|
|
38
|
+
"dispatch-worker",
|
|
39
|
+
"api-worker"
|
|
40
|
+
];
|
|
41
|
+
const PERMISSIONS = {
|
|
42
|
+
access: "Account → Access: Apps and Policies → Edit",
|
|
43
|
+
aiGateway: "Account → AI Gateway → Edit",
|
|
44
|
+
dns: "Zone → DNS → Edit",
|
|
45
|
+
emailRouting: "Zone → Email Routing Rules → Edit",
|
|
46
|
+
hyperdrive: "Account → Hyperdrive → Edit",
|
|
47
|
+
kv: "Account → Workers KV Storage → Edit",
|
|
48
|
+
queues: "Account → Queues → Edit",
|
|
49
|
+
r2: "Account → Workers R2 Storage → Edit",
|
|
50
|
+
routes: "Zone → Workers Routes → Edit",
|
|
51
|
+
serviceTokens: "Account → Access: Service Tokens → Edit",
|
|
52
|
+
workers: "Account → Workers Scripts → Edit"
|
|
53
|
+
};
|
|
54
|
+
function isPlatformTailWorker(manifest, resource) {
|
|
55
|
+
return resource.kind === "worker" && (resource.key === "tail-worker" || resource.name === manifest.deployment.resources.tailWorker);
|
|
56
|
+
}
|
|
57
|
+
function purgeResourcesResumeCommand(manifest) {
|
|
58
|
+
return `bwf platform uninstall ${manifest.id} --purge-resources`;
|
|
59
|
+
}
|
|
60
|
+
function accessStepKey(access) {
|
|
61
|
+
return `${PURGE_RESOURCES_STEP_PREFIX}access:${access.key}`;
|
|
62
|
+
}
|
|
63
|
+
/** Access resources that --purge-resources already deleted. */
|
|
64
|
+
function isPurgedAccessResource(manifest, access) {
|
|
65
|
+
return manifest.steps.some((step) => step.key === accessStepKey(access));
|
|
66
|
+
}
|
|
67
|
+
function hasStep(manifest, key) {
|
|
68
|
+
return manifest.steps.some((step) => step.key === `${PURGE_RESOURCES_STEP_PREFIX}${key}`);
|
|
69
|
+
}
|
|
70
|
+
function keptStepKey(key) {
|
|
71
|
+
return `kept:${key}`;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Why --purge-resources kept a resource it was going to delete, for example because
|
|
75
|
+
* a route now serves another Worker; null when it did not keep it. Access
|
|
76
|
+
* resources use the key `access:<key>`.
|
|
77
|
+
*/
|
|
78
|
+
function purgeResourcesKeptReason(manifest, key) {
|
|
79
|
+
return manifest.steps.find((step) => step.key === `uninstall:purge-resources:${keptStepKey(key)}`)?.resultHash ?? null;
|
|
80
|
+
}
|
|
81
|
+
/** An uninstall that started has not finished, so what it kept can be reconsidered. */
|
|
82
|
+
function isReopenable(manifest) {
|
|
83
|
+
return manifest.status !== "uninstalled";
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* A resource the installation created that --purge-resources may still delete: one
|
|
87
|
+
* that is ready, or one that an uninstall which stopped before it finished
|
|
88
|
+
* recorded as retained. Resources --purge-resources itself kept, and earlier
|
|
89
|
+
* versions of a resource kept when it was replaced, are never reconsidered.
|
|
90
|
+
*/
|
|
91
|
+
function isPurgeResourcesCandidate(manifest, resource) {
|
|
92
|
+
return resource.ownership === "created" && (resource.state === "ready" || resource.state === "retained" && isReopenable(manifest) && !resource.key.startsWith("retained:") && purgeResourcesKeptReason(manifest, resource.key) === null);
|
|
93
|
+
}
|
|
94
|
+
/** The zone that routes and DNS records live in, if it can still be used. */
|
|
95
|
+
function usableZone(manifest) {
|
|
96
|
+
return manifest.resources.find((resource) => resource.key === "zone" && (resource.state === "ready" || resource.state === "retained" && isReopenable(manifest)));
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* A recorded resource whose live configuration no longer matches the
|
|
100
|
+
* installation's record. --purge-resources keeps such a DNS record and continues.
|
|
101
|
+
*/
|
|
102
|
+
var PlatformResourceChangedError = class extends Error {
|
|
103
|
+
resourceKey;
|
|
104
|
+
reason;
|
|
105
|
+
constructor(resourceKey, reason, message) {
|
|
106
|
+
super(message);
|
|
107
|
+
this.resourceKey = resourceKey;
|
|
108
|
+
this.reason = reason;
|
|
109
|
+
this.name = "PlatformResourceChangedError";
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
/** The zone whose Email Routing rules may send mail to the gateway Worker. */
|
|
113
|
+
function emailRoutingZone(manifest) {
|
|
114
|
+
return manifest.deployment.capabilities.email ? manifest.deployment.emailSharedZoneId ?? null : null;
|
|
115
|
+
}
|
|
116
|
+
/** Everything --purge-resources will delete, in deletion order. */
|
|
117
|
+
function purgeResourcesTargets(manifest) {
|
|
118
|
+
const resources = manifest.resources;
|
|
119
|
+
const routing = resources.find((resource) => resource.key === "routing-kv");
|
|
120
|
+
const candidate = (resource) => isPurgeResourcesCandidate(manifest, resource);
|
|
121
|
+
if (!routing || routing.state !== "ready" && !candidate(routing)) return [];
|
|
122
|
+
const zone = usableZone(manifest);
|
|
123
|
+
const workers = resources.filter((resource) => resource.kind === "worker" && candidate(resource));
|
|
124
|
+
const targets = [];
|
|
125
|
+
for (const resource of resources) {
|
|
126
|
+
if (resource.kind !== "worker-route" && resource.kind !== "worker-custom-domain" || resource.state !== "ready" && resource.state !== "retained" || resource.kind === "worker-route" && !zone || purgeResourcesKeptReason(manifest, resource.key) !== null) continue;
|
|
127
|
+
const name = platformTrafficAttachmentWorker(manifest.deployment, resource);
|
|
128
|
+
const worker = workers.find((entry) => entry.name === name);
|
|
129
|
+
if (worker) targets.push({
|
|
130
|
+
phase: "traffic",
|
|
131
|
+
resource,
|
|
132
|
+
worker
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
for (const resource of resources) if (resource.kind === "dns-record" && candidate(resource) && zone) targets.push({
|
|
136
|
+
phase: "dns",
|
|
137
|
+
resource
|
|
138
|
+
});
|
|
139
|
+
const access = (manifest.authenticationResources ?? []).filter((entry) => entry.ownership === "created" && !isPurgedAccessResource(manifest, entry) && purgeResourcesKeptReason(manifest, `access:${entry.key}`) === null);
|
|
140
|
+
for (const kind of ["application", "service-token"]) for (const entry of access.filter((candidate) => candidate.kind === kind)) targets.push({
|
|
141
|
+
phase: "access",
|
|
142
|
+
access: entry
|
|
143
|
+
});
|
|
144
|
+
const gateway = workers.find((worker) => worker.key === "email-gateway-worker");
|
|
145
|
+
if (gateway && emailRoutingZone(manifest) && !hasStep(manifest, "email-routing")) targets.push({
|
|
146
|
+
phase: "email",
|
|
147
|
+
resource: gateway
|
|
148
|
+
});
|
|
149
|
+
const queues = resources.filter((resource) => resource.kind === "queue" && candidate(resource));
|
|
150
|
+
for (const resource of queues) if (!hasStep(manifest, `consumers:${resource.key}`)) targets.push({
|
|
151
|
+
phase: "queue-consumers",
|
|
152
|
+
resource
|
|
153
|
+
});
|
|
154
|
+
const rank = (resource) => {
|
|
155
|
+
const index = WORKER_ORDER.indexOf(resource.key);
|
|
156
|
+
return index < 0 ? WORKER_ORDER.length : index;
|
|
157
|
+
};
|
|
158
|
+
for (const resource of workers.filter((worker) => !isPlatformTailWorker(manifest, worker)).sort((left, right) => rank(left) - rank(right) || left.key.localeCompare(right.key))) targets.push({
|
|
159
|
+
phase: "workers",
|
|
160
|
+
resource
|
|
161
|
+
});
|
|
162
|
+
for (const resource of queues) targets.push({
|
|
163
|
+
phase: "queues",
|
|
164
|
+
resource
|
|
165
|
+
});
|
|
166
|
+
for (const resource of resources) if (resource.kind === "dispatch-namespace" && candidate(resource)) targets.push({
|
|
167
|
+
phase: "dispatch",
|
|
168
|
+
resource
|
|
169
|
+
});
|
|
170
|
+
for (const resource of workers.filter((worker) => isPlatformTailWorker(manifest, worker))) targets.push({
|
|
171
|
+
phase: "tail",
|
|
172
|
+
resource
|
|
173
|
+
});
|
|
174
|
+
for (const kind of ["hyperdrive", "kv-namespace"]) for (const resource of resources) if (resource.kind === kind && resource.key !== "routing-kv" && candidate(resource)) targets.push({
|
|
175
|
+
phase: "data",
|
|
176
|
+
resource
|
|
177
|
+
});
|
|
178
|
+
for (const kind of ["r2-bucket", "ai-gateway"]) for (const resource of resources) if (resource.kind === kind && candidate(resource)) targets.push({
|
|
179
|
+
phase: kind === "r2-bucket" ? "r2" : "ai-gateway",
|
|
180
|
+
resource
|
|
181
|
+
});
|
|
182
|
+
if (candidate(routing)) targets.push({
|
|
183
|
+
phase: "routing",
|
|
184
|
+
resource: routing
|
|
185
|
+
});
|
|
186
|
+
return targets;
|
|
187
|
+
}
|
|
188
|
+
/** Whether --purge-resources removes, or has removed, the rules that send mail to the gateway Worker. */
|
|
189
|
+
function purgeResourcesHandlesEmailRouting(manifest) {
|
|
190
|
+
return hasStep(manifest, "email-routing") || purgeResourcesTargets(manifest).some((target) => target.phase === "email");
|
|
191
|
+
}
|
|
192
|
+
/** Manifest resources that --purge-resources leaves in the account. */
|
|
193
|
+
function purgeResourcesKeptResources(manifest) {
|
|
194
|
+
const targets = new Set(purgeResourcesTargets(manifest).flatMap((target) => "resource" in target ? [target.resource.key] : []));
|
|
195
|
+
return manifest.resources.filter((resource) => (resource.state === "ready" || resource.state === "retained") && !targets.has(resource.key));
|
|
196
|
+
}
|
|
197
|
+
function resourceLabel(resource) {
|
|
198
|
+
return `${resource.kind}: ${resource.name}${resource.name === resource.id ? "" : ` (${resource.id})`}`;
|
|
199
|
+
}
|
|
200
|
+
/** Plan lines for --purge-resources: what is deleted, in order, then what is kept. */
|
|
201
|
+
function describePurgeResourcesPlan(manifest) {
|
|
202
|
+
const targets = purgeResourcesTargets(manifest);
|
|
203
|
+
const lines = [];
|
|
204
|
+
let step = 0;
|
|
205
|
+
let previous = null;
|
|
206
|
+
const consumerQueues = [];
|
|
207
|
+
for (const target of targets) {
|
|
208
|
+
if (target.phase === "email") {
|
|
209
|
+
step++;
|
|
210
|
+
previous = target.phase;
|
|
211
|
+
lines.push(` ${step}. Email Routing rules in zone ${emailRoutingZone(manifest)} that send mail to ${target.resource.name}, and its catch-all rule if it does (reset to drop mail, disabled)`);
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (target.phase !== previous) {
|
|
215
|
+
step++;
|
|
216
|
+
previous = target.phase;
|
|
217
|
+
}
|
|
218
|
+
const prefix = ` ${step}. `;
|
|
219
|
+
if (target.phase === "traffic") lines.push(`${prefix}${resourceLabel(target.resource)} -> ${target.worker.name}`);
|
|
220
|
+
else if (target.phase === "access") lines.push(`${prefix}Access ${target.access.kind}: ${target.access.name} (${target.access.id})`);
|
|
221
|
+
else if (target.phase === "queue-consumers") {
|
|
222
|
+
consumerQueues.push(target.resource.name);
|
|
223
|
+
if (consumerQueues.length === 1) lines.push(`${prefix}queue consumers run by this installation's Workers on:`);
|
|
224
|
+
lines.push(` ${target.resource.name}`);
|
|
225
|
+
} else if (target.phase === "dispatch") lines.push(`${prefix}${resourceLabel(target.resource)}, with any application Workers still in it`);
|
|
226
|
+
else if (target.phase === "tail") lines.push(`${prefix}${resourceLabel(target.resource)}, the tail Worker, after the others`);
|
|
227
|
+
else if (target.phase === "workers" && target.resource.key === "api-worker") lines.push(`${prefix}${resourceLabel(target.resource)}, with its Durable Object data`);
|
|
228
|
+
else if (target.phase === "r2") lines.push(`${prefix}${resourceLabel(target.resource)}, emptied first`);
|
|
229
|
+
else if (target.phase === "ai-gateway") lines.push(`${prefix}${resourceLabel(target.resource)}, if Cloudflare shows it was created during installation; otherwise kept`);
|
|
230
|
+
else if (target.phase === "routing") lines.push(`${prefix}${resourceLabel(target.resource)}, last; it holds uninstall progress`);
|
|
231
|
+
else lines.push(`${prefix}${resourceLabel(target.resource)}`);
|
|
232
|
+
}
|
|
233
|
+
return lines.length ? ["Delete every resource this installation created (--purge-resources), in this order:", ...lines] : ["--purge-resources finds no resource it can prove this installation created."];
|
|
234
|
+
}
|
|
235
|
+
/** Lines naming what --purge-resources never removes. */
|
|
236
|
+
function purgeResourcesAlwaysKept() {
|
|
237
|
+
return [
|
|
238
|
+
" The external PostgreSQL database and its data.",
|
|
239
|
+
" Analytics Engine datasets; Cloudflare has no API to delete them.",
|
|
240
|
+
" Access policies and identity providers you chose.",
|
|
241
|
+
" API tokens you created for this platform. Revoke them in the Cloudflare dashboard."
|
|
242
|
+
];
|
|
243
|
+
}
|
|
244
|
+
/** Token permissions --purge-resources needs for this manifest. */
|
|
245
|
+
function purgeResourcesPermissions(manifest) {
|
|
246
|
+
const targets = purgeResourcesTargets(manifest);
|
|
247
|
+
const needed = /* @__PURE__ */ new Set();
|
|
248
|
+
for (const target of targets) {
|
|
249
|
+
if (target.phase === "access") {
|
|
250
|
+
needed.add(target.access.kind === "application" ? PERMISSIONS.access : PERMISSIONS.serviceTokens);
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
if (target.phase === "email") {
|
|
254
|
+
needed.add(PERMISSIONS.emailRouting);
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
const { kind } = target.resource;
|
|
258
|
+
if (kind === "worker-route") needed.add(PERMISSIONS.routes);
|
|
259
|
+
else if (kind === "worker" || kind === "worker-custom-domain" || kind === "dispatch-namespace") needed.add(PERMISSIONS.workers);
|
|
260
|
+
else if (kind === "dns-record") needed.add(PERMISSIONS.dns);
|
|
261
|
+
else if (kind === "queue") needed.add(PERMISSIONS.queues);
|
|
262
|
+
else if (kind === "kv-namespace") needed.add(PERMISSIONS.kv);
|
|
263
|
+
else if (kind === "hyperdrive") needed.add(PERMISSIONS.hyperdrive);
|
|
264
|
+
else if (kind === "r2-bucket") needed.add(PERMISSIONS.r2);
|
|
265
|
+
else if (kind === "ai-gateway") needed.add(PERMISSIONS.aiGateway);
|
|
266
|
+
}
|
|
267
|
+
return Object.values(PERMISSIONS).filter((permission) => needed.has(permission));
|
|
268
|
+
}
|
|
269
|
+
function deniedStatus(error) {
|
|
270
|
+
return error instanceof PlatformCloudflareApiError && (error.status === 401 || error.status === 403);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Check resource reads before the first change. Browser login cannot change
|
|
274
|
+
* DNS or Access, so those need an API token. Read probes cannot prove Edit;
|
|
275
|
+
* the plan lists the required permissions.
|
|
276
|
+
*/
|
|
277
|
+
async function checkPurgeResourcesCredentials(client, manifest, credential) {
|
|
278
|
+
const targets = purgeResourcesTargets(manifest);
|
|
279
|
+
const resources = targets.flatMap((target) => "resource" in target ? [target.resource] : []);
|
|
280
|
+
const access = targets.flatMap((target) => "access" in target ? [target.access] : []);
|
|
281
|
+
const has = (kind) => resources.some((resource) => resource.kind === kind);
|
|
282
|
+
const zone = manifest.resources.find((resource) => resource.key === "zone");
|
|
283
|
+
const emailZone = targets.some((target) => target.phase === "email") ? emailRoutingZone(manifest) : null;
|
|
284
|
+
const accounts = [.../* @__PURE__ */ new Set([manifest.account.id, ...access.map((entry) => entry.accountId)])];
|
|
285
|
+
const scope = `${accounts.length === 1 ? "account" : "accounts"} ${accounts.join(" and ")}${has("dns-record") || has("worker-route") ? ` and zone ${zone?.name ?? ""}` : ""}${emailZone ? ` and Email Routing zone ${emailZone}` : ""}`;
|
|
286
|
+
if (credential.source === "oauth") {
|
|
287
|
+
const browserMissing = [
|
|
288
|
+
...has("dns-record") ? [PERMISSIONS.dns] : [],
|
|
289
|
+
...access.some((entry) => entry.kind === "application") ? [PERMISSIONS.access] : [],
|
|
290
|
+
...access.some((entry) => entry.kind === "service-token") ? [PERMISSIONS.serviceTokens] : [],
|
|
291
|
+
...has("ai-gateway") && !credential.aiGatewayToken ? [PERMISSIONS.aiGateway] : []
|
|
292
|
+
];
|
|
293
|
+
if (browserMissing.length) throw new Error(`platform: Cloudflare browser login cannot delete every resource --purge-resources plans. Set CLOUDFLARE_API_TOKEN to a token with ${purgeResourcesPermissions(manifest).join(", ")}, scoped to ${scope}, then rerun. Browser login is missing: ${browserMissing.join(", ")}. No Cloudflare resource was changed.`);
|
|
294
|
+
}
|
|
295
|
+
const probes = [];
|
|
296
|
+
if (has("worker") || has("worker-custom-domain")) probes.push([PERMISSIONS.workers, () => client.listWorkerNames(manifest.account.id)]);
|
|
297
|
+
if (has("worker-custom-domain")) probes.push([PERMISSIONS.workers, () => client.listWorkerDomains(manifest.account.id)]);
|
|
298
|
+
if (has("worker-route") && zone) probes.push([PERMISSIONS.routes, () => client.listWorkerRoutes(zone.id)]);
|
|
299
|
+
for (const resource of resources) if (resource.kind === "dns-record" && zone) probes.push([PERMISSIONS.dns, () => client.listDnsRecords(zone.id, resource.name)]);
|
|
300
|
+
else if (resource.kind === "queue") probes.push([PERMISSIONS.queues, () => client.listQueueConsumers(manifest.account.id, resource.id)]);
|
|
301
|
+
for (const entry of access) probes.push([entry.kind === "application" ? PERMISSIONS.access : PERMISSIONS.serviceTokens, () => client.getAccessResource(entry.accountId, entry.kind, entry.id)]);
|
|
302
|
+
if (emailZone) probes.push([PERMISSIONS.emailRouting, () => client.listEmailRoutingRules(emailZone)]);
|
|
303
|
+
if (has("dispatch-namespace")) probes.push([PERMISSIONS.workers, () => client.listDispatchNamespaces(manifest.account.id)]);
|
|
304
|
+
if (has("kv-namespace")) probes.push([PERMISSIONS.kv, () => client.listKvNamespaces(manifest.account.id)]);
|
|
305
|
+
if (has("hyperdrive")) probes.push([PERMISSIONS.hyperdrive, () => client.listHyperdriveConfigs(manifest.account.id)]);
|
|
306
|
+
if (has("r2-bucket")) probes.push([PERMISSIONS.r2, () => client.listR2Buckets(manifest.account.id)]);
|
|
307
|
+
if (has("ai-gateway")) probes.push([PERMISSIONS.aiGateway, () => client.listAiGateways(manifest.account.id)]);
|
|
308
|
+
const missing = /* @__PURE__ */ new Set();
|
|
309
|
+
for (const [permission, probe] of probes) try {
|
|
310
|
+
await probe();
|
|
311
|
+
} catch (error) {
|
|
312
|
+
if (!deniedStatus(error)) throw error;
|
|
313
|
+
missing.add(permission);
|
|
314
|
+
}
|
|
315
|
+
if (missing.size) throw new Error(`platform: The Cloudflare credential cannot read every resource --purge-resources would delete. Add ${[...missing].join(", ")} for ${scope}, then rerun. No Cloudflare resource was changed.`);
|
|
316
|
+
}
|
|
317
|
+
const LISTED_PROJECTS = 20;
|
|
318
|
+
/**
|
|
319
|
+
* Projects own Workers, storage, and domains that only the running platform
|
|
320
|
+
* can delete. --purge-resources deletes the platform, so it refuses before any
|
|
321
|
+
* change while a project remains.
|
|
322
|
+
*/
|
|
323
|
+
async function assertNoPlatformProjects(read) {
|
|
324
|
+
const slugs = await readPlatformDatabase(read, (reason) => `platform: Refusing --purge-resources because the project list could not be read from the platform database: ${reason}\nMake the installation database reachable (export NOSAM_PLATFORM_DATABASE_URL if this machine has not recorded it), then retry.`);
|
|
325
|
+
if (slugs.length) throw new Error([
|
|
326
|
+
`platform: Refusing --purge-resources while the platform still has ${slugs.length === 1 ? "1 project" : `${slugs.length} projects`}.`,
|
|
327
|
+
"--purge-resources deletes the platform, and only the running platform can delete each project's Workers, storage, and domains.",
|
|
328
|
+
"Delete each project first with `bwf project delete <name>`, then retry:",
|
|
329
|
+
...slugs.slice(0, LISTED_PROJECTS).map((slug) => ` ${slug}`),
|
|
330
|
+
...slugs.length > LISTED_PROJECTS ? [` …and ${slugs.length - LISTED_PROJECTS} more`] : []
|
|
331
|
+
].join("\n"));
|
|
332
|
+
}
|
|
333
|
+
const AI_GATEWAY_CREATION_WINDOW_MS = 6e5;
|
|
334
|
+
/**
|
|
335
|
+
* AI Gateway ids are chosen by the caller and can be reused after a delete,
|
|
336
|
+
* and gateways carry no ownership marker. Only a creation time next to the
|
|
337
|
+
* installer's provision intent shows that this is the gateway it created.
|
|
338
|
+
*/
|
|
339
|
+
function createdDuringInstallation(manifest, resource, createdAt) {
|
|
340
|
+
const created = createdAt === void 0 ? NaN : Date.parse(createdAt);
|
|
341
|
+
if (Number.isNaN(created)) return false;
|
|
342
|
+
return manifest.steps.some((step) => (step.key === `provision-intent:${resource.key}` || step.key.startsWith(`provision-intent:${resource.key}:`)) && Math.abs(created - Date.parse(step.completedAt)) <= AI_GATEWAY_CREATION_WINDOW_MS);
|
|
343
|
+
}
|
|
344
|
+
function ownershipRefusal(manifest, description, reason) {
|
|
345
|
+
return /* @__PURE__ */ new Error(`platform: Refusing to delete ${description} because ${reason}. It may no longer belong to this installation. Delete or fix it in the Cloudflare dashboard if it is yours, then rerun: ${purgeResourcesResumeCommand(manifest)}`);
|
|
346
|
+
}
|
|
347
|
+
function cloudflareRefusal(manifest, description, error, hint) {
|
|
348
|
+
if (!(error instanceof PlatformCloudflareApiError)) return error;
|
|
349
|
+
return new Error(`platform: Cloudflare refused to delete ${description}: ${error.message}\n${hint}\nProgress is saved. Rerun: ${purgeResourcesResumeCommand(manifest)}`, { cause: error });
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Delete every target in order. Returns the manifest with each deleted
|
|
353
|
+
* resource recorded; routing KV is left for the caller to delete last.
|
|
354
|
+
*/
|
|
355
|
+
async function runPurgeResourcesTeardown(context, initial) {
|
|
356
|
+
const { client } = context;
|
|
357
|
+
let next = initial;
|
|
358
|
+
const accountId = next.account.id;
|
|
359
|
+
const save = async (manifest) => {
|
|
360
|
+
next = manifest;
|
|
361
|
+
await context.checkpoint(next);
|
|
362
|
+
};
|
|
363
|
+
const markDeleted = async (key) => {
|
|
364
|
+
const resource = next.resources.find((entry) => entry.key === key);
|
|
365
|
+
await save(recordInstallationResource(next, {
|
|
366
|
+
...resource,
|
|
367
|
+
state: "deleted"
|
|
368
|
+
}, (/* @__PURE__ */ new Date()).toISOString()));
|
|
369
|
+
};
|
|
370
|
+
const recordStep = async (key, resultHash = "completed") => {
|
|
371
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
372
|
+
await save(recordInstallationStep(next, {
|
|
373
|
+
completedAt: now,
|
|
374
|
+
key: `${PURGE_RESOURCES_STEP_PREFIX}${key}`,
|
|
375
|
+
resultHash
|
|
376
|
+
}, now));
|
|
377
|
+
};
|
|
378
|
+
/**
|
|
379
|
+
* Live proof for these keys. A resource an earlier uninstall recorded as
|
|
380
|
+
* retained is proven like a ready one; only its recorded state differs.
|
|
381
|
+
*/
|
|
382
|
+
const verify = (keys) => context.verify({
|
|
383
|
+
...next,
|
|
384
|
+
resources: next.resources.map((resource) => keys.has(resource.key) && resource.state === "retained" ? {
|
|
385
|
+
...resource,
|
|
386
|
+
state: "ready"
|
|
387
|
+
} : resource)
|
|
388
|
+
}, keys);
|
|
389
|
+
/**
|
|
390
|
+
* Prove the resource; false when it is already gone (and recorded).
|
|
391
|
+
*
|
|
392
|
+
* Cloudflare has no conditional DELETE: Workers and dispatch namespaces are
|
|
393
|
+
* addressed by name, and a route or custom domain can be changed in place.
|
|
394
|
+
* Something replaced between this proof and the DELETE can still be removed.
|
|
395
|
+
* That one-request window is accepted because --purge-resources is opt-in and its
|
|
396
|
+
* plan lists every resource first. A forced Worker DELETE has the same
|
|
397
|
+
* window between reading its dependents and the DELETE.
|
|
398
|
+
*/
|
|
399
|
+
const prove = async (resource) => {
|
|
400
|
+
if ((await verify(/* @__PURE__ */ new Set(["routing-kv", resource.key]))).has(resource.key)) {
|
|
401
|
+
await markDeleted(resource.key);
|
|
402
|
+
return false;
|
|
403
|
+
}
|
|
404
|
+
return true;
|
|
405
|
+
};
|
|
406
|
+
/** Keep a resource that no longer matches the record, and save why. */
|
|
407
|
+
const keep = async (key, reason) => {
|
|
408
|
+
const resource = next.resources.find((entry) => entry.key === key);
|
|
409
|
+
if (resource?.state === "ready") await save(recordInstallationResource(next, {
|
|
410
|
+
...resource,
|
|
411
|
+
state: "retained"
|
|
412
|
+
}, (/* @__PURE__ */ new Date()).toISOString()));
|
|
413
|
+
await recordStep(keptStepKey(key), reason);
|
|
414
|
+
};
|
|
415
|
+
const remove = async (resource, hint, zoneId) => {
|
|
416
|
+
if (!await prove(resource)) return;
|
|
417
|
+
try {
|
|
418
|
+
await client.deleteResource(accountId, resource, zoneId);
|
|
419
|
+
} catch (error) {
|
|
420
|
+
throw cloudflareRefusal(next, `${resource.kind} ${resource.name}`, error, hint);
|
|
421
|
+
}
|
|
422
|
+
await markDeleted(resource.key);
|
|
423
|
+
};
|
|
424
|
+
const zone = usableZone(next);
|
|
425
|
+
const createdWorkerNames = new Set(next.resources.filter((resource) => resource.kind === "worker" && resource.ownership === "created").map((resource) => resource.name));
|
|
426
|
+
/** The recorded Worker under this name that this run still deletes, if any. */
|
|
427
|
+
const workerTarget = (name) => next.resources.find((resource) => resource.kind === "worker" && resource.name === name && isPurgeResourcesCandidate(next, resource));
|
|
428
|
+
const workerHint = "A Worker this installation did not create may still use it, for example by sending it logs as a tail Worker or through a service binding. Remove that link in the Cloudflare dashboard.";
|
|
429
|
+
/**
|
|
430
|
+
* Delete a platform Worker. When Cloudflare refuses because other Workers
|
|
431
|
+
* still bind to it, force the DELETE only if each of them is a Worker this
|
|
432
|
+
* run deletes too and still carries this installation's ownership marker.
|
|
433
|
+
*/
|
|
434
|
+
const removeWorker = async (resource) => {
|
|
435
|
+
if (!await prove(resource)) return;
|
|
436
|
+
try {
|
|
437
|
+
await client.deleteResource(accountId, resource);
|
|
438
|
+
} catch (error) {
|
|
439
|
+
if (!(error instanceof PlatformCloudflareApiError)) throw error;
|
|
440
|
+
const dependents = await client.listWorkerDependents(accountId, resource.name).catch(() => null);
|
|
441
|
+
const outside = dependents?.workers.filter((name) => !workerTarget(name)) ?? [];
|
|
442
|
+
const keys = outside.length ? [] : dependents?.workers.map((name) => workerTarget(name).key) ?? [];
|
|
443
|
+
const missing = dependents && !dependents.pagesFunction && keys.length ? await verify(/* @__PURE__ */ new Set(["routing-kv", ...keys])) : null;
|
|
444
|
+
if (!dependents || dependents.pagesFunction || dependents.workers.length === 0 || outside.length > 0 || !missing || keys.some((key) => missing.has(key))) throw cloudflareRefusal(next, `${resource.kind} ${resource.name}`, error, outside.length ? `Workers outside this installation still use it: ${outside.join(", ")}. Remove that link in the Cloudflare dashboard.` : workerHint);
|
|
445
|
+
try {
|
|
446
|
+
await client.forceDeleteWorker(accountId, resource.name);
|
|
447
|
+
} catch (forced) {
|
|
448
|
+
throw cloudflareRefusal(next, `${resource.kind} ${resource.name}`, forced, workerHint);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
await markDeleted(resource.key);
|
|
452
|
+
};
|
|
453
|
+
for (const target of purgeResourcesTargets(initial)) {
|
|
454
|
+
if (target.phase === "access") {
|
|
455
|
+
const { access } = target;
|
|
456
|
+
const live = await client.getAccessResource(access.accountId, access.kind, access.id);
|
|
457
|
+
if (live) {
|
|
458
|
+
if (live.name !== access.name || !(access.name.startsWith(`void-${next.id}-`) || access.name.startsWith(`nosam-${next.id}-`))) {
|
|
459
|
+
await keep(`access:${access.key}`, `its live name ${JSON.stringify(live.name)} is not the name this installation recorded`);
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
try {
|
|
463
|
+
await client.deleteAccessResource(access.accountId, access.kind, access.id);
|
|
464
|
+
} catch (error) {
|
|
465
|
+
throw cloudflareRefusal(next, `Access ${access.kind} ${access.name}`, error, "Check that nothing outside this installation still uses it.");
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
await recordStep(`access:${access.key}`);
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
const current = next.resources.find((resource) => resource.key === target.resource.key);
|
|
472
|
+
if (!current || current.state === "deleted" || purgeResourcesKeptReason(next, current.key) !== null || target.phase !== "traffic" && !isPurgeResourcesCandidate(next, current)) continue;
|
|
473
|
+
switch (target.phase) {
|
|
474
|
+
case "traffic": {
|
|
475
|
+
const worker = next.resources.find((resource) => resource.key === target.worker.key);
|
|
476
|
+
if (!worker || !isPurgeResourcesCandidate(next, worker) || !await prove(worker)) break;
|
|
477
|
+
if (current.kind === "worker-route") {
|
|
478
|
+
const live = (await client.listWorkerRoutes(zone.id)).find((route) => route.id === current.id);
|
|
479
|
+
if (live && (live.pattern !== current.name || live.script !== worker.name)) {
|
|
480
|
+
await keep(current.key, `it now sends ${JSON.stringify(live.pattern)} to ${JSON.stringify(live.script)}`);
|
|
481
|
+
break;
|
|
482
|
+
}
|
|
483
|
+
if (live) await client.deleteWorkerRoute(zone.id, current.id);
|
|
484
|
+
} else {
|
|
485
|
+
const live = (await client.listWorkerDomains(accountId)).find((domain) => domain.id === current.id);
|
|
486
|
+
if (live && (live.hostname !== current.name || live.service !== worker.name)) {
|
|
487
|
+
await keep(current.key, `it now sends ${JSON.stringify(live.hostname)} to ${JSON.stringify(live.service)}`);
|
|
488
|
+
break;
|
|
489
|
+
}
|
|
490
|
+
if (live) await client.deleteWorkerDomain(accountId, current.id);
|
|
491
|
+
}
|
|
492
|
+
await markDeleted(current.key);
|
|
493
|
+
break;
|
|
494
|
+
}
|
|
495
|
+
case "dns":
|
|
496
|
+
try {
|
|
497
|
+
await remove(current, "Check the record in the Cloudflare dashboard.", zone.id);
|
|
498
|
+
} catch (error) {
|
|
499
|
+
if (!(error instanceof PlatformResourceChangedError && error.resourceKey === current.key)) throw error;
|
|
500
|
+
await keep(current.key, error.reason);
|
|
501
|
+
}
|
|
502
|
+
break;
|
|
503
|
+
case "email": {
|
|
504
|
+
if (!await prove(current)) break;
|
|
505
|
+
const zoneId = emailRoutingZone(next);
|
|
506
|
+
const hint = "Check the Email Routing rules for this zone in the Cloudflare dashboard. Never disable Email Routing for the zone.";
|
|
507
|
+
try {
|
|
508
|
+
for (const rule of await client.listEmailRoutingRules(zoneId)) if (rule.workerName === current.name) await client.deleteEmailRoutingRule(zoneId, rule.id);
|
|
509
|
+
if ((await client.getEmailRoutingCatchAll(zoneId))?.workerName === current.name) await client.resetEmailRoutingCatchAll(zoneId);
|
|
510
|
+
} catch (error) {
|
|
511
|
+
throw cloudflareRefusal(next, `Email Routing rules that send mail to ${current.name}`, error, hint);
|
|
512
|
+
}
|
|
513
|
+
await recordStep("email-routing");
|
|
514
|
+
break;
|
|
515
|
+
}
|
|
516
|
+
case "queue-consumers":
|
|
517
|
+
if (!await prove(current)) break;
|
|
518
|
+
for (const consumer of await client.listQueueConsumers(accountId, current.id)) if (consumer.script && createdWorkerNames.has(consumer.script)) await client.deleteQueueConsumer(accountId, current.id, consumer.id);
|
|
519
|
+
await recordStep(`consumers:${current.key}`);
|
|
520
|
+
break;
|
|
521
|
+
case "workers":
|
|
522
|
+
await removeWorker(current);
|
|
523
|
+
break;
|
|
524
|
+
case "tail":
|
|
525
|
+
await remove(current, workerHint);
|
|
526
|
+
break;
|
|
527
|
+
case "queues":
|
|
528
|
+
await remove(current, "A Worker this installation did not create may still use the Queue as a producer or consumer. Remove it from that Worker in the Cloudflare dashboard.");
|
|
529
|
+
break;
|
|
530
|
+
case "dispatch": {
|
|
531
|
+
if (!await prove(current)) break;
|
|
532
|
+
const projects = await context.readProjects();
|
|
533
|
+
if (projects.length) throw new Error(`platform: Stopped before deleting the application Workers in dispatch namespace ${current.name} because ${projects.length === 1 ? "a project was" : "projects were"} created while this uninstall ran: ${projects.join(", ")}. Nothing in the namespace was deleted. --purge-resources refuses while the platform database lists a project. Remove each one from the "projects" table once you have dealt with its Cloudflare resources, then rerun: ${purgeResourcesResumeCommand(next)}`);
|
|
534
|
+
for (const script of await client.listDispatchNamespaceScripts(accountId, current.name)) try {
|
|
535
|
+
await client.deleteDispatchNamespaceScript(accountId, current.name, script);
|
|
536
|
+
} catch (error) {
|
|
537
|
+
throw cloudflareRefusal(next, `application Worker ${script}`, error, workerHint);
|
|
538
|
+
}
|
|
539
|
+
try {
|
|
540
|
+
await client.deleteResource(accountId, current);
|
|
541
|
+
} catch (error) {
|
|
542
|
+
throw cloudflareRefusal(next, `dispatch-namespace ${current.name}`, error, "Check the namespace in the Cloudflare dashboard.");
|
|
543
|
+
}
|
|
544
|
+
await markDeleted(current.key);
|
|
545
|
+
break;
|
|
546
|
+
}
|
|
547
|
+
case "ai-gateway": {
|
|
548
|
+
const live = (await client.listAiGateways(accountId)).find((gateway) => gateway.id === current.id && gateway.name === current.name);
|
|
549
|
+
if (live && !createdDuringInstallation(next, current, live.createdAt)) {
|
|
550
|
+
await keep(current.key, "Cloudflare does not show it was created during installation");
|
|
551
|
+
break;
|
|
552
|
+
}
|
|
553
|
+
await remove(current, "Check that nothing outside this installation still uses it.");
|
|
554
|
+
break;
|
|
555
|
+
}
|
|
556
|
+
case "data":
|
|
557
|
+
await remove(current, "Check that nothing outside this installation still uses it.");
|
|
558
|
+
break;
|
|
559
|
+
case "r2": await purgeBucket(current);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
return next;
|
|
563
|
+
async function purgeBucket(bucket) {
|
|
564
|
+
const markerStep = `r2-marker:${bucket.key}`;
|
|
565
|
+
if (!hasStep(next, markerStep)) {
|
|
566
|
+
if (!await prove(bucket)) return;
|
|
567
|
+
await client.emptyR2Bucket(accountId, bucket.name, /* @__PURE__ */ new Set([PLATFORM_R2_OWNERSHIP_MARKER_KEY]), async () => {
|
|
568
|
+
if ((await verify(/* @__PURE__ */ new Set(["routing-kv", bucket.key]))).has(bucket.key)) throw ownershipRefusal(next, `R2 bucket ${bucket.name}`, "it disappeared while it was being emptied");
|
|
569
|
+
});
|
|
570
|
+
if (!await prove(bucket)) return;
|
|
571
|
+
const generation = await context.bucketGeneration(next, bucket);
|
|
572
|
+
if (generation === null) {
|
|
573
|
+
await markDeleted(bucket.key);
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
await recordStep(markerStep, generation);
|
|
577
|
+
await client.deleteR2Object(accountId, bucket.name, PLATFORM_R2_OWNERSHIP_MARKER_KEY);
|
|
578
|
+
} else {
|
|
579
|
+
const saved = next.steps.find((step) => step.key === `${PURGE_RESOURCES_STEP_PREFIX}${markerStep}`);
|
|
580
|
+
const generation = await context.bucketGeneration(next, bucket);
|
|
581
|
+
if (generation === null) {
|
|
582
|
+
await markDeleted(bucket.key);
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
if (generation !== saved?.resultHash) throw ownershipRefusal(next, `R2 bucket ${bucket.name}`, "its creation fingerprint changed");
|
|
586
|
+
await client.deleteR2Object(accountId, bucket.name, PLATFORM_R2_OWNERSHIP_MARKER_KEY);
|
|
587
|
+
}
|
|
588
|
+
try {
|
|
589
|
+
await client.deleteResource(accountId, bucket);
|
|
590
|
+
} catch (error) {
|
|
591
|
+
throw cloudflareRefusal(next, `r2-bucket ${bucket.name}`, error, "Cloudflare deletes only empty buckets. If objects were added after it was emptied, delete them in the Cloudflare dashboard.");
|
|
592
|
+
}
|
|
593
|
+
await markDeleted(bucket.key);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
// src/cli/platform-management.ts
|
|
597
|
+
async function verifyPlatformInstallationOwnership(client, manifest, options = {}) {
|
|
598
|
+
const ready = manifest.resources.filter((resource) => resource.state === "ready" && isOwnershipVerifiableKind(resource.kind) && !options.retainedReplacementKeys?.has(resource.key));
|
|
599
|
+
if (!ready.find((resource) => resource.key === "routing-kv")) {
|
|
600
|
+
const unsafe = ready.filter((resource) => resource.kind !== "zone");
|
|
601
|
+
if (unsafe.length > 0) throw ownershipError(`the remote installation checkpoint is missing for ${unsafe[0].kind} ${unsafe[0].name}`);
|
|
602
|
+
const zone = ready.find((resource) => resource.kind === "zone");
|
|
603
|
+
if (zone) {
|
|
604
|
+
if ((await client.findZone(manifest.account.id, zone.name))?.id !== zone.id) throw ownershipError(`zone ${zone.name} was replaced`);
|
|
605
|
+
}
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
await verifyPlatformMutationOwnership(client, manifest, new Set(ready.map((resource) => resource.key)), options);
|
|
609
|
+
}
|
|
610
|
+
function selectAuthoritativePlatformManifest(local, authoritative) {
|
|
611
|
+
if (!authoritative) return local;
|
|
612
|
+
if (authoritative.id !== local.id || authoritative.ownershipNonce !== local.ownershipNonce || authoritative.account.id !== local.account.id) throw new Error("platform: The authoritative lifecycle state belongs to another installation.");
|
|
613
|
+
return authoritative;
|
|
614
|
+
}
|
|
615
|
+
function commandArgument(value) {
|
|
616
|
+
return /^[a-zA-Z0-9_./:@-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
|
|
617
|
+
}
|
|
618
|
+
function platformLifecycleResumeCommand(args, installationId) {
|
|
619
|
+
const command = [
|
|
620
|
+
"bwf",
|
|
621
|
+
"platform",
|
|
622
|
+
args.subcommand,
|
|
623
|
+
commandArgument(installationId)
|
|
624
|
+
];
|
|
625
|
+
if (args.runtime) command.push("--runtime", commandArgument(args.runtime));
|
|
626
|
+
if (args.subcommand === "rollback" && args.fromRuntime) command.push("--from-runtime", commandArgument(args.fromRuntime));
|
|
627
|
+
if ("dashboardUrl" in args && args.dashboardUrl) command.push("--dashboard-url", commandArgument(args.dashboardUrl));
|
|
628
|
+
if ("customDomains" in args && args.customDomains) command.push("--custom-domains");
|
|
629
|
+
if ("runtimeLogs" in args && args.runtimeLogs) command.push("--runtime-logs", args.runtimeLogs);
|
|
630
|
+
if ("storageLocation" in args && args.storageLocation) command.push("--storage-location", args.storageLocation);
|
|
631
|
+
if (args.yes) command.push("--yes");
|
|
632
|
+
return command.join(" ");
|
|
633
|
+
}
|
|
634
|
+
async function runInstalledPlatformCommand(args) {
|
|
635
|
+
if (args.subcommand !== "upgrade" && args.subcommand !== "rollback" && args.subcommand !== "repair" && args.subcommand !== "disable" && args.subcommand !== "enable" && args.subcommand !== "uninstall") throw new Error(`platform: Unsupported lifecycle command ${args.subcommand}.`);
|
|
636
|
+
assertNoninteractivePlatformMutationAcknowledged(args, process.stdin.isTTY === true);
|
|
637
|
+
log.step(`Preparing platform ${args.subcommand}`);
|
|
638
|
+
const timingStart = performance.now();
|
|
639
|
+
let timingPrevious = timingStart;
|
|
640
|
+
const markPhase = (phase) => {
|
|
641
|
+
if (process.env.NOSAM_PLATFORM_TIMINGS !== "1") return;
|
|
642
|
+
const current = performance.now();
|
|
643
|
+
process.stderr.write(`[platform timing] phase ${phase} ${(current - timingPrevious).toFixed(0)} ms, total ${(current - timingStart).toFixed(0)} ms\n`);
|
|
644
|
+
timingPrevious = current;
|
|
645
|
+
};
|
|
646
|
+
const manifest = await resolveInstalledPlatformManifest(args.selector);
|
|
647
|
+
const operatorCredential = await resolvePlatformCloudflareCredential({ savedManagementToken: readInstallationRecoverySecrets(manifest)?.managementApiToken });
|
|
648
|
+
const operatorClient = new PlatformCloudflareClient(operatorCredential.token);
|
|
649
|
+
await withPlatformProgress("Checking Cloudflare access", () => verifyPlatformCloudflareCredential(operatorClient, {
|
|
650
|
+
account: manifest.account,
|
|
651
|
+
source: operatorCredential.source,
|
|
652
|
+
r2Buckets: args.subcommand === "disable" || args.subcommand === "uninstall" ? [] : manifest.resources.filter((resource) => resource.kind === "r2-bucket").map((resource) => resource.name),
|
|
653
|
+
allowMissingR2Buckets: args.subcommand === "repair"
|
|
654
|
+
}));
|
|
655
|
+
markPhase("operator credential");
|
|
656
|
+
const runtime = args.subcommand === "uninstall" || args.subcommand === "disable" ? null : loadPlatformRuntime(args.runtime);
|
|
657
|
+
const rollbackSourceRuntime = args.subcommand === "rollback" ? loadPlatformRuntime(args.fromRuntime) : null;
|
|
658
|
+
let progress;
|
|
659
|
+
let reportResult;
|
|
660
|
+
const execute = async (manifest, databaseLock, databaseCheckpointExists = false) => {
|
|
661
|
+
if (args.subcommand === "rollback") assertPlatformRollbackCompatibility(manifest, runtime, rollbackSourceRuntime);
|
|
662
|
+
const recovery = readInstallationRecoverySecrets(manifest);
|
|
663
|
+
const gatewayToken = process.env.NOSAM_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN || recovery?.cloudflareApiToken;
|
|
664
|
+
const client = operatorCredential.source === "oauth" && gatewayToken ? operatorClient.withAiGatewayToken(gatewayToken) : operatorClient;
|
|
665
|
+
const databaseUrl = resolvePlatformInstallDatabaseUrl(recovery, manifest);
|
|
666
|
+
if (args.subcommand === "disable") {
|
|
667
|
+
await disablePlatform(client, manifest, args.plan, {
|
|
668
|
+
checkpoint: databaseLock?.checkpoint,
|
|
669
|
+
databaseUrl
|
|
670
|
+
});
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
if (args.subcommand === "uninstall") {
|
|
674
|
+
const apiUrl = manifest.endpoints.apiUrl;
|
|
675
|
+
const appAccessSetupToken = recovery?.appAccessSetupToken;
|
|
676
|
+
await uninstallPlatform(client, manifest, args, {
|
|
677
|
+
checkpoint: databaseLock?.checkpoint,
|
|
678
|
+
databaseUrl,
|
|
679
|
+
readProjectZeroTrust: databaseLock ? databaseLock.readProjectZeroTrust : () => readPlatformProjectZeroTrustState(databaseUrl, manifest.id, manifest.ownershipNonce),
|
|
680
|
+
lockProjectZeroTrust: databaseLock?.lockProjectZeroTrust,
|
|
681
|
+
fenceProjectZeroTrust: databaseLock?.fenceProjectZeroTrust,
|
|
682
|
+
liftProjectZeroTrustFence: databaseLock?.liftProjectZeroTrustFence,
|
|
683
|
+
readProjects: databaseLock ? databaseLock.readProjects : () => readPlatformProjectSlugs(databaseUrl, manifest.id, manifest.ownershipNonce),
|
|
684
|
+
credential: {
|
|
685
|
+
source: operatorCredential.source,
|
|
686
|
+
aiGatewayToken: !!gatewayToken
|
|
687
|
+
},
|
|
688
|
+
...apiUrl && appAccessSetupToken ? { turnOffProjectZeroTrust: async () => {
|
|
689
|
+
const saved = recovery?.accessCredentialsJson ? JSON.parse(recovery.accessCredentialsJson) : {};
|
|
690
|
+
if (saved && typeof saved === "object" && apiUrl in saved) activatePlatformAccessCredentials(JSON.stringify({ [apiUrl]: saved[apiUrl] }), [apiUrl]);
|
|
691
|
+
if (manifest.deployment.authentication.accessProtection) ensurePlatformAccessToken(apiUrl, false, true);
|
|
692
|
+
await turnOffInstalledProjectZeroTrust({
|
|
693
|
+
apiUrl,
|
|
694
|
+
installationId: manifest.id,
|
|
695
|
+
probeToken: createPlatformHealthProbeToken(manifest.ownershipNonce),
|
|
696
|
+
setupToken: appAccessSetupToken,
|
|
697
|
+
updateCommand: readPendingInstallationSecrets(manifest) ? `bwf platform install --resume --name ${commandArgument(manifest.id)}` : `bwf platform upgrade ${commandArgument(manifest.id)}`
|
|
698
|
+
});
|
|
699
|
+
} } : {}
|
|
700
|
+
});
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
if (args.subcommand === "enable" && manifest.desiredState === "enabled" && manifest.status === "installed") {
|
|
704
|
+
log.info(`${manifest.deployment.displayName} is already enabled.`);
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
const loginFile = args.subcommand === "repair" ? args.authConfig : void 0;
|
|
708
|
+
if (loginFile !== void 0) {
|
|
709
|
+
if (manifest.desiredState === "disabled") throw new Error(`platform: This platform is disabled. Run \`bwf platform enable ${commandArgument(manifest.id)}\` first, then repair to change the login settings.`);
|
|
710
|
+
if (!manifest.deployment.authentication.configurable) throw new Error("platform: This installation signs in with the GitHub OAuth App from its installation settings. Set NOSAM_PLATFORM_GITHUB_CLIENT_ID and NOSAM_PLATFORM_GITHUB_CLIENT_SECRET when running repair to replace it.");
|
|
711
|
+
if (!recovery?.authenticationSetupJson || !recovery.authSetupToken) throw new Error("platform: Changing the login settings needs the setup authority saved on the computer that installed the platform. Run this repair there.");
|
|
712
|
+
await readLoginReplacementFile(loginFile, manifest.deployment.authentication, recovery.authenticationSetupJson);
|
|
713
|
+
}
|
|
714
|
+
const deployment = manifest.deployment;
|
|
715
|
+
const planInput = {
|
|
716
|
+
accountId: manifest.account.id,
|
|
717
|
+
...args.subcommand === "upgrade" && process.env.NOSAM_EMAIL_SHARED_ZONE_ID ? { emailSharedZoneId: process.env.NOSAM_EMAIL_SHARED_ZONE_ID } : {},
|
|
718
|
+
...args.subcommand === "upgrade" && process.env.NOSAM_EMAIL_SENDER_DOMAIN ? { emailSenderDomain: process.env.NOSAM_EMAIL_SENDER_DOMAIN } : {},
|
|
719
|
+
applicationDomain: deployment.application.baseDomain,
|
|
720
|
+
controlPlaneDomain: deployment.controlPlane.apiHostname ?? "",
|
|
721
|
+
...args.subcommand !== "rollback" && args.dashboardUrl !== void 0 ? { dashboardUrl: args.dashboardUrl } : {},
|
|
722
|
+
...args.subcommand !== "rollback" && args.customDomains ? { customDomains: true } : {},
|
|
723
|
+
...args.subcommand === "upgrade" && args.storageLocation !== void 0 ? { storageLocation: args.storageLocation } : {},
|
|
724
|
+
...args.subcommand === "upgrade" && args.runtimeLogs !== void 0 ? { runtimeLogs: args.runtimeLogs } : {},
|
|
725
|
+
dedicatedZone: deployment.application.dedicatedZone,
|
|
726
|
+
displayName: deployment.displayName,
|
|
727
|
+
installationSlug: deployment.installationSlug,
|
|
728
|
+
zoneName: deployment.application.zoneName
|
|
729
|
+
};
|
|
730
|
+
const plan = await withPlatformProgress(`Preparing ${args.subcommand} plan`, () => createPlatformInstallPlan(client, planInput, manifest, {
|
|
731
|
+
authoritativeProvisionIntents: databaseCheckpointExists,
|
|
732
|
+
repairMissing: args.subcommand === "repair",
|
|
733
|
+
allowUnverifiedAiGateway: args.plan,
|
|
734
|
+
includeEmailGateway: runtime.manifest.artifacts.emailGateway !== void 0,
|
|
735
|
+
enableSandbox: runtime.manifest.safetyProtocols.sandboxDrain >= 3,
|
|
736
|
+
deploymentExecution: runtime.manifest.deploymentExecution === 1,
|
|
737
|
+
allowRuntimeLogsChange: args.subcommand === "upgrade",
|
|
738
|
+
allowStorageLocationChange: args.subcommand === "upgrade"
|
|
739
|
+
}));
|
|
740
|
+
assertPlatformRuntimeLogsSupported(plan.deployment, runtime.manifest);
|
|
741
|
+
assertPlatformStorageSupported(plan.deployment, runtime.manifest);
|
|
742
|
+
markPhase("plan");
|
|
743
|
+
note(formatPlatformInstallPlan(plan, manifest.deployment), args.subcommand === "upgrade" ? "Upgrade plan" : args.subcommand === "rollback" ? "Rollback plan" : args.subcommand === "enable" ? "Enable plan" : "Repair plan");
|
|
744
|
+
note([
|
|
745
|
+
`Version: ${manifest.platformVersion} → ${runtime.manifest.platformVersion}`,
|
|
746
|
+
`Source: ${runtime.source}`,
|
|
747
|
+
`Revision: ${runtime.manifest.sourceRevision ?? "not recorded"}`,
|
|
748
|
+
`Manifest SHA-256: ${runtime.manifestSha256}`
|
|
749
|
+
].join("\n"), "Platform runtime");
|
|
750
|
+
log.info(manifest.desiredState === "disabled" && args.subcommand !== "enable" ? "Application traffic will stay paused because this installation is disabled." : "Application traffic may pause briefly during a safe cutover.");
|
|
751
|
+
if (args.plan) {
|
|
752
|
+
if (loginFile !== void 0) log.info(`Login settings will be replaced from ${loginFile}; a new setup code is printed at the end.`);
|
|
753
|
+
const outsideChanges = await findPlatformWorkerOutsideChanges(client, plan, runtime, { manifest });
|
|
754
|
+
if (outsideChanges.length > 0) log.warn(`${formatPlatformWorkerOutsideChanges(outsideChanges)}\nThis command replaces their configuration with the bwf configuration. Run it in a terminal to review them first.`);
|
|
755
|
+
outro("No Cloudflare or local installation state was changed.");
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
assertPlatformOperatorCredentialCanApplyPlan(operatorCredential, plan);
|
|
759
|
+
const repairingMissingRoutingCheckpoint = args.subcommand === "repair" && plan.actions.some((action) => action.key === "routing-kv" && action.action === "create" && action.id === null);
|
|
760
|
+
await verifyPlatformMutationOwnership(client, manifest, new Set(manifest.resources.filter((resource) => isOwnershipVerifiableKind(resource.kind) && !plan.actions.some((action) => action.key === resource.key && action.action === "create" && action.name !== resource.name)).map((resource) => resource.key)), {
|
|
761
|
+
allowMissingRoutingCheckpoint: repairingMissingRoutingCheckpoint,
|
|
762
|
+
allowUninitializedRoutingCheckpoint: args.subcommand === "repair" && databaseCheckpointExists,
|
|
763
|
+
databaseUrl
|
|
764
|
+
});
|
|
765
|
+
markPhase("ownership");
|
|
766
|
+
let replacedLogin;
|
|
767
|
+
if (args.subcommand === "repair" && (loginFile !== void 0 || process.stdin.isTTY && !args.yes) && manifest.desiredState !== "disabled" && manifest.deployment.authentication.configurable && recovery?.authenticationSetupJson && recovery.authSetupToken) {
|
|
768
|
+
const setup = await databaseLock?.readAdministratorSetup?.();
|
|
769
|
+
if (loginFile !== void 0) {
|
|
770
|
+
if (!setup) throw new Error("platform: The database lifecycle lock cannot read the administrator setup.");
|
|
771
|
+
if (setup.usersExist || setup.requestHash !== null && !setup.pending) throw new Error("platform: The first administrator has already signed in. Change login methods with `bwf platform config auth`.");
|
|
772
|
+
if (setup.requestHash === null) throw new Error(`platform: Administrator setup was never started. Resume the install with \`bwf platform install --resume --name ${commandArgument(manifest.id)}\`.`);
|
|
773
|
+
}
|
|
774
|
+
if (setup?.pending && !setup.usersExist && (loginFile !== void 0 || await promptForConfirmation("First administrator setup is not finished. Change the login settings before continuing?", false))) replacedLogin = await replacePendingInstallationAuthentication({
|
|
775
|
+
...loginFile !== void 0 ? { file: loginFile } : {},
|
|
776
|
+
authentication: manifest.deployment.authentication,
|
|
777
|
+
setupJson: recovery.authenticationSetupJson,
|
|
778
|
+
apiUrl: plan.apiUrl
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
const installation = args.subcommand === "enable" ? setInstallationDesiredState(manifest, "enabled", (/* @__PURE__ */ new Date()).toISOString()) : manifest;
|
|
782
|
+
const bootstrapGitHubLogin = process.env.NOSAM_PLATFORM_ADMIN_GITHUB_LOGIN || recovery?.bootstrapGitHubLogin || "";
|
|
783
|
+
const bootstrapGitHubId = process.env.NOSAM_PLATFORM_ADMIN_GITHUB_ID || recovery?.bootstrapGitHubId || (bootstrapGitHubLogin ? await resolveBootstrapGitHubId(bootstrapGitHubLogin) : "");
|
|
784
|
+
const secrets = createPlatformInstallationSecrets({
|
|
785
|
+
bootstrapGitHubId,
|
|
786
|
+
bootstrapGitHubLogin,
|
|
787
|
+
cloudflareApiToken: process.env.NOSAM_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN || "",
|
|
788
|
+
checkpoint: recovery,
|
|
789
|
+
databaseUrl,
|
|
790
|
+
emailEnabled: plan.deployment.capabilities.email,
|
|
791
|
+
emailSigningSecret: process.env.NOSAM_PLATFORM_EMAIL_SIGNING_SECRET || "",
|
|
792
|
+
existingEmailEnabled: manifest.deployment.capabilities.email,
|
|
793
|
+
existingInstallation: true,
|
|
794
|
+
updateExistingWorkers: true,
|
|
795
|
+
githubClientId: process.env.NOSAM_PLATFORM_GITHUB_CLIENT_ID || "",
|
|
796
|
+
githubClientSecret: process.env.NOSAM_PLATFORM_GITHUB_CLIENT_SECRET || "",
|
|
797
|
+
jwtSecret: process.env.NOSAM_PLATFORM_JWT_SECRET || "",
|
|
798
|
+
projectSecretKey: process.env.NOSAM_PLATFORM_PROJECT_SECRET_KEY || "",
|
|
799
|
+
projectSecretKeysJson: process.env.NOSAM_PLATFORM_PROJECT_SECRET_KEYS_JSON || "",
|
|
800
|
+
projectSecretActiveKeyVersion: process.env.NOSAM_PLATFORM_PROJECT_SECRET_ACTIVE_KEY_VERSION || "",
|
|
801
|
+
r2AccessKeyId: process.env.NOSAM_PLATFORM_R2_ACCESS_KEY_ID || "",
|
|
802
|
+
r2SecretAccessKey: process.env.NOSAM_PLATFORM_R2_SECRET_ACCESS_KEY || "",
|
|
803
|
+
...replacedLogin
|
|
804
|
+
});
|
|
805
|
+
const runtimeTokenToPreflight = resolvePlatformRuntimeTokenToPreflight(plan, secrets, { enablingCustomDomains: plan.deployment.capabilities.customDomains && !manifest.deployment.capabilities.customDomains });
|
|
806
|
+
const emailZoneId = installation.desiredState !== "disabled" && plan.deployment.capabilities.email ? plan.deployment.emailSharedZoneId : void 0;
|
|
807
|
+
if (runtimeTokenToPreflight) await verifyPlatformRuntimeTokenPermissions(new PlatformCloudflareClient(runtimeTokenToPreflight), {
|
|
808
|
+
accountId: manifest.account.id,
|
|
809
|
+
applicationDomain: deployment.application.baseDomain,
|
|
810
|
+
customDomains: plan.deployment.capabilities.customDomains,
|
|
811
|
+
...emailZoneId ? { emailZoneId } : {},
|
|
812
|
+
zoneId: plan.zone?.id ?? null
|
|
813
|
+
});
|
|
814
|
+
else if (emailZoneId && secrets.cloudflareApiToken) try {
|
|
815
|
+
await verifyPlatformRuntimeTokenEmailPermissions(new PlatformCloudflareClient(secrets.cloudflareApiToken), {
|
|
816
|
+
accountId: manifest.account.id,
|
|
817
|
+
savedToken: true,
|
|
818
|
+
zoneId: emailZoneId
|
|
819
|
+
});
|
|
820
|
+
} catch (error) {
|
|
821
|
+
if (!(error instanceof PlatformRuntimeTokenEmailPermissionError) || !error.tokenNotValid) throw error;
|
|
822
|
+
log.warn("The runtime API token saved on this machine is not valid (HTTP 401). bwf cannot check the platform email permissions before it changes the platform, and it continues without this check. To do the check, set NOSAM_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN to the runtime token of the platform.");
|
|
823
|
+
}
|
|
824
|
+
markPhase("runtime token");
|
|
825
|
+
if (!databaseLock?.readAuthenticationState) throw new Error("platform: The database lifecycle lock cannot read authoritative authentication settings.");
|
|
826
|
+
const outsideChanges = await reviewPlatformWorkerOutsideChanges({
|
|
827
|
+
client,
|
|
828
|
+
plan,
|
|
829
|
+
runtime,
|
|
830
|
+
installation: {
|
|
831
|
+
manifest: installation,
|
|
832
|
+
readAuthenticationState: databaseLock.readAuthenticationState
|
|
833
|
+
},
|
|
834
|
+
interactive: process.stdin.isTTY === true && process.stdout.isTTY === true && !args.yes,
|
|
835
|
+
command: platformLifecycleResumeCommand({
|
|
836
|
+
...args,
|
|
837
|
+
yes: false
|
|
838
|
+
}, manifest.id),
|
|
839
|
+
accepted: "acceptOutsideChanges" in args && args.acceptOutsideChanges === true
|
|
840
|
+
});
|
|
841
|
+
markPhase("outside changes");
|
|
842
|
+
progress = createPlatformProgress();
|
|
843
|
+
progress.start(args.subcommand === "upgrade" ? "Upgrading the platform" : args.subcommand === "rollback" ? "Rolling back the platform" : args.subcommand === "enable" ? "Enabling the platform" : "Repairing the platform");
|
|
844
|
+
if (installation !== manifest) writeInstallationManifest(installation);
|
|
845
|
+
const keepAcceptedLogin = async (error) => {
|
|
846
|
+
const after = replacedLogin ? await databaseLock?.readAdministratorSetup?.().catch(() => void 0) : void 0;
|
|
847
|
+
if (!after || !recovery?.authenticationSetupJson || after.requestHash !== authenticationSetupRequestHash(recovery.authenticationSetupJson) || !after.usersExist && after.pending) return error;
|
|
848
|
+
const pending = readPendingInstallationSecrets(installation);
|
|
849
|
+
if (pending) writePendingInstallationSecrets(installation, {
|
|
850
|
+
...pending,
|
|
851
|
+
authenticationSetupJson: recovery.authenticationSetupJson,
|
|
852
|
+
...recovery.authBootstrapCode ? { authBootstrapCode: recovery.authBootstrapCode } : {}
|
|
853
|
+
});
|
|
854
|
+
return new Error("platform: The first administrator signed in before the new login settings were applied. Nothing changed. Change login methods with `bwf platform config auth`.", { cause: error });
|
|
855
|
+
};
|
|
856
|
+
const result = await installPlatform(plan, secrets, installation, {
|
|
857
|
+
acquireDatabaseLifecycleLock: async () => Object.assign(async () => {}, {
|
|
858
|
+
checkpoint: databaseLock?.checkpoint,
|
|
859
|
+
liftProjectZeroTrustFence: databaseLock?.liftProjectZeroTrustFence,
|
|
860
|
+
prepareDatabase: databaseLock?.prepareDatabase,
|
|
861
|
+
prepareSandboxDrain: databaseLock?.prepareSandboxDrain,
|
|
862
|
+
publishAiLogging: databaseLock?.publishAiLogging,
|
|
863
|
+
readAuthenticationState: databaseLock?.readAuthenticationState,
|
|
864
|
+
requiredSafetyProtocols: databaseLock?.requiredSafetyProtocols,
|
|
865
|
+
verifyDatabase: databaseLock?.verifyDatabase
|
|
866
|
+
}),
|
|
867
|
+
client,
|
|
868
|
+
operatorApiToken: operatorCredential.token,
|
|
869
|
+
...outsideChanges.length > 0 ? {
|
|
870
|
+
replaceOutsideChanges: outsideChanges.map((change) => change.name),
|
|
871
|
+
uploadOutsideChanges: (configs) => uploadPlatformWorkerOutsideChanges(configs, {
|
|
872
|
+
changes: outsideChanges,
|
|
873
|
+
client,
|
|
874
|
+
operatorApiToken: operatorCredential.token,
|
|
875
|
+
progress,
|
|
876
|
+
accepted: "acceptOutsideChanges" in args && args.acceptOutsideChanges === true
|
|
877
|
+
})
|
|
878
|
+
} : {},
|
|
879
|
+
databaseRollbackSource: rollbackSourceRuntime ?? void 0,
|
|
880
|
+
onProgress: (message) => {
|
|
881
|
+
markPhase(message);
|
|
882
|
+
progress?.message(message);
|
|
883
|
+
},
|
|
884
|
+
runtime,
|
|
885
|
+
operation: args.subcommand,
|
|
886
|
+
replanWorkers: async (recoveryManifest) => (await createPlatformInstallPlan(client, planInput, recoveryManifest, {
|
|
887
|
+
allowRuntimeLogsChange: args.subcommand === "upgrade",
|
|
888
|
+
authoritativeProvisionIntents: true,
|
|
889
|
+
repairMissing: true,
|
|
890
|
+
includeEmailGateway: runtime.manifest.artifacts.emailGateway !== void 0,
|
|
891
|
+
enableSandbox: runtime.manifest.safetyProtocols.sandboxDrain >= 3,
|
|
892
|
+
deploymentExecution: runtime.manifest.deploymentExecution === 1
|
|
893
|
+
})).actions.filter((action) => action.kind === "worker"),
|
|
894
|
+
revalidateBeforeWorkerDeploy: (manifest, action) => revalidatePlatformInstallAction(client, plan, manifest, action, {
|
|
895
|
+
repairMissing: args.subcommand === "repair",
|
|
896
|
+
stableWorkerUpdate: args.subcommand === "upgrade"
|
|
897
|
+
})
|
|
898
|
+
}).catch(async (error) => {
|
|
899
|
+
throw await keepAcceptedLogin(error);
|
|
900
|
+
});
|
|
901
|
+
progress.message("Finalizing platform changes");
|
|
902
|
+
markPhase("installer complete");
|
|
903
|
+
const runtimeLogsWarning = !result.waitingForDns && !result.waitingForSandboxDrain && shouldUpdateProjectWorkerRuntimeLogs({
|
|
904
|
+
previous: manifest.deployment,
|
|
905
|
+
next: result.manifest.deployment,
|
|
906
|
+
explicit: args.subcommand === "upgrade" && args.runtimeLogs !== void 0
|
|
907
|
+
}) ? await updateProjectWorkerRuntimeLogs(client, {
|
|
908
|
+
accountId: manifest.account.id,
|
|
909
|
+
namespace: result.manifest.deployment.resources.dispatchNamespace,
|
|
910
|
+
minimal: !!result.manifest.deployment.runtimeLogs,
|
|
911
|
+
installationId: manifest.id
|
|
912
|
+
}) : void 0;
|
|
913
|
+
reportResult = () => {
|
|
914
|
+
progress?.stop(result.waitingForDns || result.waitingForSandboxDrain ? "Platform operation paused; progress is saved." : `Platform ${args.subcommand} complete.`);
|
|
915
|
+
progress = void 0;
|
|
916
|
+
if (result.waitingForDns) {
|
|
917
|
+
note(`Wait for ${deployment.application.zoneName} to become active, then resume:\n${platformLifecycleResumeCommand(args, manifest.id)}`, "Waiting for nameservers");
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
if (result.waitingForSandboxDrain) {
|
|
921
|
+
note([
|
|
922
|
+
"Application traffic is paused. Saved progress is ready to resume.",
|
|
923
|
+
"1. Review remaining Sandbox work: bwf platform system sandbox-drain --plan",
|
|
924
|
+
"2. Apply: bwf platform system sandbox-drain --yes (follow nextCursor with --cursor '<value>' until complete: true).",
|
|
925
|
+
`3. Resume: ${platformLifecycleResumeCommand(args, manifest.id)}`,
|
|
926
|
+
`Administrator status: ${plan.apiUrl}/admin/status`
|
|
927
|
+
].join("\n"), "Waiting for managed Sandbox drain");
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
930
|
+
log.info(result.manifest.desiredState === "disabled" ? "Application traffic remains paused. Enable the installation when you are ready." : `Platform verification passed. Traffic is enabled at ${plan.apiUrl}.`);
|
|
931
|
+
if (args.subcommand === "rollback") log.info("PostgreSQL migrations were retained; rollback changes the runtime only.");
|
|
932
|
+
if (result.emailOperationId) log.info(`Shared email routing ready (operation ${result.emailOperationId}).`);
|
|
933
|
+
if (result.setupPending) {
|
|
934
|
+
const code = readInstallationRecoverySecrets(result.manifest)?.authBootstrapCode;
|
|
935
|
+
if (code) {
|
|
936
|
+
log.info(`First administrator setup: ${formatUrl(`${plan.apiUrl}/setup`)}`);
|
|
937
|
+
console.log(`One-time administrator setup code: ${code}`);
|
|
938
|
+
log.info(`Login callback URL: ${formatUrl(`${plan.apiUrl}/auth/callback`)}`);
|
|
939
|
+
log.info(`If sign-in fails, run \`bwf platform repair ${commandArgument(manifest.id)}\` to change the login settings.`);
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
if (runtimeLogsWarning) log.warn(runtimeLogsWarning);
|
|
943
|
+
printSuccess(`${deployment.displayName}: runtime ${runtime.manifest.platformVersion} ${args.subcommand === "rollback" ? "restored" : "ready"}.`);
|
|
944
|
+
};
|
|
945
|
+
};
|
|
946
|
+
if (args.plan) {
|
|
947
|
+
await execute(manifest);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
const release = acquirePlatformLifecycleLock(manifest.account.id, manifest.deployment.installationSlug);
|
|
951
|
+
try {
|
|
952
|
+
const current = resolveInstallationManifest(manifest.id);
|
|
953
|
+
const recovery = readInstallationRecoverySecrets(current);
|
|
954
|
+
const databaseUrl = resolvePlatformInstallDatabaseUrl(recovery, current);
|
|
955
|
+
if (!databaseUrl) throw new Error("platform: DATABASE_URL is required to safely serialize lifecycle changes across hosts.");
|
|
956
|
+
const releaseDatabase = await withPlatformProgress("Reading platform state", () => acquirePlatformDatabaseLifecycleLock(databaseUrl, current.id, current.ownershipNonce));
|
|
957
|
+
markPhase("database lock");
|
|
958
|
+
try {
|
|
959
|
+
const authoritative = releaseDatabase.authoritativeManifest;
|
|
960
|
+
const databaseCheckpointExists = authoritative !== null && authoritative !== void 0;
|
|
961
|
+
const currentManifest = selectAuthoritativePlatformManifest(current, authoritative);
|
|
962
|
+
if (authoritative && JSON.stringify(authoritative) !== JSON.stringify(current)) writeInstallationManifest(authoritative);
|
|
963
|
+
if (!authoritative) await releaseDatabase.checkpoint?.(currentManifest);
|
|
964
|
+
await execute(currentManifest, releaseDatabase, databaseCheckpointExists);
|
|
965
|
+
} finally {
|
|
966
|
+
await releaseDatabase();
|
|
967
|
+
}
|
|
968
|
+
reportResult?.();
|
|
969
|
+
markPhase("complete");
|
|
970
|
+
} catch (error) {
|
|
971
|
+
const operationStarted = progress !== void 0;
|
|
972
|
+
progress?.error(`Platform ${args.subcommand} failed.`);
|
|
973
|
+
progress = void 0;
|
|
974
|
+
if (operationStarted && args.subcommand !== "uninstall" && args.subcommand !== "disable") note([
|
|
975
|
+
"Traffic may remain paused. Inspect the saved state before continuing:",
|
|
976
|
+
`bwf platform status ${commandArgument(manifest.id)}`,
|
|
977
|
+
"After resolving the error, resume with the same runtime:",
|
|
978
|
+
platformLifecycleResumeCommand(args, manifest.id)
|
|
979
|
+
].join("\n"), "Recovery");
|
|
980
|
+
throw error;
|
|
981
|
+
} finally {
|
|
982
|
+
try {
|
|
983
|
+
progress?.clear();
|
|
984
|
+
} finally {
|
|
985
|
+
release();
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
function assertPlatformRollbackCompatibility(installation, target, source) {
|
|
990
|
+
if (target.manifest.emailProtocolVersion !== 1 && (installation.deployment.capabilities.email || installation.resources.some((resource) => resource.key === "email-gateway-worker" && resource.state === "ready"))) throw new Error("platform: The rollback target predates the email gateway and cannot safely replace this installation. Use a runtime with email protocol version 1.");
|
|
991
|
+
assertPlatformStorageSupported(installation.deployment, target.manifest);
|
|
992
|
+
if (installation.deployment.runtimeLogs && target.manifest.runtimeLogs !== 1) throw new Error("platform: The rollback target cannot keep runtime logs minimal. Run `bwf platform upgrade --runtime-logs full` first, then roll back.");
|
|
993
|
+
if (!installation.runtime) throw new Error("platform: The installed runtime has no artifact provenance, so post-success rollback cannot identify its compatibility manifest.");
|
|
994
|
+
if (source.manifest.platformVersion !== installation.platformVersion || source.manifestSha256 !== installation.runtime.manifestSha256) throw new Error("platform: --from-runtime does not exactly match the installed runtime artifact digest. Supply the runtime used by the current successful deployment.");
|
|
995
|
+
if (target.manifestSha256 === source.manifestSha256) throw new Error("platform: The rollback target is already the installed runtime artifact.");
|
|
996
|
+
if ((target.manifest.authenticationProtocolVersion ?? 0) < Math.max(source.manifest.authenticationProtocolVersion ?? 0, installation.deployment.authentication.configurable ? 1 : 0)) throw new Error("platform: The rollback target cannot enforce the installed authentication configuration and session revocation protocol. Use a compatible runtime.");
|
|
997
|
+
if (Math.max(installation.usageProtocolVersion, source.manifest.usageProtocolVersion) >= 2 && target.manifest.usageProtocolVersion < 2) throw new Error("platform: The rollback target predates ownership-aware usage attribution and cannot safely account for transferred projects. Use a runtime with usage protocol version 2 or newer.");
|
|
998
|
+
if (target.manifest.database.lineage !== source.manifest.database.lineage) throw new Error("platform: The rollback target belongs to a different database lineage.");
|
|
999
|
+
const prefix = source.manifest.database.migrations.slice(0, target.manifest.database.migrations.length);
|
|
1000
|
+
if (JSON.stringify(prefix) !== JSON.stringify(target.manifest.database.migrations)) throw new Error("platform: The rollback target database migrations are not an exact prefix of the installed runtime.");
|
|
1001
|
+
if (!source.manifest.database.rollbackSafeFrom.some((entry) => entry.platformVersion === target.manifest.platformVersion && entry.schemaDigest === target.manifest.database.schemaDigest)) throw new Error(`platform: Installed runtime ${source.manifest.platformVersion} does not declare post-success rollback compatibility with ${target.manifest.platformVersion} at schema ${target.manifest.database.schemaDigest}.`);
|
|
1002
|
+
if (installation.databaseSchemaDigest !== source.manifest.database.schemaDigest) throw new Error("platform: The authoritative installation checkpoint does not record the installed runtime database schema. Repair or roll forward before rollback.");
|
|
1003
|
+
if (target.manifest.safetyProtocols.sandboxDrain < installation.safetyProtocols.sandboxDrain) throw new Error("platform: The rollback target predates the installed sandbox-drain safety protocol.");
|
|
1004
|
+
}
|
|
1005
|
+
function resolvePlatformRuntimeTokenToPreflight(plan, secrets, options = {}) {
|
|
1006
|
+
const explicitUpdate = secrets.workerSecretUpdates?.CF_API_TOKEN;
|
|
1007
|
+
if (explicitUpdate) return explicitUpdate;
|
|
1008
|
+
if (options.enablingCustomDomains) {
|
|
1009
|
+
if (!secrets.cloudflareApiToken) throw new Error("platform: Before enabling project custom domains, set NOSAM_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN to the platform runtime token with Zone → SSL and Certificates → Edit on the application zone so bwf can check its access.");
|
|
1010
|
+
return secrets.cloudflareApiToken;
|
|
1011
|
+
}
|
|
1012
|
+
return plan.actions.some((action) => action.kind === "worker" && action.action === "create" && (action.key === "api-worker" || action.key === "proxy-worker")) ? secrets.cloudflareApiToken : "";
|
|
1013
|
+
}
|
|
1014
|
+
async function resolveInstalledPlatformManifest(selector, dependencies = {}) {
|
|
1015
|
+
if (selector) return resolveInstallationManifest(selector);
|
|
1016
|
+
const manifests = listInstallationManifests().filter((manifest) => manifest.status !== "uninstalled");
|
|
1017
|
+
if (manifests.length <= 1) return resolveInstallationManifest("");
|
|
1018
|
+
if (!(dependencies.interactive ?? process.stdin.isTTY)) throw new Error("platform: Multiple local installations exist; specify an installation id.");
|
|
1019
|
+
const picked = dependencies.selectInstallation ? await dependencies.selectInstallation(manifests) : await select({
|
|
1020
|
+
message: "Select an installed bwf platform:",
|
|
1021
|
+
options: manifests.map((manifest) => ({
|
|
1022
|
+
hint: `${manifest.account.name} · ${manifest.id}`,
|
|
1023
|
+
label: manifest.deployment.displayName,
|
|
1024
|
+
value: manifest.id
|
|
1025
|
+
}))
|
|
1026
|
+
});
|
|
1027
|
+
if (isCancel(picked)) throw new Error("platform: Cancelled.");
|
|
1028
|
+
return resolveInstallationManifest(String(picked));
|
|
1029
|
+
}
|
|
1030
|
+
async function disablePlatform(client, initialManifest, planOnly, dependencies = {}) {
|
|
1031
|
+
const manifest = await withPlatformProgress("Reading platform resources", () => recoverDurablyMarkedProvisionIntents(client, initialManifest));
|
|
1032
|
+
const saveCheckpoint = (state) => writeLifecycleCheckpoint(client, state, dependencies.checkpoint);
|
|
1033
|
+
const saveRemoteManifest = (state) => writeRemoteManifest(client, state, dependencies.checkpoint);
|
|
1034
|
+
note("Block all platform traffic and the platform API. Routes, custom domains, Workers, and data stay installed.", "Disable plan");
|
|
1035
|
+
if (planOnly) {
|
|
1036
|
+
outro("No Cloudflare or local installation state was changed.");
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
if (manifest !== initialManifest) writeInstallationManifest(manifest);
|
|
1040
|
+
const alreadyDisabled = manifest.status === "disabled";
|
|
1041
|
+
await verifyPlatformMutationOwnership(client, manifest, /* @__PURE__ */ new Set([
|
|
1042
|
+
"routing-kv",
|
|
1043
|
+
"zone",
|
|
1044
|
+
...manifest.resources.filter((resource) => resource.kind === "worker").map((resource) => resource.key)
|
|
1045
|
+
]), { databaseUrl: dependencies.databaseUrl });
|
|
1046
|
+
let next = setInstallationDesiredState(manifest, "disabled", (/* @__PURE__ */ new Date()).toISOString());
|
|
1047
|
+
writeInstallationManifest(next);
|
|
1048
|
+
if (!alreadyDisabled) {
|
|
1049
|
+
next = transitionInstallation(next, "disabling", (/* @__PURE__ */ new Date()).toISOString());
|
|
1050
|
+
writeInstallationManifest(next);
|
|
1051
|
+
}
|
|
1052
|
+
try {
|
|
1053
|
+
await saveRemoteManifest(next);
|
|
1054
|
+
const routing = requireResource(next, "routing-kv");
|
|
1055
|
+
const trafficGeneration = currentTrafficGeneration(next);
|
|
1056
|
+
await client.putKvValue(next.account.id, routing.id, PLATFORM_DISABLED_KEY, PLATFORM_DISABLED_VALUE);
|
|
1057
|
+
next = markTrafficAttachmentsRetained(next);
|
|
1058
|
+
if (!hasLifecycleStep(next, `disable:${trafficGeneration}:routes`)) next = recordLifecycleStep(next, `disable:${trafficGeneration}:routes`);
|
|
1059
|
+
await saveCheckpoint(next);
|
|
1060
|
+
next = transitionInstallation(next, "disabled", (/* @__PURE__ */ new Date()).toISOString());
|
|
1061
|
+
await saveCheckpoint(next);
|
|
1062
|
+
printSuccess(`${next.deployment.displayName} is disabled. Its data was not changed.`);
|
|
1063
|
+
} catch (error) {
|
|
1064
|
+
next = transitionInstallation(next, "failed", (/* @__PURE__ */ new Date()).toISOString());
|
|
1065
|
+
writeInstallationManifest(next);
|
|
1066
|
+
await saveRemoteManifest(next).catch(() => {});
|
|
1067
|
+
throw error;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
async function uninstallPlatform(client, initialManifest, args, dependencies = {}) {
|
|
1071
|
+
const manifest = await withPlatformProgress("Reading platform resources", () => recoverDurablyMarkedProvisionIntents(client, initialManifest));
|
|
1072
|
+
const saveCheckpoint = (state) => writeLifecycleCheckpoint(client, state, dependencies.checkpoint);
|
|
1073
|
+
const saveRemoteManifest = (state) => writeRemoteManifest(client, state, dependencies.checkpoint);
|
|
1074
|
+
const retainData = !args.purgeData;
|
|
1075
|
+
const purgeResources = args.purgeResources;
|
|
1076
|
+
const routingKv = manifest.resources.find((resource) => resource.key === "routing-kv");
|
|
1077
|
+
const reopenedRouting = purgeResources && routingKv?.state === "retained" && isPurgeResourcesCandidate(manifest, routingKv);
|
|
1078
|
+
const hasRoutingCheckpoint = routingKv?.state === "ready" || reopenedRouting;
|
|
1079
|
+
const interactive = dependencies.interactive ?? process.stdin.isTTY;
|
|
1080
|
+
const confirmAction = dependencies.confirm ?? promptForConfirmation;
|
|
1081
|
+
const zeroTrust = await withPlatformProgress("Checking project access", () => assertProjectZeroTrustAllowsUninstall(dependencies.readProjectZeroTrust, { canTurnOff: !!dependencies.turnOffProjectZeroTrust }));
|
|
1082
|
+
if (purgeResources) await withPlatformProgress("Checking platform projects", () => assertNoPlatformProjects(dependencies.readProjects));
|
|
1083
|
+
if (args.plan || interactive && !args.yes) note([...zeroTrust ? zeroTrust.turnOff.length ? ["Turn off project Zero Trust; no platform user exists yet. Delete its Access applications:", formatZeroTrustApplications(zeroTrust.turnOff)] : ["Turn off project Zero Trust; no platform user exists yet."] : [], purgeResources ? purgeResourcesPlanText(manifest) : [
|
|
1084
|
+
"Disable platform traffic.",
|
|
1085
|
+
retainData ? "Keep Workers and data." : "Delete eligible data; keep Workers, R2, and AI Gateway.",
|
|
1086
|
+
"Delete unused Queues.",
|
|
1087
|
+
...describeKeptResources(manifest, plannedKeptResources(manifest, retainData, hasRoutingCheckpoint), "Keep for manual cleanup:", "Keep Access resources:")
|
|
1088
|
+
].join("\n")].join("\n"), import_picocolors.default.bold("Uninstall plan"));
|
|
1089
|
+
if (purgeResources) {
|
|
1090
|
+
const credentialCheck = checkPurgeResourcesCredentials(client, manifest, dependencies.credential ?? {
|
|
1091
|
+
source: "environment",
|
|
1092
|
+
aiGatewayToken: false
|
|
1093
|
+
});
|
|
1094
|
+
if (args.plan) await credentialCheck.catch((error) => {
|
|
1095
|
+
log.warn(error instanceof Error ? error.message : String(error));
|
|
1096
|
+
});
|
|
1097
|
+
else await credentialCheck;
|
|
1098
|
+
}
|
|
1099
|
+
if (args.plan) {
|
|
1100
|
+
outro("No Cloudflare or local installation state was changed.");
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
if (manifest !== initialManifest) writeInstallationManifest(manifest);
|
|
1104
|
+
if (interactive && !args.yes) {
|
|
1105
|
+
if (!await confirmAction(purgeResources ? "Permanently delete every Cloudflare resource this installation created?" : args.purgeData ? "Permanently purge installer-owned platform data?" : "Uninstall this platform?", false)) {
|
|
1106
|
+
outro("No changes made.");
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
log.step(`Uninstalling ${manifest.deployment.displayName}...`);
|
|
1111
|
+
const purgeResourcesKept = new Set(purgeResources ? purgeResourcesKeptResources(manifest).map((resource) => resource.key) : []);
|
|
1112
|
+
const resourcesToDelete = new Set(manifest.resources.filter((resource) => (shouldDeleteResource(resource, retainData) || purgeResources && (resource.state === "ready" || isPurgeResourcesCandidate(manifest, resource)) && !purgeResourcesKept.has(resource.key) && isOwnershipVerifiableKind(resource.kind) && resource.kind !== "dns-record" && !hasLifecycleStep(manifest, `uninstall:purge-resources:r2-marker:${resource.key}`)) && (hasRoutingCheckpoint || resource.kind === "zone") && !(resource.kind === "dns-record" && !manifest.resources.some((entry) => entry.key === "zone"))).map((resource) => resource.key));
|
|
1113
|
+
const ownershipTargets = /* @__PURE__ */ new Set([
|
|
1114
|
+
...hasRoutingCheckpoint ? ["routing-kv"] : [],
|
|
1115
|
+
"zone",
|
|
1116
|
+
...manifest.resources.filter((resource) => resource.kind === "worker").map((resource) => resource.key),
|
|
1117
|
+
...resourcesToDelete
|
|
1118
|
+
]);
|
|
1119
|
+
const proofManifest = {
|
|
1120
|
+
...manifest,
|
|
1121
|
+
resources: manifest.resources.map((resource) => resource.state === "retained" && resourcesToDelete.has(resource.key) ? {
|
|
1122
|
+
...resource,
|
|
1123
|
+
state: "ready"
|
|
1124
|
+
} : resource)
|
|
1125
|
+
};
|
|
1126
|
+
let missingResources;
|
|
1127
|
+
if (hasRoutingCheckpoint) missingResources = await verifyPlatformMutationOwnership(client, proofManifest, ownershipTargets, {
|
|
1128
|
+
allowDeletedRoutingCheckpoint: args.purgeData,
|
|
1129
|
+
databaseUrl: dependencies.databaseUrl
|
|
1130
|
+
});
|
|
1131
|
+
else {
|
|
1132
|
+
await verifyPlatformInstallationOwnership(client, manifest, { databaseUrl: dependencies.databaseUrl });
|
|
1133
|
+
missingResources = /* @__PURE__ */ new Set();
|
|
1134
|
+
}
|
|
1135
|
+
const { fenceProjectZeroTrust, liftProjectZeroTrustFence, lockProjectZeroTrust } = dependencies;
|
|
1136
|
+
if (!lockProjectZeroTrust || !fenceProjectZeroTrust || !liftProjectZeroTrustFence) throw new Error("platform: Refusing to uninstall because no platform database connection is available to hold off project Zero Trust changes.");
|
|
1137
|
+
if (zeroTrust) {
|
|
1138
|
+
log.step("Turning off project Zero Trust");
|
|
1139
|
+
await dependencies.turnOffProjectZeroTrust();
|
|
1140
|
+
}
|
|
1141
|
+
const releaseProjectZeroTrust = await lockProjectZeroTrust();
|
|
1142
|
+
let fenced = false;
|
|
1143
|
+
let disablingTraffic = false;
|
|
1144
|
+
const stopProjectZeroTrustHold = async () => {
|
|
1145
|
+
if (fenced && !disablingTraffic) await liftProjectZeroTrustFence().catch((error) => {
|
|
1146
|
+
log.warn(`Could not reopen project Zero Trust changes after the uninstall stopped: ${error instanceof Error ? error.message : String(error)}\nRun \`bwf platform uninstall\` again, or \`bwf platform repair\` to keep the platform.`);
|
|
1147
|
+
});
|
|
1148
|
+
await releaseProjectZeroTrust();
|
|
1149
|
+
};
|
|
1150
|
+
let next = manifest;
|
|
1151
|
+
try {
|
|
1152
|
+
await assertProjectZeroTrustAllowsUninstall(dependencies.readProjectZeroTrust);
|
|
1153
|
+
if (purgeResources) await assertNoPlatformProjects(dependencies.readProjects);
|
|
1154
|
+
fenced = true;
|
|
1155
|
+
await fenceProjectZeroTrust();
|
|
1156
|
+
next = transitionInstallation(manifest, "uninstalling", (/* @__PURE__ */ new Date()).toISOString());
|
|
1157
|
+
writeInstallationManifest(next);
|
|
1158
|
+
} catch (error) {
|
|
1159
|
+
await stopProjectZeroTrustHold();
|
|
1160
|
+
throw error;
|
|
1161
|
+
}
|
|
1162
|
+
try {
|
|
1163
|
+
await saveRemoteManifest(next);
|
|
1164
|
+
const routing = hasRoutingCheckpoint ? requireResource(next, "routing-kv") : void 0;
|
|
1165
|
+
disablingTraffic = true;
|
|
1166
|
+
if (routing) await client.putKvValue(next.account.id, routing.id, PLATFORM_DISABLED_KEY, PLATFORM_DISABLED_VALUE);
|
|
1167
|
+
await releaseProjectZeroTrust();
|
|
1168
|
+
for (const key of missingResources) {
|
|
1169
|
+
const resource = requireResource(next, key);
|
|
1170
|
+
next = updateResourceState(next, key, resource.ownership === "created" ? "deleted" : "retained");
|
|
1171
|
+
await saveCheckpoint(next);
|
|
1172
|
+
}
|
|
1173
|
+
const workers = new Set(next.resources.filter((resource) => resource.kind === "worker" && resource.state === "ready").map((resource) => resource.name));
|
|
1174
|
+
const zone = next.resources.find((resource) => resource.key === "zone");
|
|
1175
|
+
if (zone?.state === "ready") {
|
|
1176
|
+
for (const worker of next.resources.filter((resource) => resource.kind === "worker" && resource.state === "ready" && workers.has(resource.name))) if (!(await verifyPlatformMutationOwnership(client, next, /* @__PURE__ */ new Set([
|
|
1177
|
+
"routing-kv",
|
|
1178
|
+
"zone",
|
|
1179
|
+
worker.key
|
|
1180
|
+
]), { databaseUrl: dependencies.databaseUrl })).has(worker.key)) {
|
|
1181
|
+
next = markTrafficAttachmentsRetained(next);
|
|
1182
|
+
next = recordLifecycleStep(next, `uninstall:routes:${worker.key}`);
|
|
1183
|
+
await saveCheckpoint(next);
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
if (purgeResources && hasRoutingCheckpoint) next = await runPurgeResourcesTeardown({
|
|
1187
|
+
client,
|
|
1188
|
+
checkpoint: async (checkpointManifest) => {
|
|
1189
|
+
next = checkpointManifest;
|
|
1190
|
+
await saveCheckpoint(checkpointManifest);
|
|
1191
|
+
},
|
|
1192
|
+
verify: (checkpointManifest, keys) => verifyPlatformMutationOwnership(client, checkpointManifest, keys, {
|
|
1193
|
+
allowDeletedRoutingCheckpoint: true,
|
|
1194
|
+
databaseUrl: dependencies.databaseUrl
|
|
1195
|
+
}),
|
|
1196
|
+
bucketGeneration: async (checkpointManifest, bucket) => {
|
|
1197
|
+
const live = (await client.listR2Buckets(checkpointManifest.account.id)).find((entry) => entry.id === bucket.id && entry.name === bucket.name);
|
|
1198
|
+
if (!live) return null;
|
|
1199
|
+
return live.fingerprint === void 0 ? "unknown" : r2BucketConfigHash(bucket.name, live.fingerprint);
|
|
1200
|
+
},
|
|
1201
|
+
readProjects: () => dependencies.readProjects()
|
|
1202
|
+
}, next);
|
|
1203
|
+
const deletionPriority = {
|
|
1204
|
+
worker: 0,
|
|
1205
|
+
queue: 1,
|
|
1206
|
+
"ai-gateway": 2,
|
|
1207
|
+
"dns-record": 3,
|
|
1208
|
+
"dispatch-namespace": 4,
|
|
1209
|
+
hyperdrive: 5,
|
|
1210
|
+
"kv-namespace": 6,
|
|
1211
|
+
"r2-bucket": 7,
|
|
1212
|
+
zone: 8
|
|
1213
|
+
};
|
|
1214
|
+
const resources = [...next.resources].sort((left, right) => resourceDeletionPriority(left, deletionPriority) - resourceDeletionPriority(right, deletionPriority));
|
|
1215
|
+
const queuesInUse = hasRoutingCheckpoint && resources.some((resource) => resource.kind === "queue" && shouldDeleteResource(resource, retainData)) && await hasLiveInstallationWorker(client, next);
|
|
1216
|
+
for (const listed of resources) {
|
|
1217
|
+
const resource = reopenedRouting && listed.key === "routing-kv" ? {
|
|
1218
|
+
...listed,
|
|
1219
|
+
state: "ready"
|
|
1220
|
+
} : listed;
|
|
1221
|
+
if (resource.state !== "ready") continue;
|
|
1222
|
+
if (!hasRoutingCheckpoint && resource.kind !== "zone") {
|
|
1223
|
+
next = updateResourceState(next, resource.key, "retained");
|
|
1224
|
+
await saveCheckpoint(next);
|
|
1225
|
+
continue;
|
|
1226
|
+
}
|
|
1227
|
+
if (!shouldDeleteResource(resource, retainData)) {
|
|
1228
|
+
const removed = resource.kind === "ai-gateway" && resource.ownership === "created" && !hasNamedResource(await client.listAiGateways(next.account.id), resource);
|
|
1229
|
+
next = updateResourceState(next, resource.key, removed ? "deleted" : "retained");
|
|
1230
|
+
await saveCheckpoint(next);
|
|
1231
|
+
continue;
|
|
1232
|
+
}
|
|
1233
|
+
if (resource.kind === "dns-record" && !zone || resource.kind === "queue" && queuesInUse) {
|
|
1234
|
+
next = updateResourceState(next, resource.key, "retained");
|
|
1235
|
+
await saveCheckpoint(next);
|
|
1236
|
+
continue;
|
|
1237
|
+
}
|
|
1238
|
+
if ((await verifyPlatformMutationOwnership(client, next, /* @__PURE__ */ new Set(["routing-kv", resource.key]), {
|
|
1239
|
+
allowDeletedRoutingCheckpoint: args.purgeData,
|
|
1240
|
+
databaseUrl: dependencies.databaseUrl
|
|
1241
|
+
})).has(resource.key)) {
|
|
1242
|
+
next = updateResourceState(next, resource.key, resource.ownership === "created" ? "deleted" : "retained");
|
|
1243
|
+
await saveCheckpoint(next);
|
|
1244
|
+
continue;
|
|
1245
|
+
}
|
|
1246
|
+
await client.deleteResource(next.account.id, resource, zone?.id);
|
|
1247
|
+
next = updateResourceState(next, resource.key, "deleted");
|
|
1248
|
+
await saveCheckpoint(next);
|
|
1249
|
+
}
|
|
1250
|
+
const completed = transitionInstallation(next, "uninstalled", (/* @__PURE__ */ new Date()).toISOString());
|
|
1251
|
+
await saveRemoteManifest(completed);
|
|
1252
|
+
next = completed;
|
|
1253
|
+
writeInstallationManifest(completed);
|
|
1254
|
+
if (!retainData) removeInstallationRecoverySecrets(next);
|
|
1255
|
+
removePlatformConnectionForInstallation(next.id);
|
|
1256
|
+
const kept = describeKeptResources(next, next.resources.filter((resource) => resource.state === "retained"), "Cloudflare resources:", "Access resources:", purgeResources && purgeResourcesHandlesEmailRouting(next));
|
|
1257
|
+
if (kept.length) note(kept.join("\n"), import_picocolors.default.bold("Kept resources"));
|
|
1258
|
+
printSuccess(`Uninstalled ${next.deployment.displayName}.`);
|
|
1259
|
+
} catch (error) {
|
|
1260
|
+
await stopProjectZeroTrustHold().catch(() => {});
|
|
1261
|
+
next = transitionInstallation(next, "failed", (/* @__PURE__ */ new Date()).toISOString());
|
|
1262
|
+
writeInstallationManifest(next);
|
|
1263
|
+
await saveRemoteManifest(next).catch(() => {});
|
|
1264
|
+
throw error;
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
async function recoverDurablyMarkedProvisionIntents(client, manifest) {
|
|
1268
|
+
const pending = [
|
|
1269
|
+
[
|
|
1270
|
+
"api-worker",
|
|
1271
|
+
"worker",
|
|
1272
|
+
manifest.deployment.resources.apiWorker
|
|
1273
|
+
],
|
|
1274
|
+
[
|
|
1275
|
+
"proxy-worker",
|
|
1276
|
+
"worker",
|
|
1277
|
+
manifest.deployment.resources.proxyWorker
|
|
1278
|
+
],
|
|
1279
|
+
[
|
|
1280
|
+
"email-gateway-worker",
|
|
1281
|
+
"worker",
|
|
1282
|
+
manifest.deployment.resources.emailGatewayWorker
|
|
1283
|
+
],
|
|
1284
|
+
[
|
|
1285
|
+
"tail-worker",
|
|
1286
|
+
"worker",
|
|
1287
|
+
manifest.deployment.resources.tailWorker
|
|
1288
|
+
],
|
|
1289
|
+
[
|
|
1290
|
+
"dispatch-worker",
|
|
1291
|
+
"worker",
|
|
1292
|
+
manifest.deployment.resources.dispatchWorker
|
|
1293
|
+
],
|
|
1294
|
+
[
|
|
1295
|
+
"assets-bucket",
|
|
1296
|
+
"r2-bucket",
|
|
1297
|
+
manifest.deployment.resources.assetsBucket
|
|
1298
|
+
]
|
|
1299
|
+
].filter(([key, kind, name]) => !manifest.resources.some((resource) => resource.key === key) && hasProvisionIntentStep(manifest, key, kind, name));
|
|
1300
|
+
if (pending.length === 0) return manifest;
|
|
1301
|
+
const [workers, buckets] = await Promise.all([client.listWorkerNames(manifest.account.id), client.listR2Buckets(manifest.account.id)]);
|
|
1302
|
+
let recovered = manifest;
|
|
1303
|
+
for (const [key, kind, name] of pending) {
|
|
1304
|
+
const live = kind === "worker" ? workers.includes(name) ? {
|
|
1305
|
+
id: name,
|
|
1306
|
+
name
|
|
1307
|
+
} : null : buckets.find((bucket) => bucket.name === name) ?? null;
|
|
1308
|
+
if (!live) continue;
|
|
1309
|
+
const resource = {
|
|
1310
|
+
configHash: legacyResourceConfigHash(kind, name),
|
|
1311
|
+
id: live.id,
|
|
1312
|
+
key,
|
|
1313
|
+
kind,
|
|
1314
|
+
name,
|
|
1315
|
+
ownership: "created",
|
|
1316
|
+
state: "ready"
|
|
1317
|
+
};
|
|
1318
|
+
verifyResourceMarker(kind === "worker" ? (await client.getWorkerPlainTextBindings(manifest.account.id, name)).PLATFORM_OWNERSHIP_MARKER : await client.getR2Object(manifest.account.id, name, PLATFORM_R2_OWNERSHIP_MARKER_KEY), manifest, resource);
|
|
1319
|
+
recovered = recordInstallationResource(recovered, resource, manifest.updatedAt);
|
|
1320
|
+
}
|
|
1321
|
+
return recovered;
|
|
1322
|
+
}
|
|
1323
|
+
const DATA_RESOURCE_KINDS = /* @__PURE__ */ new Set([
|
|
1324
|
+
"ai-gateway",
|
|
1325
|
+
"dispatch-namespace",
|
|
1326
|
+
"hyperdrive",
|
|
1327
|
+
"kv-namespace",
|
|
1328
|
+
"r2-bucket"
|
|
1329
|
+
]);
|
|
1330
|
+
function isOwnershipVerifiableKind(kind) {
|
|
1331
|
+
return kind === "ai-gateway" || kind === "dispatch-namespace" || kind === "dns-record" || kind === "hyperdrive" || kind === "kv-namespace" || kind === "queue" || kind === "r2-bucket" || kind === "worker" || kind === "zone";
|
|
1332
|
+
}
|
|
1333
|
+
const KEPT_RESOURCE_ORDER = [
|
|
1334
|
+
"dns-record",
|
|
1335
|
+
"worker-route",
|
|
1336
|
+
"worker-custom-domain",
|
|
1337
|
+
"queue",
|
|
1338
|
+
"worker",
|
|
1339
|
+
"dispatch-namespace",
|
|
1340
|
+
"kv-namespace",
|
|
1341
|
+
"hyperdrive",
|
|
1342
|
+
"r2-bucket",
|
|
1343
|
+
"ai-gateway",
|
|
1344
|
+
"analytics-dataset",
|
|
1345
|
+
"zone"
|
|
1346
|
+
];
|
|
1347
|
+
/** Resources an uninstall with these options leaves in the account. */
|
|
1348
|
+
function plannedKeptResources(manifest, retainData, hasRoutingCheckpoint) {
|
|
1349
|
+
const workersRemain = manifest.resources.some((resource) => resource.kind === "worker" && resource.state === "ready");
|
|
1350
|
+
return manifest.resources.filter((resource) => resource.state === "retained" || resource.state === "ready" && (!hasRoutingCheckpoint && resource.kind !== "zone" || !shouldDeleteResource(resource, retainData) || resource.kind === "queue" && workersRemain));
|
|
1351
|
+
}
|
|
1352
|
+
function keptResourceRank(manifest, resource) {
|
|
1353
|
+
return isPlatformTailWorker(manifest, resource) ? KEPT_RESOURCE_ORDER.indexOf("dispatch-namespace") + .5 : KEPT_RESOURCE_ORDER.indexOf(resource.kind);
|
|
1354
|
+
}
|
|
1355
|
+
function purgeResourcesPlanText(manifest) {
|
|
1356
|
+
const permissions = purgeResourcesPermissions(manifest);
|
|
1357
|
+
const keepManifest = {
|
|
1358
|
+
...manifest,
|
|
1359
|
+
authenticationResources: (manifest.authenticationResources ?? []).filter((resource) => resource.ownership !== "created" || purgeResourcesKeptReason(manifest, `access:${resource.key}`) !== null)
|
|
1360
|
+
};
|
|
1361
|
+
return [
|
|
1362
|
+
"Disable platform traffic.",
|
|
1363
|
+
...describePurgeResourcesPlan(manifest),
|
|
1364
|
+
...describeKeptResources(keepManifest, purgeResourcesKeptResources(manifest), "Keep for manual cleanup:", "Keep Access resources you connected:", purgeResourcesHandlesEmailRouting(manifest)),
|
|
1365
|
+
"Always kept:",
|
|
1366
|
+
...purgeResourcesAlwaysKept(),
|
|
1367
|
+
...permissions.length ? [`API token needs: ${permissions.join(", ")}. Browser login cannot delete DNS records or Access resources.`] : []
|
|
1368
|
+
].join("\n");
|
|
1369
|
+
}
|
|
1370
|
+
function describeKeptResources(manifest, resources, heading, accessHeading, emailRulesRemoved = false) {
|
|
1371
|
+
const sorted = [...resources].sort((left, right) => keptResourceRank(manifest, left) - keptResourceRank(manifest, right));
|
|
1372
|
+
const isTraffic = (resource) => KEPT_RESOURCE_ORDER.indexOf(resource.kind) < KEPT_RESOURCE_ORDER.indexOf("queue");
|
|
1373
|
+
const why = (key) => {
|
|
1374
|
+
const reason = purgeResourcesKeptReason(manifest, key);
|
|
1375
|
+
return reason === null ? "" : `, kept because ${reason}`;
|
|
1376
|
+
};
|
|
1377
|
+
const line = (resource) => ` ${resource.kind}: ${resource.name}${resource.name === resource.id ? "" : ` (${resource.id})`}${why(resource.key)}`;
|
|
1378
|
+
const { capabilities, emailSenderDomain, emailSharedZoneId, resources: names } = manifest.deployment;
|
|
1379
|
+
const email = capabilities.email ? [emailRulesRemoved && emailSenderDomain ? ` Email Routing for ${emailSenderDomain} (zone ${emailSharedZoneId}): its settings and the sender domain's MX, SPF, and DKIM records.` : emailSenderDomain ? ` Email Routing for ${emailSenderDomain} (zone ${emailSharedZoneId}): its routing DNS records and any catch-all rule that sends mail to ${names.emailGatewayWorker}.` : ` Email Routing: any catch-all rule that sends mail to ${names.emailGatewayWorker}.`] : [];
|
|
1380
|
+
const remainingAccess = (manifest.authenticationResources ?? []).filter((resource) => !isPurgedAccessResource(manifest, resource));
|
|
1381
|
+
const accessLine = (resource) => ` ${resource.ownership} ${resource.kind}: ${resource.name} (${resource.id}, account ${resource.accountId})${why(`access:${resource.key}`)}`;
|
|
1382
|
+
const keptAccess = (resource) => purgeResourcesKeptReason(manifest, `access:${resource.key}`) !== null;
|
|
1383
|
+
const kept = [
|
|
1384
|
+
...sorted.filter(isTraffic).map(line),
|
|
1385
|
+
...remainingAccess.filter(keptAccess).map(accessLine),
|
|
1386
|
+
...email,
|
|
1387
|
+
...sorted.filter((resource) => !isTraffic(resource)).map(line)
|
|
1388
|
+
];
|
|
1389
|
+
const access = remainingAccess.filter((resource) => !keptAccess(resource)).map(accessLine);
|
|
1390
|
+
return [...kept.length ? [heading, ...kept] : [], ...access.length ? [accessHeading, ...access] : []];
|
|
1391
|
+
}
|
|
1392
|
+
function shouldDeleteResource(resource, retainData) {
|
|
1393
|
+
if (resource.state !== "ready" || resource.ownership !== "created") return false;
|
|
1394
|
+
if (resource.kind === "zone") return false;
|
|
1395
|
+
if (resource.kind === "ai-gateway") return false;
|
|
1396
|
+
if (resource.kind === "dns-record") return false;
|
|
1397
|
+
if (resource.kind === "r2-bucket") return false;
|
|
1398
|
+
if (resource.kind === "worker") return false;
|
|
1399
|
+
if (resource.kind === "worker-route" || resource.kind === "worker-custom-domain") return false;
|
|
1400
|
+
return !(retainData && DATA_RESOURCE_KINDS.has(resource.kind));
|
|
1401
|
+
}
|
|
1402
|
+
async function hasLiveInstallationWorker(client, manifest) {
|
|
1403
|
+
const names = manifest.deployment.resources;
|
|
1404
|
+
const installationWorkers = /* @__PURE__ */ new Set([
|
|
1405
|
+
names.apiWorker,
|
|
1406
|
+
names.proxyWorker,
|
|
1407
|
+
names.emailGatewayWorker,
|
|
1408
|
+
names.tailWorker,
|
|
1409
|
+
names.dispatchWorker,
|
|
1410
|
+
...manifest.resources.filter((resource) => resource.kind === "worker").map((resource) => resource.name)
|
|
1411
|
+
]);
|
|
1412
|
+
return (await client.listWorkerNames(manifest.account.id)).some((name) => installationWorkers.has(name));
|
|
1413
|
+
}
|
|
1414
|
+
function resourceDeletionPriority(resource, priorities) {
|
|
1415
|
+
return resource.key === "routing-kv" ? 100 : priorities[resource.kind] ?? 99;
|
|
1416
|
+
}
|
|
1417
|
+
async function verifyPlatformMutationOwnership(client, manifest, targetKeys, options = {}) {
|
|
1418
|
+
const routing = requireResource(manifest, "routing-kv");
|
|
1419
|
+
const targetResources = manifest.resources.filter((resource) => targetKeys.has(resource.key) && resource.state === "ready");
|
|
1420
|
+
let rawRemote = null;
|
|
1421
|
+
let remote = null;
|
|
1422
|
+
let replacingMissingRoutingCheckpoint = false;
|
|
1423
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
1424
|
+
rawRemote = await client.getKvValue(manifest.account.id, routing.id, REMOTE_INSTALLATION_MANIFEST_KEY);
|
|
1425
|
+
if (rawRemote !== null) {
|
|
1426
|
+
try {
|
|
1427
|
+
remote = parsePlatformInstallationManifest(JSON.parse(rawRemote));
|
|
1428
|
+
} catch {
|
|
1429
|
+
throw ownershipError("the remote installation checkpoint is invalid");
|
|
1430
|
+
}
|
|
1431
|
+
if (remote.id !== manifest.id || remote.ownershipNonce !== manifest.ownershipNonce || remote.account.id !== manifest.account.id) throw ownershipError("the remote installation identity does not match this installation");
|
|
1432
|
+
if (targetResources.every((resource) => hasMatchingResourceProof(remote, resource))) break;
|
|
1433
|
+
}
|
|
1434
|
+
if (attempt < 2) await setTimeout(50 * 2 ** attempt);
|
|
1435
|
+
}
|
|
1436
|
+
if (rawRemote === null) {
|
|
1437
|
+
if ((options.allowMissingRoutingCheckpoint || options.allowUninitializedRoutingCheckpoint) && routing.ownership === "created") {
|
|
1438
|
+
const namespaces = await client.listKvNamespaces(manifest.account.id);
|
|
1439
|
+
const routingMatches = namespaces.some((entry) => entry.id === routing.id && entry.name === routing.name);
|
|
1440
|
+
const routingIdentityCollides = namespaces.some((entry) => entry.id === routing.id || entry.name === routing.name);
|
|
1441
|
+
if (options.allowMissingRoutingCheckpoint && !routingIdentityCollides || options.allowUninitializedRoutingCheckpoint && routingMatches) {
|
|
1442
|
+
remote = manifest;
|
|
1443
|
+
replacingMissingRoutingCheckpoint = true;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
if (!replacingMissingRoutingCheckpoint && options.allowDeletedRoutingCheckpoint && canResumeAfterRoutingCheckpointDeletion(manifest, targetKeys)) {
|
|
1447
|
+
if (!(await client.listKvNamespaces(manifest.account.id)).some((entry) => entry.id === routing.id)) return /* @__PURE__ */ new Set([routing.key]);
|
|
1448
|
+
}
|
|
1449
|
+
if (!replacingMissingRoutingCheckpoint) throw ownershipError("the remote installation checkpoint is missing");
|
|
1450
|
+
}
|
|
1451
|
+
if (!remote) throw ownershipError("the remote installation checkpoint is missing");
|
|
1452
|
+
const localAdvancesRemote = isPlatformManifestMonotonicExtension(remote, manifest);
|
|
1453
|
+
for (const resource of targetResources) {
|
|
1454
|
+
const proof = remote.resources.find((entry) => entry.key === resource.key);
|
|
1455
|
+
if (!hasMatchingResourceProof(remote, resource)) {
|
|
1456
|
+
if (!proof && localAdvancesRemote && resource.kind !== "ai-gateway" && hasMatchingResourceIntent(remote, resource)) continue;
|
|
1457
|
+
throw ownershipError(`the remote checkpoint does not own ${resource.kind} ${resource.name}`);
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
const missing = new Set(replacingMissingRoutingCheckpoint ? [routing.key] : []);
|
|
1461
|
+
const accountId = manifest.account.id;
|
|
1462
|
+
const zone = manifest.resources.find((resource) => resource.key === "zone");
|
|
1463
|
+
const [aiGateways, dispatchNamespaces, hyperdrives, kvNamespaces, r2Buckets, workerNames] = await Promise.all([
|
|
1464
|
+
client.listAiGateways(accountId),
|
|
1465
|
+
targetResources.some((resource) => resource.kind === "dispatch-namespace") ? client.listDispatchNamespaces(accountId) : Promise.resolve([]),
|
|
1466
|
+
client.listHyperdriveConfigs(accountId),
|
|
1467
|
+
client.listKvNamespaces(accountId),
|
|
1468
|
+
client.listR2Buckets(accountId),
|
|
1469
|
+
client.listWorkerNames(accountId)
|
|
1470
|
+
]);
|
|
1471
|
+
for (const resource of targetResources) {
|
|
1472
|
+
let exists = true;
|
|
1473
|
+
if (resource.kind === "ai-gateway") exists = hasNamedResource(aiGateways, resource);
|
|
1474
|
+
else if (resource.kind === "dispatch-namespace") exists = hasNamedResource(dispatchNamespaces, resource);
|
|
1475
|
+
else if (resource.kind === "hyperdrive") {
|
|
1476
|
+
exists = hasNamedResource(hyperdrives, resource);
|
|
1477
|
+
if (exists) {
|
|
1478
|
+
const live = await client.getHyperdriveConfig(accountId, resource.id);
|
|
1479
|
+
exists = live.id === resource.id && live.name === resource.name;
|
|
1480
|
+
if (exists) {
|
|
1481
|
+
const legacyHash = legacyResourceConfigHash(resource.kind, resource.name);
|
|
1482
|
+
const malformedLegacyHash = !/^[a-f0-9]{64}$/.test(resource.configHash);
|
|
1483
|
+
if (live.origin.serviceId !== void 0 && resource.ownership !== "adopted") throw ownershipError(`hyperdrive ${resource.name} changed to a Workers VPC origin`);
|
|
1484
|
+
if (options.databaseUrl && resource.ownership !== "adopted") {
|
|
1485
|
+
const expected = hyperdriveOriginFromConnectionString(options.databaseUrl);
|
|
1486
|
+
if (!hyperdriveOriginMatches(live.origin, expected)) throw ownershipError(`hyperdrive ${resource.name} targets a different PostgreSQL origin than this installation's pinned database`);
|
|
1487
|
+
const expectedHash = hyperdriveOriginConfigHash(expected);
|
|
1488
|
+
if (resource.configHash !== expectedHash && resource.configHash !== legacyHash && !malformedLegacyHash) throw ownershipError(`hyperdrive ${resource.name} does not match the installation's database fingerprint`);
|
|
1489
|
+
} else if (resource.ownership === "adopted" && (resource.configHash !== hyperdriveOriginConfigHash(live.origin) || options.databaseUrl && live.origin.database !== platformDatabaseNameFromOwnerUrl(options.databaseUrl))) throw ownershipError(`hyperdrive ${resource.name} changed configuration`);
|
|
1490
|
+
else if (resource.ownership !== "adopted" && resource.configHash !== hyperdriveOriginConfigHash(live.origin) && resource.configHash !== legacyHash && !malformedLegacyHash) throw ownershipError(`hyperdrive ${resource.name} changed configuration`);
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
} else if (resource.kind === "kv-namespace") exists = hasNamedResource(kvNamespaces, resource);
|
|
1494
|
+
else if (resource.kind === "queue") exists = hasNamedResource(await client.listQueues(accountId, resource.name), resource);
|
|
1495
|
+
else if (resource.kind === "zone") exists = (await client.findZone(accountId, resource.name))?.id === resource.id;
|
|
1496
|
+
else if (resource.kind === "dns-record") {
|
|
1497
|
+
if (!zone) exists = false;
|
|
1498
|
+
else {
|
|
1499
|
+
const current = (await client.listDnsRecords(zone.id, resource.name)).find((entry) => entry.id === resource.id && entry.name === resource.name);
|
|
1500
|
+
exists = current !== void 0;
|
|
1501
|
+
if (current && resource.ownership === "created") {
|
|
1502
|
+
const liveHash = dnsRecordConfigHash(current.name, current.type, current.content, current.proxied);
|
|
1503
|
+
const legacyHash = legacyResourceConfigHash(resource.kind, resource.name);
|
|
1504
|
+
const expectedHash = dnsRecordConfigHash(resource.name, "AAAA", "100::", true);
|
|
1505
|
+
if (liveHash !== resource.configHash && !(resource.configHash === legacyHash && liveHash === expectedHash)) throw new PlatformResourceChangedError(resource.key, "its configuration changed after installation", ownershipError(`dns-record ${resource.name} changed configuration after installation`).message);
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
} else if (resource.kind === "worker") {
|
|
1509
|
+
exists = workerNames.includes(resource.name);
|
|
1510
|
+
if (exists) verifyResourceMarker((await client.getWorkerPlainTextBindings(accountId, resource.name)).PLATFORM_OWNERSHIP_MARKER, manifest, resource);
|
|
1511
|
+
} else if (resource.kind === "r2-bucket") {
|
|
1512
|
+
const live = r2Buckets.find((entry) => entry.id === resource.id && entry.name === resource.name);
|
|
1513
|
+
exists = live !== void 0;
|
|
1514
|
+
if (live) {
|
|
1515
|
+
if (!matchesRecordedR2Fingerprint(resource.configHash, live)) throw ownershipError(`r2-bucket ${resource.name} changed creation fingerprint`);
|
|
1516
|
+
verifyResourceMarker(await client.getR2Object(accountId, resource.name, PLATFORM_R2_OWNERSHIP_MARKER_KEY), manifest, resource);
|
|
1517
|
+
}
|
|
1518
|
+
} else throw ownershipError(`live ownership checks do not support ${resource.kind}`);
|
|
1519
|
+
if (!exists) missing.add(resource.key);
|
|
1520
|
+
}
|
|
1521
|
+
return missing;
|
|
1522
|
+
}
|
|
1523
|
+
function hasMatchingResourceProof(manifest, resource) {
|
|
1524
|
+
const proof = manifest.resources.find((entry) => entry.key === resource.key);
|
|
1525
|
+
return proof?.id === resource.id && proof.kind === resource.kind && proof.name === resource.name && proof.ownership === resource.ownership;
|
|
1526
|
+
}
|
|
1527
|
+
function hasMatchingResourceIntent(manifest, resource) {
|
|
1528
|
+
if (resource.ownership === "created") return hasProvisionIntentStep(manifest, resource.key, resource.kind, resource.name);
|
|
1529
|
+
if (resource.ownership === "adopted") return manifest.steps.some((step) => step.key === `adoption-intent:${resource.key}` && step.resultHash === platformAdoptionIntentHash(manifest, resource.key, resource.kind, resource.id, resource.name));
|
|
1530
|
+
return false;
|
|
1531
|
+
}
|
|
1532
|
+
function isPlatformManifestMonotonicExtension(earlier, later) {
|
|
1533
|
+
if (earlier.id !== later.id || earlier.ownershipNonce !== later.ownershipNonce || earlier.account.id !== later.account.id || earlier.createdAt !== later.createdAt || JSON.stringify(earlier.deployment) !== JSON.stringify(later.deployment) || Date.parse(later.updatedAt) < Date.parse(earlier.updatedAt)) return false;
|
|
1534
|
+
const resourcesAdvance = earlier.resources.every((resource) => {
|
|
1535
|
+
const next = later.resources.find((entry) => entry.key === resource.key);
|
|
1536
|
+
return next?.id === resource.id && next.kind === resource.kind && next.name === resource.name && next.ownership === resource.ownership && (next.state === resource.state || resource.state === "ready" && (next.state === "deleted" || next.state === "retained") || resource.state === "retained" && next.state === "deleted");
|
|
1537
|
+
});
|
|
1538
|
+
const stepsAdvance = earlier.steps.every((step) => later.steps.some((entry) => entry.key === step.key && entry.completedAt === step.completedAt && entry.resultHash === step.resultHash));
|
|
1539
|
+
const authenticationResourcesAdvance = (earlier.authenticationResources ?? []).every((resource) => (later.authenticationResources ?? []).some((next) => JSON.stringify(next) === JSON.stringify(resource)));
|
|
1540
|
+
return resourcesAdvance && stepsAdvance && authenticationResourcesAdvance;
|
|
1541
|
+
}
|
|
1542
|
+
function hasNamedResource(entries, resource) {
|
|
1543
|
+
return entries.some((entry) => entry.id === resource.id && entry.name === resource.name);
|
|
1544
|
+
}
|
|
1545
|
+
function verifyResourceMarker(value, manifest, resource) {
|
|
1546
|
+
const problem = resourceMarkerProblem(value, manifest, resource);
|
|
1547
|
+
if (problem) throw ownershipError(`${resource.kind} ${resource.name} ${problem}`);
|
|
1548
|
+
}
|
|
1549
|
+
function canResumeAfterRoutingCheckpointDeletion(manifest, targetKeys) {
|
|
1550
|
+
if (manifest.status !== "failed" && manifest.status !== "uninstalling") return false;
|
|
1551
|
+
return manifest.resources.every((resource) => resource.key === "routing-kv" || !targetKeys.has(resource.key) || resource.state !== "ready");
|
|
1552
|
+
}
|
|
1553
|
+
function ownershipError(reason) {
|
|
1554
|
+
return /* @__PURE__ */ new Error(`platform: Refusing to change Cloudflare resources because ${reason}. Run \`bwf platform repair\` to restore ownership proofs before retrying.`);
|
|
1555
|
+
}
|
|
1556
|
+
function requireResource(manifest, key) {
|
|
1557
|
+
const resource = manifest.resources.find((entry) => entry.key === key);
|
|
1558
|
+
if (!resource) throw new Error(`platform: Installation manifest is missing ${key}.`);
|
|
1559
|
+
return resource;
|
|
1560
|
+
}
|
|
1561
|
+
function updateResourceState(manifest, key, state) {
|
|
1562
|
+
const resource = requireResource(manifest, key);
|
|
1563
|
+
return recordInstallationResource(manifest, {
|
|
1564
|
+
...resource,
|
|
1565
|
+
state
|
|
1566
|
+
}, (/* @__PURE__ */ new Date()).toISOString());
|
|
1567
|
+
}
|
|
1568
|
+
function markTrafficAttachmentsRetained(manifest) {
|
|
1569
|
+
let next = manifest;
|
|
1570
|
+
for (const resource of manifest.resources) if (resource.state === "ready" && (resource.kind === "worker-route" || resource.kind === "worker-custom-domain")) next = updateResourceState(next, resource.key, "retained");
|
|
1571
|
+
return next;
|
|
1572
|
+
}
|
|
1573
|
+
function hasLifecycleStep(manifest, key) {
|
|
1574
|
+
return manifest.steps.some((step) => step.key === key);
|
|
1575
|
+
}
|
|
1576
|
+
function currentTrafficGeneration(manifest) {
|
|
1577
|
+
return Math.max(0, ...manifest.steps.flatMap((step) => {
|
|
1578
|
+
const match = /^traffic-enabled:(\d+)$/.exec(step.key);
|
|
1579
|
+
return match ? [Number(match[1])] : [];
|
|
1580
|
+
}));
|
|
1581
|
+
}
|
|
1582
|
+
function recordLifecycleStep(manifest, key) {
|
|
1583
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1584
|
+
return recordInstallationStep(manifest, {
|
|
1585
|
+
completedAt: now,
|
|
1586
|
+
key,
|
|
1587
|
+
resultHash: "completed"
|
|
1588
|
+
}, now);
|
|
1589
|
+
}
|
|
1590
|
+
async function writeLifecycleCheckpoint(client, manifest, databaseCheckpoint) {
|
|
1591
|
+
writeInstallationManifest(manifest);
|
|
1592
|
+
await writeRemoteManifest(client, manifest, databaseCheckpoint);
|
|
1593
|
+
}
|
|
1594
|
+
async function writeRemoteManifest(client, manifest, databaseCheckpoint) {
|
|
1595
|
+
await databaseCheckpoint?.(manifest);
|
|
1596
|
+
const routing = manifest.resources.find((resource) => resource.key === "routing-kv" && resource.state !== "deleted");
|
|
1597
|
+
if (routing) await client.putKvValue(manifest.account.id, routing.id, REMOTE_INSTALLATION_MANIFEST_KEY, JSON.stringify(manifest));
|
|
1598
|
+
}
|
|
1599
|
+
async function promptForConfirmation(message, initialValue) {
|
|
1600
|
+
const answer = await confirm({
|
|
1601
|
+
message,
|
|
1602
|
+
initialValue
|
|
1603
|
+
});
|
|
1604
|
+
if (isCancel(answer) || typeof answer === "symbol") throw new Error("platform: Cancelled.");
|
|
1605
|
+
return answer;
|
|
1606
|
+
}
|
|
1607
|
+
export { recoverDurablyMarkedProvisionIntents as a, runInstalledPlatformCommand as c, verifyPlatformInstallationOwnership as d, platformLifecycleResumeCommand as i, selectAuthoritativePlatformManifest as l, disablePlatform as n, resolveInstalledPlatformManifest as o, isPlatformManifestMonotonicExtension as r, resolvePlatformRuntimeTokenToPreflight as s, assertPlatformRollbackCompatibility as t, uninstallPlatform as u };
|