wrangler 2.20.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/README.md +4 -4
  2. package/bin/wrangler.js +9 -75
  3. package/package.json +5 -13
  4. package/templates/__tests__/tsconfig.tsbuildinfo +1 -1
  5. package/templates/checked-fetch.js +1 -1
  6. package/templates/first-party-worker-module-facade.ts +2 -2
  7. package/templates/middleware/common.ts +9 -4
  8. package/templates/middleware/loader-sw.ts +2 -7
  9. package/templates/new-worker-scheduled.ts +1 -1
  10. package/templates/new-worker.ts +1 -1
  11. package/templates/pages-dev-util.ts +4 -1
  12. package/templates/pages-shim.ts +0 -3
  13. package/templates/tsconfig.tsbuildinfo +1 -1
  14. package/wrangler-dist/cli.d.ts +149 -75
  15. package/wrangler-dist/cli.js +60062 -64338
  16. package/import_meta_url.js +0 -3
  17. package/miniflare-config-stubs/.env.empty +0 -0
  18. package/miniflare-config-stubs/package.empty.json +0 -1
  19. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  20. package/miniflare-dist/index.mjs +0 -6442
  21. package/src/__tests__/access.test.ts +0 -25
  22. package/src/__tests__/api-dev.test.ts +0 -238
  23. package/src/__tests__/api-devregistry.test.ts +0 -121
  24. package/src/__tests__/api.test.ts +0 -102
  25. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  26. package/src/__tests__/config-cache.test.ts +0 -42
  27. package/src/__tests__/configuration.test.ts +0 -4517
  28. package/src/__tests__/constellation.test.ts +0 -371
  29. package/src/__tests__/d1/d1.test.ts +0 -82
  30. package/src/__tests__/d1/execute.test.ts +0 -66
  31. package/src/__tests__/d1/migrate.test.ts +0 -257
  32. package/src/__tests__/d1/splitter.test.ts +0 -255
  33. package/src/__tests__/delete.test.ts +0 -272
  34. package/src/__tests__/deployments.test.ts +0 -369
  35. package/src/__tests__/dev.test.tsx +0 -1617
  36. package/src/__tests__/generate.test.ts +0 -237
  37. package/src/__tests__/get-host-from-url.test.ts +0 -16
  38. package/src/__tests__/guess-worker-format.test.ts +0 -120
  39. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  40. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  41. package/src/__tests__/helpers/end-event-loop.ts +0 -6
  42. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  43. package/src/__tests__/helpers/mock-auth-domain.ts +0 -20
  44. package/src/__tests__/helpers/mock-bin.ts +0 -36
  45. package/src/__tests__/helpers/mock-console.ts +0 -112
  46. package/src/__tests__/helpers/mock-dialogs.ts +0 -139
  47. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +0 -25
  48. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -11
  49. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  50. package/src/__tests__/helpers/mock-istty.ts +0 -74
  51. package/src/__tests__/helpers/mock-known-routes.ts +0 -12
  52. package/src/__tests__/helpers/mock-kv.ts +0 -46
  53. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -263
  54. package/src/__tests__/helpers/mock-process.ts +0 -34
  55. package/src/__tests__/helpers/mock-set-timeout.ts +0 -16
  56. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  57. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  58. package/src/__tests__/helpers/msw/blob-worker.cjs +0 -19
  59. package/src/__tests__/helpers/msw/handlers/access.ts +0 -13
  60. package/src/__tests__/helpers/msw/handlers/deployments.ts +0 -160
  61. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -81
  62. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -31
  63. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -60
  64. package/src/__tests__/helpers/msw/handlers/script.ts +0 -56
  65. package/src/__tests__/helpers/msw/handlers/user.ts +0 -52
  66. package/src/__tests__/helpers/msw/handlers/zones.ts +0 -20
  67. package/src/__tests__/helpers/msw/index.ts +0 -52
  68. package/src/__tests__/helpers/msw/read-file-sync.js +0 -61
  69. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  70. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  71. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +0 -28
  72. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  73. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  74. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  75. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -11
  76. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  77. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  78. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  79. package/src/__tests__/https-options.test.ts +0 -163
  80. package/src/__tests__/index.test.ts +0 -282
  81. package/src/__tests__/init.test.ts +0 -3196
  82. package/src/__tests__/jest.setup.ts +0 -179
  83. package/src/__tests__/kv.test.ts +0 -1799
  84. package/src/__tests__/logger.test.ts +0 -207
  85. package/src/__tests__/logout.test.ts +0 -47
  86. package/src/__tests__/metrics.test.ts +0 -493
  87. package/src/__tests__/middleware.scheduled.test.ts +0 -145
  88. package/src/__tests__/middleware.test.ts +0 -816
  89. package/src/__tests__/mtls-certificates.test.ts +0 -589
  90. package/src/__tests__/package-manager.test.ts +0 -353
  91. package/src/__tests__/pages/deployment-list.test.ts +0 -80
  92. package/src/__tests__/pages/functions-build.test.ts +0 -528
  93. package/src/__tests__/pages/pages.test.ts +0 -81
  94. package/src/__tests__/pages/project-create.test.ts +0 -63
  95. package/src/__tests__/pages/project-list.test.ts +0 -110
  96. package/src/__tests__/pages/project-upload.test.ts +0 -500
  97. package/src/__tests__/pages/publish.test.ts +0 -2864
  98. package/src/__tests__/pages-deployment-tail.test.ts +0 -957
  99. package/src/__tests__/parse.test.ts +0 -436
  100. package/src/__tests__/paths.test.ts +0 -39
  101. package/src/__tests__/publish.test.ts +0 -8849
  102. package/src/__tests__/pubsub.test.ts +0 -496
  103. package/src/__tests__/queues.test.ts +0 -532
  104. package/src/__tests__/r2.test.ts +0 -374
  105. package/src/__tests__/route.test.ts +0 -45
  106. package/src/__tests__/secret.test.ts +0 -693
  107. package/src/__tests__/tail.test.ts +0 -989
  108. package/src/__tests__/test-old-node-version.js +0 -31
  109. package/src/__tests__/traverse-module-graph.test.ts +0 -220
  110. package/src/__tests__/tsconfig-sanity.ts +0 -12
  111. package/src/__tests__/tsconfig.json +0 -8
  112. package/src/__tests__/tsconfig.tsbuildinfo +0 -1
  113. package/src/__tests__/type-generation.test.ts +0 -234
  114. package/src/__tests__/user.test.ts +0 -118
  115. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  116. package/src/__tests__/validate-dev-props.test.ts +0 -56
  117. package/src/__tests__/version.test.ts +0 -35
  118. package/src/__tests__/whoami.test.tsx +0 -172
  119. package/src/__tests__/worker-namespace.test.ts +0 -340
  120. package/src/abort.d.ts +0 -3
  121. package/src/api/dev.ts +0 -321
  122. package/src/api/index.ts +0 -11
  123. package/src/api/mtls-certificate.ts +0 -148
  124. package/src/api/pages/create-worker-bundle-contents.ts +0 -77
  125. package/src/api/pages/index.ts +0 -5
  126. package/src/api/pages/publish.tsx +0 -371
  127. package/src/bundle-reporter.ts +0 -68
  128. package/src/bundle.ts +0 -929
  129. package/src/cfetch/index.ts +0 -158
  130. package/src/cfetch/internal.ts +0 -258
  131. package/src/cli.ts +0 -28
  132. package/src/config/README.md +0 -107
  133. package/src/config/config.ts +0 -282
  134. package/src/config/diagnostics.ts +0 -80
  135. package/src/config/environment.ts +0 -625
  136. package/src/config/index.ts +0 -403
  137. package/src/config/validation-helpers.ts +0 -597
  138. package/src/config/validation.ts +0 -2369
  139. package/src/config-cache.ts +0 -85
  140. package/src/constellation/createProject.tsx +0 -51
  141. package/src/constellation/deleteProject.ts +0 -51
  142. package/src/constellation/deleteProjectModel.ts +0 -68
  143. package/src/constellation/index.ts +0 -75
  144. package/src/constellation/listCatalog.tsx +0 -35
  145. package/src/constellation/listModel.tsx +0 -41
  146. package/src/constellation/listProject.tsx +0 -28
  147. package/src/constellation/listRuntime.tsx +0 -28
  148. package/src/constellation/options.ts +0 -17
  149. package/src/constellation/types.ts +0 -17
  150. package/src/constellation/uploadModel.tsx +0 -64
  151. package/src/constellation/utils.ts +0 -90
  152. package/src/create-worker-preview.ts +0 -293
  153. package/src/create-worker-upload-form.ts +0 -363
  154. package/src/d1/backups.tsx +0 -219
  155. package/src/d1/constants.ts +0 -2
  156. package/src/d1/create.tsx +0 -70
  157. package/src/d1/delete.ts +0 -53
  158. package/src/d1/execute.tsx +0 -357
  159. package/src/d1/formatTimeAgo.ts +0 -14
  160. package/src/d1/index.ts +0 -100
  161. package/src/d1/list.tsx +0 -62
  162. package/src/d1/migrations/apply.tsx +0 -212
  163. package/src/d1/migrations/create.tsx +0 -79
  164. package/src/d1/migrations/helpers.ts +0 -169
  165. package/src/d1/migrations/index.ts +0 -3
  166. package/src/d1/migrations/list.tsx +0 -95
  167. package/src/d1/migrations/options.ts +0 -23
  168. package/src/d1/options.ts +0 -22
  169. package/src/d1/splitter.ts +0 -161
  170. package/src/d1/types.ts +0 -25
  171. package/src/d1/utils.ts +0 -49
  172. package/src/delete.ts +0 -100
  173. package/src/deployments.ts +0 -368
  174. package/src/deprecated/index.ts +0 -144
  175. package/src/dev/dev-vars.ts +0 -39
  176. package/src/dev/dev.tsx +0 -605
  177. package/src/dev/get-local-persistence-path.ts +0 -31
  178. package/src/dev/local.tsx +0 -952
  179. package/src/dev/remote.tsx +0 -635
  180. package/src/dev/start-server.ts +0 -545
  181. package/src/dev/use-esbuild.ts +0 -215
  182. package/src/dev/validate-dev-props.ts +0 -40
  183. package/src/dev-registry.ts +0 -202
  184. package/src/dev.tsx +0 -934
  185. package/src/dialogs.ts +0 -136
  186. package/src/dispatch-namespace.ts +0 -211
  187. package/src/docs/helpers.ts +0 -50
  188. package/src/docs/index.ts +0 -54
  189. package/src/durable.ts +0 -102
  190. package/src/entry.ts +0 -344
  191. package/src/environment-variables/factory.ts +0 -89
  192. package/src/environment-variables/misc-variables.ts +0 -30
  193. package/src/errors.ts +0 -11
  194. package/src/generate/index.ts +0 -298
  195. package/src/git-client.ts +0 -135
  196. package/src/global-wrangler-config-path.ts +0 -26
  197. package/src/https-options.ts +0 -127
  198. package/src/index.ts +0 -768
  199. package/src/init.ts +0 -1037
  200. package/src/inspect.ts +0 -883
  201. package/src/intl-polyfill.d.ts +0 -139
  202. package/src/is-ci.ts +0 -14
  203. package/src/is-interactive.ts +0 -16
  204. package/src/jest.d.ts +0 -4
  205. package/src/kv/helpers.ts +0 -433
  206. package/src/kv/index.ts +0 -594
  207. package/src/logger.ts +0 -123
  208. package/src/metrics/index.ts +0 -5
  209. package/src/metrics/metrics-config.ts +0 -239
  210. package/src/metrics/metrics-dispatcher.ts +0 -96
  211. package/src/metrics/metrics-usage-headers.ts +0 -24
  212. package/src/metrics/send-event.ts +0 -99
  213. package/src/miniflare-cli/README.md +0 -30
  214. package/src/miniflare-cli/assets.ts +0 -251
  215. package/src/miniflare-cli/index.ts +0 -210
  216. package/src/miniflare-cli/request-context.ts +0 -40
  217. package/src/miniflare-cli/tsconfig.json +0 -9
  218. package/src/miniflare-cli/tsconfig.tsbuildinfo +0 -1
  219. package/src/miniflare-cli/types.ts +0 -11
  220. package/src/module-collection.ts +0 -333
  221. package/src/mtls-certificate/cli.ts +0 -155
  222. package/src/open-in-browser.ts +0 -17
  223. package/src/package-manager.ts +0 -219
  224. package/src/pages/build.ts +0 -423
  225. package/src/pages/buildFunctions.ts +0 -140
  226. package/src/pages/constants.ts +0 -18
  227. package/src/pages/deployment-tails.ts +0 -281
  228. package/src/pages/deployments.tsx +0 -84
  229. package/src/pages/dev.ts +0 -734
  230. package/src/pages/errors.ts +0 -67
  231. package/src/pages/functions/buildPlugin.ts +0 -114
  232. package/src/pages/functions/buildWorker.ts +0 -350
  233. package/src/pages/functions/filepath-routing.test.ts +0 -234
  234. package/src/pages/functions/filepath-routing.ts +0 -189
  235. package/src/pages/functions/identifiers.ts +0 -78
  236. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  237. package/src/pages/functions/routes-consolidation.ts +0 -73
  238. package/src/pages/functions/routes-transformation.test.ts +0 -282
  239. package/src/pages/functions/routes-transformation.ts +0 -115
  240. package/src/pages/functions/routes-validation.test.ts +0 -403
  241. package/src/pages/functions/routes-validation.ts +0 -202
  242. package/src/pages/functions/routes.ts +0 -151
  243. package/src/pages/functions/tsconfig.json +0 -8
  244. package/src/pages/functions/tsconfig.tsbuildinfo +0 -1
  245. package/src/pages/functions.ts +0 -86
  246. package/src/pages/hash.ts +0 -13
  247. package/src/pages/index.ts +0 -102
  248. package/src/pages/projects.tsx +0 -159
  249. package/src/pages/prompt-select-project.tsx +0 -31
  250. package/src/pages/publish.tsx +0 -267
  251. package/src/pages/types.ts +0 -46
  252. package/src/pages/upload.tsx +0 -469
  253. package/src/pages/utils.ts +0 -23
  254. package/src/parse.ts +0 -308
  255. package/src/paths.ts +0 -71
  256. package/src/proxy.ts +0 -694
  257. package/src/publish/index.ts +0 -274
  258. package/src/publish/publish.ts +0 -1065
  259. package/src/pubsub/index.ts +0 -286
  260. package/src/pubsub/pubsub-commands.ts +0 -623
  261. package/src/queues/cli/commands/consumer/add.ts +0 -71
  262. package/src/queues/cli/commands/consumer/index.ts +0 -19
  263. package/src/queues/cli/commands/consumer/remove.ts +0 -31
  264. package/src/queues/cli/commands/create.ts +0 -25
  265. package/src/queues/cli/commands/delete.ts +0 -26
  266. package/src/queues/cli/commands/index.ts +0 -35
  267. package/src/queues/cli/commands/list.ts +0 -25
  268. package/src/queues/client.ts +0 -136
  269. package/src/queues/utils.ts +0 -18
  270. package/src/r2/constants.ts +0 -4
  271. package/src/r2/helpers.ts +0 -132
  272. package/src/r2/index.ts +0 -289
  273. package/src/routes.ts +0 -140
  274. package/src/secret/index.ts +0 -377
  275. package/src/selfsigned.d.ts +0 -29
  276. package/src/sites.ts +0 -484
  277. package/src/tail/createTail.ts +0 -415
  278. package/src/tail/filters.ts +0 -277
  279. package/src/tail/index.ts +0 -211
  280. package/src/tail/printing.ts +0 -132
  281. package/src/traverse-module-graph.ts +0 -54
  282. package/src/tsconfig-sanity.ts +0 -16
  283. package/src/type-generation.ts +0 -181
  284. package/src/update-check.ts +0 -19
  285. package/src/user/access.ts +0 -68
  286. package/src/user/auth-variables.ts +0 -113
  287. package/src/user/choose-account.tsx +0 -39
  288. package/src/user/generate-auth-url.ts +0 -33
  289. package/src/user/generate-random-state.ts +0 -16
  290. package/src/user/index.ts +0 -2
  291. package/src/user/user.ts +0 -1234
  292. package/src/utils/collectKeyValues.ts +0 -14
  293. package/src/utils/render.ts +0 -93
  294. package/src/whoami.ts +0 -135
  295. package/src/worker.ts +0 -279
  296. package/src/yargs-types.ts +0 -37
  297. package/src/zones.ts +0 -191
package/src/user/user.ts DELETED
@@ -1,1234 +0,0 @@
1
- /* Based heavily on code from https://github.com/BitySA/oauth2-auth-code-pkce */
2
-
3
- /*
4
-
5
- Apache License
6
- Version 2.0, January 2004
7
- http://www.apache.org/licenses/
8
-
9
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
10
-
11
- 1. Definitions.
12
-
13
- "License" shall mean the terms and conditions for use, reproduction,
14
- and distribution as defined by Sections 1 through 9 of this document.
15
-
16
- "Licensor" shall mean the copyright owner or entity authorized by
17
- the copyright owner that is granting the License.
18
-
19
- "Legal Entity" shall mean the union of the acting entity and all
20
- other entities that control, are controlled by, or are under common
21
- control with that entity. For the purposes of this definition,
22
- "control" means (i) the power, direct or indirect, to cause the
23
- direction or management of such entity, whether by contract or
24
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
25
- outstanding shares, or (iii) beneficial ownership of such entity.
26
-
27
- "You" (or "Your") shall mean an individual or Legal Entity
28
- exercising permissions granted by this License.
29
-
30
- "Source" form shall mean the preferred form for making modifications,
31
- including but not limited to software source code, documentation
32
- source, and configuration files.
33
-
34
- "Object" form shall mean any form resulting from mechanical
35
- transformation or translation of a Source form, including but
36
- not limited to compiled object code, generated documentation,
37
- and conversions to other media types.
38
-
39
- "Work" shall mean the work of authorship, whether in Source or
40
- Object form, made available under the License, as indicated by a
41
- copyright notice that is included in or attached to the work
42
- (an example is provided in the Appendix below).
43
-
44
- "Derivative Works" shall mean any work, whether in Source or Object
45
- form, that is based on (or derived from) the Work and for which the
46
- editorial revisions, annotations, elaborations, or other modifications
47
- represent, as a whole, an original work of authorship. For the purposes
48
- of this License, Derivative Works shall not include works that remain
49
- separable from, or merely link (or bind by name) to the interfaces of,
50
- the Work and Derivative Works thereof.
51
-
52
- "Contribution" shall mean any work of authorship, including
53
- the original version of the Work and any modifications or additions
54
- to that Work or Derivative Works thereof, that is intentionally
55
- submitted to Licensor for inclusion in the Work by the copyright owner
56
- or by an individual or Legal Entity authorized to submit on behalf of
57
- the copyright owner. For the purposes of this definition, "submitted"
58
- means any form of electronic, verbal, or written communication sent
59
- to the Licensor or its representatives, including but not limited to
60
- communication on electronic mailing lists, source code control systems,
61
- and issue tracking systems that are managed by, or on behalf of, the
62
- Licensor for the purpose of discussing and improving the Work, but
63
- excluding communication that is conspicuously marked or otherwise
64
- designated in writing by the copyright owner as "Not a Contribution."
65
-
66
- "Contributor" shall mean Licensor and any individual or Legal Entity
67
- on behalf of whom a Contribution has been received by Licensor and
68
- subsequently incorporated within the Work.
69
-
70
- 2. Grant of Copyright License. Subject to the terms and conditions of
71
- this License, each Contributor hereby grants to You a perpetual,
72
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
- copyright license to reproduce, prepare Derivative Works of,
74
- publicly display, publicly perform, sublicense, and distribute the
75
- Work and such Derivative Works in Source or Object form.
76
-
77
- 3. Grant of Patent License. Subject to the terms and conditions of
78
- this License, each Contributor hereby grants to You a perpetual,
79
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
80
- (except as stated in this section) patent license to make, have made,
81
- use, offer to sell, sell, import, and otherwise transfer the Work,
82
- where such license applies only to those patent claims licensable
83
- by such Contributor that are necessarily infringed by their
84
- Contribution(s) alone or by combination of their Contribution(s)
85
- with the Work to which such Contribution(s) was submitted. If You
86
- institute patent litigation against any entity (including a
87
- cross-claim or counterclaim in a lawsuit) alleging that the Work
88
- or a Contribution incorporated within the Work constitutes direct
89
- or contributory patent infringement, then any patent licenses
90
- granted to You under this License for that Work shall terminate
91
- as of the date such litigation is filed.
92
-
93
- 4. Redistribution. You may reproduce and distribute copies of the
94
- Work or Derivative Works thereof in any medium, with or without
95
- modifications, and in Source or Object form, provided that You
96
- meet the following conditions:
97
-
98
- (a) You must give any other recipients of the Work or
99
- Derivative Works a copy of this License; and
100
-
101
- (b) You must cause any modified files to carry prominent notices
102
- stating that You changed the files; and
103
-
104
- (c) You must retain, in the Source form of any Derivative Works
105
- that You distribute, all copyright, patent, trademark, and
106
- attribution notices from the Source form of the Work,
107
- excluding those notices that do not pertain to any part of
108
- the Derivative Works; and
109
-
110
- (d) If the Work includes a "NOTICE" text file as part of its
111
- distribution, then any Derivative Works that You distribute must
112
- include a readable copy of the attribution notices contained
113
- within such NOTICE file, excluding those notices that do not
114
- pertain to any part of the Derivative Works, in at least one
115
- of the following places: within a NOTICE text file distributed
116
- as part of the Derivative Works; within the Source form or
117
- documentation, if provided along with the Derivative Works; or,
118
- within a display generated by the Derivative Works, if and
119
- wherever such third-party notices normally appear. The contents
120
- of the NOTICE file are for informational purposes only and
121
- do not modify the License. You may add Your own attribution
122
- notices within Derivative Works that You distribute, alongside
123
- or as an addendum to the NOTICE text from the Work, provided
124
- that such additional attribution notices cannot be construed
125
- as modifying the License.
126
-
127
- You may add Your own copyright statement to Your modifications and
128
- may provide additional or different license terms and conditions
129
- for use, reproduction, or distribution of Your modifications, or
130
- for any such Derivative Works as a whole, provided Your use,
131
- reproduction, and distribution of the Work otherwise complies with
132
- the conditions stated in this License.
133
-
134
- 5. Submission of Contributions. Unless You explicitly state otherwise,
135
- any Contribution intentionally submitted for inclusion in the Work
136
- by You to the Licensor shall be under the terms and conditions of
137
- this License, without any additional terms or conditions.
138
- Notwithstanding the above, nothing herein shall supersede or modify
139
- the terms of any separate license agreement you may have executed
140
- with Licensor regarding such Contributions.
141
-
142
- 6. Trademarks. This License does not grant permission to use the trade
143
- names, trademarks, service marks, or product names of the Licensor,
144
- except as required for reasonable and customary use in describing the
145
- origin of the Work and reproducing the content of the NOTICE file.
146
-
147
- 7. Disclaimer of Warranty. Unless required by applicable law or
148
- agreed to in writing, Licensor provides the Work (and each
149
- Contributor provides its Contributions) on an "AS IS" BASIS,
150
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
151
- implied, including, without limitation, any warranties or conditions
152
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
153
- PARTICULAR PURPOSE. You are solely responsible for determining the
154
- appropriateness of using or redistributing the Work and assume any
155
- risks associated with Your exercise of permissions under this License.
156
-
157
- 8. Limitation of Liability. In no event and under no legal theory,
158
- whether in tort (including negligence), contract, or otherwise,
159
- unless required by applicable law (such as deliberate and grossly
160
- negligent acts) or agreed to in writing, shall any Contributor be
161
- liable to You for damages, including any direct, indirect, special,
162
- incidental, or consequential damages of any character arising as a
163
- result of this License or out of the use or inability to use the
164
- Work (including but not limited to damages for loss of goodwill,
165
- work stoppage, computer failure or malfunction, or any and all
166
- other commercial damages or losses), even if such Contributor
167
- has been advised of the possibility of such damages.
168
-
169
- 9. Accepting Warranty or Additional Liability. While redistributing
170
- the Work or Derivative Works thereof, You may choose to offer,
171
- and charge a fee for, acceptance of support, warranty, indemnity,
172
- or other liability obligations and/or rights consistent with this
173
- License. However, in accepting such obligations, You may act only
174
- on Your own behalf and on Your sole responsibility, not on behalf
175
- of any other Contributor, and only if You agree to indemnify,
176
- defend, and hold each Contributor harmless for any liability
177
- incurred by, or claims asserted against, such Contributor by reason
178
- of your accepting any such warranty or additional liability.
179
-
180
- END OF TERMS AND CONDITIONS
181
-
182
- APPENDIX: How to apply the Apache License to your work.
183
-
184
- To apply the Apache License to your work, attach the following
185
- boilerplate notice, with the fields enclosed by brackets "[]"
186
- replaced with your own identifying information. (Don't include
187
- the brackets!) The text should be enclosed in the appropriate
188
- comment syntax for the file format. We also recommend that a
189
- file or class name and description of purpose be included on the
190
- same "printed page" as the copyright notice for easier
191
- identification within third-party archives.
192
-
193
- Copyright [yyyy] [name of copyright owner]
194
-
195
- Licensed under the Apache License, Version 2.0 (the "License");
196
- you may not use this file except in compliance with the License.
197
- You may obtain a copy of the License at
198
-
199
- http://www.apache.org/licenses/LICENSE-2.0
200
-
201
- Unless required by applicable law or agreed to in writing, software
202
- distributed under the License is distributed on an "AS IS" BASIS,
203
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
204
- See the License for the specific language governing permissions and
205
- limitations under the License.
206
- */
207
-
208
- import assert from "node:assert";
209
- import { webcrypto as crypto } from "node:crypto";
210
- import { mkdirSync, rmSync, writeFileSync } from "node:fs";
211
- import http from "node:http";
212
- import path from "node:path";
213
- import url from "node:url";
214
- import { TextEncoder } from "node:util";
215
- import TOML from "@iarna/toml";
216
- import { HostURL } from "@webcontainer/env";
217
- import { fetch } from "undici";
218
- import {
219
- getConfigCache,
220
- purgeConfigCaches,
221
- saveToConfigCache,
222
- } from "../config-cache";
223
- import { NoDefaultValueProvided, select } from "../dialogs";
224
- import { getGlobalWranglerConfigPath } from "../global-wrangler-config-path";
225
- import { CI } from "../is-ci";
226
- import isInteractive from "../is-interactive";
227
- import { logger } from "../logger";
228
- import openInBrowser from "../open-in-browser";
229
- import { parseTOML, readFileSync } from "../parse";
230
- import { domainUsesAccess } from "./access";
231
- import {
232
- getAuthDomainFromEnv,
233
- getAuthUrlFromEnv,
234
- getClientIdFromEnv,
235
- getCloudflareAccessToken,
236
- getCloudflareAPITokenFromEnv,
237
- getCloudflareGlobalAuthEmailFromEnv,
238
- getCloudflareGlobalAuthKeyFromEnv,
239
- getRevokeUrlFromEnv,
240
- getTokenUrlFromEnv,
241
- } from "./auth-variables";
242
- import { getAccountChoices } from "./choose-account";
243
- import { generateAuthUrl } from "./generate-auth-url";
244
- import { generateRandomState } from "./generate-random-state";
245
- import type { ChooseAccountItem } from "./choose-account";
246
- import type { ParsedUrlQuery } from "node:querystring";
247
-
248
- export type ApiCredentials =
249
- | {
250
- apiToken: string;
251
- }
252
- | {
253
- authKey: string;
254
- authEmail: string;
255
- };
256
-
257
- /**
258
- * Try to read an API token or Global Auth from the environment.
259
- */
260
- export function getAuthFromEnv(): ApiCredentials | undefined {
261
- const globalApiKey = getCloudflareGlobalAuthKeyFromEnv();
262
- const globalApiEmail = getCloudflareGlobalAuthEmailFromEnv();
263
- const apiToken = getCloudflareAPITokenFromEnv();
264
-
265
- if (globalApiKey && globalApiEmail) {
266
- return { authKey: globalApiKey, authEmail: globalApiEmail };
267
- } else if (apiToken) {
268
- return { apiToken };
269
- }
270
- }
271
-
272
- /**
273
- * An implementation of rfc6749#section-4.1 and rfc7636.
274
- */
275
-
276
- interface PKCECodes {
277
- codeChallenge: string;
278
- codeVerifier: string;
279
- }
280
-
281
- /**
282
- * The module level state of the authentication flow.
283
- */
284
- interface State extends AuthTokens {
285
- authorizationCode?: string;
286
- codeChallenge?: string;
287
- codeVerifier?: string;
288
- hasAuthCodeBeenExchangedForAccessToken?: boolean;
289
- stateQueryParam?: string;
290
- scopes?: Scope[];
291
- }
292
-
293
- /**
294
- * The tokens related to authentication.
295
- */
296
- interface AuthTokens {
297
- accessToken?: AccessToken;
298
- refreshToken?: RefreshToken;
299
- scopes?: Scope[];
300
- /** @deprecated - this field was only provided by the deprecated v1 `wrangler config` command. */
301
- apiToken?: string;
302
- }
303
-
304
- /**
305
- * The path to the config file that holds user authentication data,
306
- * relative to the user's home directory.
307
- */
308
- export const USER_AUTH_CONFIG_FILE = "config/default.toml";
309
-
310
- /**
311
- * The data that may be read from the `USER_CONFIG_FILE`.
312
- */
313
- export interface UserAuthConfig {
314
- oauth_token?: string;
315
- refresh_token?: string;
316
- expiration_time?: string;
317
- scopes?: string[];
318
- /** @deprecated - this field was only provided by the deprecated v1 `wrangler config` command. */
319
- api_token?: string;
320
- }
321
-
322
- interface RefreshToken {
323
- value: string;
324
- }
325
-
326
- interface AccessToken {
327
- value: string;
328
- expiry: string;
329
- }
330
-
331
- const Scopes = {
332
- "account:read":
333
- "See your account info such as account details, analytics, and memberships.",
334
- "user:read":
335
- "See your user info such as name, email address, and account memberships.",
336
- "workers:write":
337
- "See and change Cloudflare Workers data such as zones, KV storage, namespaces, scripts, and routes.",
338
- "workers_kv:write":
339
- "See and change Cloudflare Workers KV Storage data such as keys and namespaces.",
340
- "workers_routes:write":
341
- "See and change Cloudflare Workers data such as filters and routes.",
342
- "workers_scripts:write":
343
- "See and change Cloudflare Workers scripts, durable objects, subdomains, triggers, and tail data.",
344
- "workers_tail:read": "See Cloudflare Workers tail and script data.",
345
- "d1:write": "See and change D1 Databases.",
346
- "pages:write":
347
- "See and change Cloudflare Pages projects, settings and deployments.",
348
- "zone:read": "Grants read level access to account zone.",
349
- "ssl_certs:write": "See and manage mTLS certificates for your account",
350
- "constellation:write": "Manage Constellation AI projects/models",
351
- } as const;
352
-
353
- /**
354
- * The possible keys for a Scope.
355
- *
356
- * "offline_access" is automatically included.
357
- */
358
- type Scope = keyof typeof Scopes;
359
-
360
- const ScopeKeys = Object.keys(Scopes) as Scope[];
361
-
362
- export function validateScopeKeys(
363
- scopes: string[]
364
- ): scopes is typeof ScopeKeys {
365
- return scopes.every((scope) => scope in Scopes);
366
- }
367
-
368
- /**
369
- * To allow OAuth callbacks in environments such as WebContainer we need to
370
- * create a host URL which only resolves `localhost` to a WebContainer
371
- * hostname if the process is running in a WebContainer. On local this will
372
- * be a no-op and it leaves the URL unmodified.
373
- *
374
- * @see https://www.npmjs.com/package/@webcontainer/env
375
- */
376
- const CALLBACK_URL = HostURL.parse("http://localhost:8976/oauth/callback").href;
377
-
378
- let LocalState: State = {
379
- ...getAuthTokens(),
380
- };
381
-
382
- /**
383
- * Compute the current auth tokens.
384
- */
385
- function getAuthTokens(config?: UserAuthConfig): AuthTokens | undefined {
386
- // get refreshToken/accessToken from fs if exists
387
- try {
388
- // if the environment variable is available, we don't need to do anything here
389
- if (getAuthFromEnv()) return;
390
-
391
- // otherwise try loading from the user auth config file.
392
- const { oauth_token, refresh_token, expiration_time, scopes, api_token } =
393
- config || readAuthConfigFile();
394
-
395
- if (oauth_token) {
396
- return {
397
- accessToken: {
398
- value: oauth_token,
399
- // If there is no `expiration_time` field then set it to an old date, to cause it to expire immediately.
400
- expiry: expiration_time ?? "2000-01-01:00:00:00+00:00",
401
- },
402
- refreshToken: { value: refresh_token ?? "" },
403
- scopes: scopes as Scope[],
404
- };
405
- } else if (api_token) {
406
- logger.warn(
407
- "It looks like you have used Wrangler v1's `config` command to login with an API token.\n" +
408
- "This is no longer supported in the current version of Wrangler.\n" +
409
- "If you wish to authenticate via an API token then please set the `CLOUDFLARE_API_TOKEN` environment variable."
410
- );
411
- return { apiToken: api_token };
412
- }
413
- } catch {
414
- return undefined;
415
- }
416
- }
417
-
418
- /**
419
- * Run the initialization of the auth state, in the case that something changed.
420
- *
421
- * This runs automatically whenever `writeAuthConfigFile` is run, so generally
422
- * you won't need to call it yourself.
423
- */
424
- export function reinitialiseAuthTokens(): void;
425
-
426
- /**
427
- * Reinitialise auth state from an in-memory config, skipping
428
- * over the part where we write a file and then read it back into memory
429
- */
430
- export function reinitialiseAuthTokens(config: UserAuthConfig): void;
431
-
432
- export function reinitialiseAuthTokens(config?: UserAuthConfig): void {
433
- LocalState = {
434
- ...getAuthTokens(config),
435
- };
436
- }
437
-
438
- export function getAPIToken(): ApiCredentials | undefined {
439
- if (LocalState.apiToken) {
440
- return { apiToken: LocalState.apiToken };
441
- }
442
-
443
- const localAPIToken = getAuthFromEnv();
444
- if (localAPIToken) return localAPIToken;
445
-
446
- const storedAccessToken = LocalState.accessToken?.value;
447
- if (storedAccessToken) return { apiToken: storedAccessToken };
448
-
449
- return undefined;
450
- }
451
-
452
- interface AccessContext {
453
- token?: AccessToken;
454
- scopes?: Scope[];
455
- refreshToken?: RefreshToken;
456
- }
457
-
458
- /**
459
- * A list of OAuth2AuthCodePKCE errors.
460
- */
461
- // To "namespace" all errors.
462
- class ErrorOAuth2 extends Error {
463
- toString(): string {
464
- return "ErrorOAuth2";
465
- }
466
- }
467
-
468
- // For really unknown errors.
469
- class ErrorUnknown extends ErrorOAuth2 {
470
- toString(): string {
471
- return "ErrorUnknown";
472
- }
473
- }
474
-
475
- // Some generic, internal errors that can happen.
476
- class ErrorNoAuthCode extends ErrorOAuth2 {
477
- toString(): string {
478
- return "ErrorNoAuthCode";
479
- }
480
- }
481
- class ErrorInvalidReturnedStateParam extends ErrorOAuth2 {
482
- toString(): string {
483
- return "ErrorInvalidReturnedStateParam";
484
- }
485
- }
486
- class ErrorInvalidJson extends ErrorOAuth2 {
487
- toString(): string {
488
- return "ErrorInvalidJson";
489
- }
490
- }
491
-
492
- // Errors that occur across many endpoints
493
- class ErrorInvalidScope extends ErrorOAuth2 {
494
- toString(): string {
495
- return "ErrorInvalidScope";
496
- }
497
- }
498
- class ErrorInvalidRequest extends ErrorOAuth2 {
499
- toString(): string {
500
- return "ErrorInvalidRequest";
501
- }
502
- }
503
- class ErrorInvalidToken extends ErrorOAuth2 {
504
- toString(): string {
505
- return "ErrorInvalidToken";
506
- }
507
- }
508
-
509
- /**
510
- * Possible authorization grant errors given by the redirection from the
511
- * authorization server.
512
- */
513
- class ErrorAuthenticationGrant extends ErrorOAuth2 {
514
- toString(): string {
515
- return "ErrorAuthenticationGrant";
516
- }
517
- }
518
- class ErrorUnauthorizedClient extends ErrorAuthenticationGrant {
519
- toString(): string {
520
- return "ErrorUnauthorizedClient";
521
- }
522
- }
523
- class ErrorAccessDenied extends ErrorAuthenticationGrant {
524
- toString(): string {
525
- return "ErrorAccessDenied";
526
- }
527
- }
528
- class ErrorUnsupportedResponseType extends ErrorAuthenticationGrant {
529
- toString(): string {
530
- return "ErrorUnsupportedResponseType";
531
- }
532
- }
533
- class ErrorServerError extends ErrorAuthenticationGrant {
534
- toString(): string {
535
- return "ErrorServerError";
536
- }
537
- }
538
- class ErrorTemporarilyUnavailable extends ErrorAuthenticationGrant {
539
- toString(): string {
540
- return "ErrorTemporarilyUnavailable";
541
- }
542
- }
543
-
544
- /**
545
- * A list of possible access token response errors.
546
- */
547
- class ErrorAccessTokenResponse extends ErrorOAuth2 {
548
- toString(): string {
549
- return "ErrorAccessTokenResponse";
550
- }
551
- }
552
- class ErrorInvalidClient extends ErrorAccessTokenResponse {
553
- toString(): string {
554
- return "ErrorInvalidClient";
555
- }
556
- }
557
- class ErrorInvalidGrant extends ErrorAccessTokenResponse {
558
- toString(): string {
559
- return "ErrorInvalidGrant";
560
- }
561
- }
562
- class ErrorUnsupportedGrantType extends ErrorAccessTokenResponse {
563
- toString(): string {
564
- return "ErrorUnsupportedGrantType";
565
- }
566
- }
567
-
568
- const RawErrorToErrorClassMap: { [_: string]: typeof ErrorOAuth2 } = {
569
- invalid_request: ErrorInvalidRequest,
570
- invalid_grant: ErrorInvalidGrant,
571
- unauthorized_client: ErrorUnauthorizedClient,
572
- access_denied: ErrorAccessDenied,
573
- unsupported_response_type: ErrorUnsupportedResponseType,
574
- invalid_scope: ErrorInvalidScope,
575
- server_error: ErrorServerError,
576
- temporarily_unavailable: ErrorTemporarilyUnavailable,
577
- invalid_client: ErrorInvalidClient,
578
- unsupported_grant_type: ErrorUnsupportedGrantType,
579
- invalid_json: ErrorInvalidJson,
580
- invalid_token: ErrorInvalidToken,
581
- };
582
-
583
- /**
584
- * Translate the raw error strings returned from the server into error classes.
585
- */
586
- function toErrorClass(rawError: string): ErrorOAuth2 {
587
- return new (RawErrorToErrorClassMap[rawError] || ErrorUnknown)();
588
- }
589
-
590
- /**
591
- * The maximum length for a code verifier for the best security we can offer.
592
- * Please note the NOTE section of RFC 7636 § 4.1 - the length must be >= 43,
593
- * but <= 128, **after** base64 url encoding. This means 32 code verifier bytes
594
- * encoded will be 43 bytes, or 96 bytes encoded will be 128 bytes. So 96 bytes
595
- * is the highest valid value that can be used.
596
- */
597
- const RECOMMENDED_CODE_VERIFIER_LENGTH = 96;
598
-
599
- /**
600
- * A sensible length for the state's length, for anti-csrf.
601
- */
602
- const RECOMMENDED_STATE_LENGTH = 32;
603
-
604
- /**
605
- * Character set to generate code verifier defined in rfc7636.
606
- */
607
- export const PKCE_CHARSET =
608
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
609
-
610
- /**
611
- * OAuth 2.0 client that ONLY supports authorization code flow, with PKCE.
612
- */
613
-
614
- /**
615
- * If there is an error, it will be passed back as a rejected Promise.
616
- * If there is no code, the user should be redirected via
617
- * [fetchAuthorizationCode].
618
- */
619
- function isReturningFromAuthServer(query: ParsedUrlQuery): boolean {
620
- if (query.error) {
621
- if (Array.isArray(query.error)) {
622
- throw toErrorClass(query.error[0]);
623
- }
624
- throw toErrorClass(query.error);
625
- }
626
-
627
- const code = query.code;
628
- if (!code) {
629
- return false;
630
- }
631
-
632
- const state = LocalState;
633
-
634
- const stateQueryParam = query.state;
635
- if (stateQueryParam !== state.stateQueryParam) {
636
- logger.warn(
637
- "Received query string parameter doesn't match the one sent! Possible malicious activity somewhere."
638
- );
639
- throw new ErrorInvalidReturnedStateParam();
640
- }
641
- assert(!Array.isArray(code));
642
- state.authorizationCode = code;
643
- state.hasAuthCodeBeenExchangedForAccessToken = false;
644
- return true;
645
- }
646
-
647
- export async function getAuthURL(scopes = ScopeKeys): Promise<string> {
648
- const { codeChallenge, codeVerifier } = await generatePKCECodes();
649
- const stateQueryParam = generateRandomState(RECOMMENDED_STATE_LENGTH);
650
-
651
- Object.assign(LocalState, {
652
- codeChallenge,
653
- codeVerifier,
654
- stateQueryParam,
655
- });
656
-
657
- return generateAuthUrl({
658
- authUrl: getAuthUrlFromEnv(),
659
- clientId: getClientIdFromEnv(),
660
- callbackUrl: CALLBACK_URL,
661
- scopes,
662
- stateQueryParam,
663
- codeChallenge,
664
- });
665
- }
666
-
667
- type TokenResponse =
668
- | {
669
- access_token: string;
670
- expires_in: number;
671
- refresh_token: string;
672
- scope: string;
673
- }
674
- | {
675
- error: string;
676
- };
677
-
678
- /**
679
- * Refresh an access token from the remote service.
680
- */
681
- async function exchangeRefreshTokenForAccessToken(): Promise<AccessContext> {
682
- if (!LocalState.refreshToken) {
683
- logger.warn("No refresh token is present.");
684
- }
685
-
686
- const params = new URLSearchParams({
687
- grant_type: "refresh_token",
688
- refresh_token: LocalState.refreshToken?.value ?? "",
689
- client_id: getClientIdFromEnv(),
690
- });
691
-
692
- const response = await fetchAuthToken(params);
693
-
694
- if (response.status >= 400) {
695
- let tokenExchangeResErr = undefined;
696
-
697
- try {
698
- tokenExchangeResErr = await response.text();
699
- tokenExchangeResErr = JSON.parse(tokenExchangeResErr);
700
- } catch (e) {
701
- // If it can't parse to JSON ignore the error
702
- }
703
-
704
- if (tokenExchangeResErr !== undefined) {
705
- // We will throw the parsed error if it parsed correctly, otherwise we throw an unknown error.
706
- throw typeof tokenExchangeResErr === "string"
707
- ? new Error(tokenExchangeResErr)
708
- : tokenExchangeResErr;
709
- } else {
710
- throw new ErrorUnknown(
711
- "Failed to parse Error from exchangeRefreshTokenForAccessToken"
712
- );
713
- }
714
- } else {
715
- try {
716
- const json = (await response.json()) as TokenResponse;
717
- if ("error" in json) {
718
- throw json.error;
719
- }
720
-
721
- const { access_token, expires_in, refresh_token, scope } = json;
722
- let scopes: Scope[] = [];
723
-
724
- const accessToken: AccessToken = {
725
- value: access_token,
726
- expiry: new Date(Date.now() + expires_in * 1000).toISOString(),
727
- };
728
- LocalState.accessToken = accessToken;
729
-
730
- if (refresh_token) {
731
- LocalState.refreshToken = {
732
- value: refresh_token,
733
- };
734
- }
735
-
736
- if (scope) {
737
- // Multiple scopes are passed and delimited by spaces,
738
- // despite using the singular name "scope".
739
- scopes = scope.split(" ") as Scope[];
740
- LocalState.scopes = scopes;
741
- }
742
-
743
- const accessContext: AccessContext = {
744
- token: accessToken,
745
- scopes,
746
- refreshToken: LocalState.refreshToken,
747
- };
748
- return accessContext;
749
- } catch (error) {
750
- if (typeof error === "string") {
751
- throw toErrorClass(error);
752
- } else {
753
- throw error;
754
- }
755
- }
756
- }
757
- }
758
-
759
- /**
760
- * Fetch an access token from the remote service.
761
- */
762
- async function exchangeAuthCodeForAccessToken(): Promise<AccessContext> {
763
- const { authorizationCode, codeVerifier = "" } = LocalState;
764
-
765
- if (!codeVerifier) {
766
- logger.warn("No code verifier is being sent.");
767
- } else if (!authorizationCode) {
768
- logger.warn("No authorization grant code is being passed.");
769
- }
770
-
771
- const params = new URLSearchParams({
772
- grant_type: `authorization_code`,
773
- code: authorizationCode ?? "",
774
- redirect_uri: CALLBACK_URL,
775
- client_id: getClientIdFromEnv(),
776
- code_verifier: codeVerifier,
777
- });
778
-
779
- const response = await fetchAuthToken(params);
780
- if (!response.ok) {
781
- const { error } = (await response.json()) as { error: string };
782
- // .catch((_) => ({ error: "invalid_json" }));
783
- if (error === "invalid_grant") {
784
- logger.log("Expired! Auth code or refresh token needs to be renewed.");
785
- // alert("Redirecting to auth server to obtain a new auth grant code.");
786
- // TODO: return refreshAuthCodeOrRefreshToken();
787
- }
788
- throw toErrorClass(error);
789
- }
790
- const json = (await response.json()) as TokenResponse;
791
- if ("error" in json) {
792
- throw new Error(json.error);
793
- }
794
- const { access_token, expires_in, refresh_token, scope } = json;
795
- let scopes: Scope[] = [];
796
- LocalState.hasAuthCodeBeenExchangedForAccessToken = true;
797
-
798
- const expiryDate = new Date(Date.now() + expires_in * 1000);
799
- const accessToken: AccessToken = {
800
- value: access_token,
801
- expiry: expiryDate.toISOString(),
802
- };
803
- LocalState.accessToken = accessToken;
804
-
805
- if (refresh_token) {
806
- LocalState.refreshToken = {
807
- value: refresh_token,
808
- };
809
- }
810
-
811
- if (scope) {
812
- // Multiple scopes are passed and delimited by spaces,
813
- // despite using the singular name "scope".
814
- scopes = scope.split(" ") as Scope[];
815
- LocalState.scopes = scopes;
816
- }
817
-
818
- const accessContext: AccessContext = {
819
- token: accessToken,
820
- scopes,
821
- refreshToken: LocalState.refreshToken,
822
- };
823
- return accessContext;
824
- }
825
-
826
- /**
827
- * Implements *base64url-encode* (RFC 4648 § 5) without padding, which is NOT
828
- * the same as regular base64 encoding.
829
- */
830
- function base64urlEncode(value: string): string {
831
- let base64 = btoa(value);
832
- base64 = base64.replace(/\+/g, "-");
833
- base64 = base64.replace(/\//g, "_");
834
- base64 = base64.replace(/=/g, "");
835
- return base64;
836
- }
837
-
838
- /**
839
- * Generates a code_verifier and code_challenge, as specified in rfc7636.
840
- */
841
-
842
- async function generatePKCECodes(): Promise<PKCECodes> {
843
- const output = new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);
844
- // @ts-expect-error crypto's types aren't there yet
845
- crypto.getRandomValues(output);
846
- const codeVerifier = base64urlEncode(
847
- Array.from(output)
848
- .map((num: number) => PKCE_CHARSET[num % PKCE_CHARSET.length])
849
- .join("")
850
- );
851
- // @ts-expect-error crypto's types aren't there yet
852
- const buffer = await crypto.subtle.digest(
853
- "SHA-256",
854
- new TextEncoder().encode(codeVerifier)
855
- );
856
- const hash = new Uint8Array(buffer);
857
- let binary = "";
858
- const hashLength = hash.byteLength;
859
- for (let i = 0; i < hashLength; i++) {
860
- binary += String.fromCharCode(hash[i]);
861
- }
862
- const codeChallenge = base64urlEncode(binary);
863
- return { codeChallenge, codeVerifier };
864
- }
865
-
866
- /**
867
- * Writes a a wrangler config file (auth credentials) to disk,
868
- * and updates the user auth state with the new credentials.
869
- */
870
- export function writeAuthConfigFile(config: UserAuthConfig) {
871
- const authConfigFilePath = path.join(
872
- getGlobalWranglerConfigPath(),
873
- USER_AUTH_CONFIG_FILE
874
- );
875
- mkdirSync(path.dirname(authConfigFilePath), {
876
- recursive: true,
877
- });
878
- writeFileSync(
879
- path.join(authConfigFilePath),
880
- TOML.stringify(config as TOML.JsonMap),
881
- { encoding: "utf-8" }
882
- );
883
-
884
- reinitialiseAuthTokens();
885
- }
886
-
887
- export function readAuthConfigFile(): UserAuthConfig {
888
- const authConfigFilePath = path.join(
889
- getGlobalWranglerConfigPath(),
890
- USER_AUTH_CONFIG_FILE
891
- );
892
- const toml = parseTOML(readFileSync(authConfigFilePath));
893
- return toml;
894
- }
895
-
896
- type LoginProps = {
897
- scopes?: Scope[];
898
- browser: boolean;
899
- };
900
-
901
- export async function loginOrRefreshIfRequired(): Promise<boolean> {
902
- // TODO: if there already is a token, then try refreshing
903
- // TODO: ask permission before opening browser
904
- const { isCI } = CI;
905
- if (!getAPIToken()) {
906
- // Not logged in.
907
- // If we are not interactive, we cannot ask the user to login
908
- return isInteractive() && !isCI() && (await login());
909
- } else if (isAccessTokenExpired()) {
910
- // We're logged in, but the refresh token seems to have expired,
911
- // so let's try to refresh it
912
- const didRefresh = await refreshToken();
913
- if (didRefresh) {
914
- // The token was refreshed, so we're done here
915
- return true;
916
- } else {
917
- // If the refresh token isn't valid, then we ask the user to login again
918
- return isInteractive() && !isCI() && (await login());
919
- }
920
- } else {
921
- return true;
922
- }
923
- }
924
-
925
- export async function login(
926
- props: LoginProps = { browser: true }
927
- ): Promise<boolean> {
928
- logger.log("Attempting to login via OAuth...");
929
- const urlToOpen = await getAuthURL(props?.scopes);
930
- let server: http.Server;
931
- let loginTimeoutHandle: NodeJS.Timeout;
932
- const timerPromise = new Promise<boolean>((resolve) => {
933
- loginTimeoutHandle = setTimeout(() => {
934
- logger.error(
935
- "Timed out waiting for authorization code, please try again."
936
- );
937
- server.close();
938
- clearTimeout(loginTimeoutHandle);
939
- resolve(false);
940
- }, 120000); // wait for 120 seconds for the user to authorize
941
- });
942
-
943
- const loginPromise = new Promise<boolean>((resolve, reject) => {
944
- server = http.createServer(async (req, res) => {
945
- function finish(status: boolean, error?: Error) {
946
- clearTimeout(loginTimeoutHandle);
947
- server.close((closeErr?: Error) => {
948
- if (error || closeErr) {
949
- reject(error || closeErr);
950
- } else resolve(status);
951
- });
952
- }
953
-
954
- assert(req.url, "This request doesn't have a URL"); // This should never happen
955
- const { pathname, query } = url.parse(req.url, true);
956
- switch (pathname) {
957
- case "/oauth/callback": {
958
- let hasAuthCode = false;
959
- try {
960
- hasAuthCode = isReturningFromAuthServer(query);
961
- } catch (err: unknown) {
962
- if (err instanceof ErrorAccessDenied) {
963
- res.writeHead(307, {
964
- Location:
965
- "https://welcome.developers.workers.dev/wrangler-oauth-consent-denied",
966
- });
967
- res.end(() => {
968
- finish(false);
969
- });
970
- logger.error(
971
- "Error: Consent denied. You must grant consent to Wrangler in order to login.\n" +
972
- "If you don't want to do this consider passing an API token via the `CLOUDFLARE_API_TOKEN` environment variable"
973
- );
974
-
975
- return;
976
- } else {
977
- finish(false, err as Error);
978
- return;
979
- }
980
- }
981
- if (!hasAuthCode) {
982
- // render an error page here
983
- finish(false, new ErrorNoAuthCode());
984
- return;
985
- } else {
986
- const exchange = await exchangeAuthCodeForAccessToken();
987
- writeAuthConfigFile({
988
- oauth_token: exchange.token?.value ?? "",
989
- expiration_time: exchange.token?.expiry,
990
- refresh_token: exchange.refreshToken?.value,
991
- scopes: exchange.scopes,
992
- });
993
- res.writeHead(307, {
994
- Location:
995
- "https://welcome.developers.workers.dev/wrangler-oauth-consent-granted",
996
- });
997
- res.end(() => {
998
- finish(true);
999
- });
1000
- logger.log(`Successfully logged in.`);
1001
-
1002
- purgeConfigCaches();
1003
-
1004
- return;
1005
- }
1006
- }
1007
- }
1008
- });
1009
-
1010
- server.listen(8976);
1011
- });
1012
- if (props?.browser) {
1013
- logger.log(`Opening a link in your default browser: ${urlToOpen}`);
1014
- await openInBrowser(urlToOpen);
1015
- } else {
1016
- logger.log(`Visit this link to authenticate: ${urlToOpen}`);
1017
- }
1018
-
1019
- return Promise.race([timerPromise, loginPromise]);
1020
- }
1021
-
1022
- /**
1023
- * Checks to see if the access token has expired.
1024
- */
1025
- function isAccessTokenExpired(): boolean {
1026
- const { accessToken } = LocalState;
1027
- return Boolean(accessToken && new Date() >= new Date(accessToken.expiry));
1028
- }
1029
-
1030
- async function refreshToken(): Promise<boolean> {
1031
- // refresh
1032
- try {
1033
- const {
1034
- token: { value: oauth_token, expiry: expiration_time } = {
1035
- value: "",
1036
- expiry: "",
1037
- },
1038
- refreshToken: { value: refresh_token } = {},
1039
- scopes,
1040
- } = await exchangeRefreshTokenForAccessToken();
1041
- writeAuthConfigFile({
1042
- oauth_token,
1043
- expiration_time,
1044
- refresh_token,
1045
- scopes,
1046
- });
1047
- return true;
1048
- } catch (err) {
1049
- return false;
1050
- }
1051
- }
1052
-
1053
- export async function logout(): Promise<void> {
1054
- if (!LocalState.accessToken) {
1055
- if (!LocalState.refreshToken) {
1056
- logger.log("Not logged in, exiting...");
1057
- return;
1058
- }
1059
-
1060
- const body =
1061
- `client_id=${encodeURIComponent(getClientIdFromEnv())}&` +
1062
- `token_type_hint=refresh_token&` +
1063
- `token=${encodeURIComponent(LocalState.refreshToken?.value || "")}`;
1064
-
1065
- const response = await fetch(getRevokeUrlFromEnv(), {
1066
- method: "POST",
1067
- body,
1068
- headers: {
1069
- "Content-Type": "application/x-www-form-urlencoded",
1070
- },
1071
- });
1072
- await response.text(); // blank text? would be nice if it was something meaningful
1073
- logger.log(
1074
- "💁 Wrangler is configured with an OAuth token. The token has been successfully revoked"
1075
- );
1076
- }
1077
- const body =
1078
- `client_id=${encodeURIComponent(getClientIdFromEnv())}&` +
1079
- `token_type_hint=refresh_token&` +
1080
- `token=${encodeURIComponent(LocalState.refreshToken?.value || "")}`;
1081
-
1082
- const response = await fetch(getRevokeUrlFromEnv(), {
1083
- method: "POST",
1084
- body,
1085
- headers: {
1086
- "Content-Type": "application/x-www-form-urlencoded",
1087
- },
1088
- });
1089
- await response.text(); // blank text? would be nice if it was something meaningful
1090
- rmSync(path.join(getGlobalWranglerConfigPath(), USER_AUTH_CONFIG_FILE));
1091
- logger.log(`Successfully logged out.`);
1092
- }
1093
-
1094
- export function listScopes(message = "💁 Available scopes:"): void {
1095
- logger.log(message);
1096
- const data = ScopeKeys.map((scope: Scope) => ({
1097
- Scope: scope,
1098
- Description: Scopes[scope],
1099
- }));
1100
- logger.table(data);
1101
- // TODO: maybe a good idea to show usage here
1102
- }
1103
-
1104
- export async function getAccountId(): Promise<string | undefined> {
1105
- const apiToken = getAPIToken();
1106
- if (!apiToken) return;
1107
-
1108
- // check if we have a cached value
1109
- const cachedAccount = getAccountFromCache();
1110
- if (cachedAccount) {
1111
- return cachedAccount.id;
1112
- }
1113
- const accounts = await getAccountChoices();
1114
- if (accounts.length === 1) {
1115
- saveAccountToCache({ id: accounts[0].id, name: accounts[0].name });
1116
- return accounts[0].id;
1117
- }
1118
-
1119
- try {
1120
- const accountID = await select("Select an account", {
1121
- choices: accounts.map((account) => ({
1122
- title: account.name,
1123
- value: account.id,
1124
- })),
1125
- });
1126
- const account = accounts.find(
1127
- (a) => a.id === accountID
1128
- ) as ChooseAccountItem;
1129
- saveAccountToCache({ id: account.id, name: account.name });
1130
- return accountID;
1131
- } catch (e) {
1132
- // Did we try to select an account in CI or a non-interactive terminal?
1133
- if (e instanceof NoDefaultValueProvided) {
1134
- throw new Error(
1135
- `More than one account available but unable to select one in non-interactive mode.
1136
- Please set the appropriate \`account_id\` in your \`wrangler.toml\` file.
1137
- Available accounts are (\`<name>\`: \`<account_id>\`):
1138
- ${accounts
1139
- .map((account) => ` \`${account.name}\`: \`${account.id}\``)
1140
- .join("\n")}`
1141
- );
1142
- }
1143
- throw e;
1144
- }
1145
- }
1146
-
1147
- /**
1148
- * Ensure that a user is logged in, and a valid account_id is available.
1149
- */
1150
- export async function requireAuth(config: {
1151
- account_id?: string;
1152
- }): Promise<string> {
1153
- const loggedIn = await loginOrRefreshIfRequired();
1154
- if (!loggedIn) {
1155
- if (!isInteractive() || CI.isCI()) {
1156
- throw new Error(
1157
- "In a non-interactive environment, it's necessary to set a CLOUDFLARE_API_TOKEN environment variable for wrangler to work. Please go to https://developers.cloudflare.com/fundamentals/api/get-started/create-token/ for instructions on how to create an api token, and assign its value to CLOUDFLARE_API_TOKEN."
1158
- );
1159
- } else {
1160
- // didn't login, let's just quit
1161
- throw new Error("Did not login, quitting...");
1162
- }
1163
- }
1164
- const accountId = config.account_id || (await getAccountId());
1165
- if (!accountId) {
1166
- throw new Error("No account id found, quitting...");
1167
- }
1168
-
1169
- return accountId;
1170
- }
1171
-
1172
- /**
1173
- * Throw an error if there is no API token available.
1174
- */
1175
- export function requireApiToken(): ApiCredentials {
1176
- const credentials = getAPIToken();
1177
- if (!credentials) {
1178
- throw new Error("No API token found.");
1179
- }
1180
- return credentials;
1181
- }
1182
-
1183
- /**
1184
- * Save the given account details to a cache
1185
- */
1186
- export function saveAccountToCache(account: {
1187
- id: string;
1188
- name: string;
1189
- }): void {
1190
- saveToConfigCache<{ account: { id: string; name: string } }>(
1191
- "wrangler-account.json",
1192
- { account }
1193
- );
1194
- }
1195
-
1196
- /**
1197
- * Fetch the given account details from a cache if available
1198
- */
1199
- export function getAccountFromCache():
1200
- | undefined
1201
- | { id: string; name: string } {
1202
- return getConfigCache<{ account: { id: string; name: string } }>(
1203
- "wrangler-account.json"
1204
- ).account;
1205
- }
1206
-
1207
- /**
1208
- * Get the scopes of the following token, will only return scopes
1209
- * if the token is an OAuth token.
1210
- */
1211
- export function getScopes(): Scope[] | undefined {
1212
- return LocalState.scopes;
1213
- }
1214
-
1215
- /**
1216
- * Make a request to the Cloudflare OAuth endpoint to get a token.
1217
- *
1218
- * Note that the `body` of the POST request is form-urlencoded so
1219
- * can be represented by a URLSearchParams object.
1220
- */
1221
- async function fetchAuthToken(body: URLSearchParams) {
1222
- const headers: Record<string, string> = {
1223
- "Content-Type": "application/x-www-form-urlencoded",
1224
- };
1225
- if (await domainUsesAccess(getAuthDomainFromEnv())) {
1226
- // We are trying to access the staging API so we need an "access token".
1227
- headers["Cookie"] = `CF_Authorization=${await getCloudflareAccessToken()}`;
1228
- }
1229
- return await fetch(getTokenUrlFromEnv(), {
1230
- method: "POST",
1231
- body: body.toString(),
1232
- headers,
1233
- });
1234
- }