wrangler 2.0.12 → 2.0.16

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 (149) hide show
  1. package/README.md +7 -1
  2. package/bin/wrangler.js +111 -57
  3. package/miniflare-dist/index.mjs +9 -2
  4. package/package.json +156 -154
  5. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  6. package/src/__tests__/config-cache.test.ts +30 -24
  7. package/src/__tests__/configuration.test.ts +3935 -3476
  8. package/src/__tests__/dev.test.tsx +1128 -979
  9. package/src/__tests__/guess-worker-format.test.ts +68 -68
  10. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  11. package/src/__tests__/helpers/faye-websocket.d.ts +4 -4
  12. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  13. package/src/__tests__/helpers/mock-bin.ts +20 -20
  14. package/src/__tests__/helpers/mock-cfetch.ts +92 -92
  15. package/src/__tests__/helpers/mock-console.ts +49 -39
  16. package/src/__tests__/helpers/mock-dialogs.ts +94 -71
  17. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  18. package/src/__tests__/helpers/mock-istty.ts +65 -18
  19. package/src/__tests__/helpers/mock-kv.ts +26 -26
  20. package/src/__tests__/helpers/mock-oauth-flow.ts +223 -228
  21. package/src/__tests__/helpers/mock-process.ts +39 -0
  22. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  23. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  24. package/src/__tests__/helpers/run-in-tmp.ts +27 -27
  25. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  26. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  27. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  28. package/src/__tests__/https-options.test.ts +104 -104
  29. package/src/__tests__/index.test.ts +239 -234
  30. package/src/__tests__/init.test.ts +1605 -1250
  31. package/src/__tests__/jest.setup.ts +63 -33
  32. package/src/__tests__/kv.test.ts +1128 -1011
  33. package/src/__tests__/logger.test.ts +100 -74
  34. package/src/__tests__/package-manager.test.ts +303 -303
  35. package/src/__tests__/pages.test.ts +1152 -652
  36. package/src/__tests__/parse.test.ts +252 -252
  37. package/src/__tests__/publish.test.ts +6371 -5622
  38. package/src/__tests__/pubsub.test.ts +367 -0
  39. package/src/__tests__/r2.test.ts +133 -133
  40. package/src/__tests__/route.test.ts +18 -18
  41. package/src/__tests__/secret.test.ts +382 -377
  42. package/src/__tests__/tail.test.ts +530 -530
  43. package/src/__tests__/user.test.ts +123 -111
  44. package/src/__tests__/whoami.test.tsx +198 -117
  45. package/src/__tests__/worker-namespace.test.ts +327 -0
  46. package/src/abort.d.ts +1 -1
  47. package/src/api/dev.ts +49 -0
  48. package/src/api/index.ts +1 -0
  49. package/src/bundle-reporter.tsx +29 -0
  50. package/src/bundle.ts +157 -149
  51. package/src/cfetch/index.ts +80 -80
  52. package/src/cfetch/internal.ts +90 -83
  53. package/src/cli.ts +21 -7
  54. package/src/config/config.ts +204 -195
  55. package/src/config/diagnostics.ts +61 -61
  56. package/src/config/environment.ts +390 -357
  57. package/src/config/index.ts +206 -193
  58. package/src/config/validation-helpers.ts +366 -366
  59. package/src/config/validation.ts +1573 -1376
  60. package/src/config-cache.ts +79 -41
  61. package/src/create-worker-preview.ts +206 -136
  62. package/src/create-worker-upload-form.ts +247 -238
  63. package/src/dev/dev-vars.ts +13 -13
  64. package/src/dev/dev.tsx +329 -307
  65. package/src/dev/local.tsx +304 -275
  66. package/src/dev/remote.tsx +366 -224
  67. package/src/dev/use-esbuild.ts +126 -91
  68. package/src/dev.tsx +538 -0
  69. package/src/dialogs.tsx +97 -97
  70. package/src/durable.ts +87 -87
  71. package/src/entry.ts +234 -228
  72. package/src/environment-variables.ts +23 -23
  73. package/src/errors.ts +6 -6
  74. package/src/generate.ts +33 -0
  75. package/src/git-client.ts +42 -0
  76. package/src/https-options.ts +79 -79
  77. package/src/index.tsx +1775 -2763
  78. package/src/init.ts +549 -0
  79. package/src/inspect.ts +593 -593
  80. package/src/intl-polyfill.d.ts +123 -123
  81. package/src/is-interactive.ts +12 -0
  82. package/src/kv.ts +277 -277
  83. package/src/logger.ts +46 -39
  84. package/src/miniflare-cli/enum-keys.ts +8 -8
  85. package/src/miniflare-cli/index.ts +42 -31
  86. package/src/miniflare-cli/request-context.ts +18 -18
  87. package/src/module-collection.ts +212 -212
  88. package/src/open-in-browser.ts +4 -6
  89. package/src/package-manager.ts +123 -123
  90. package/src/pages/build.tsx +202 -0
  91. package/src/pages/constants.ts +7 -0
  92. package/src/pages/deployments.tsx +101 -0
  93. package/src/pages/dev.tsx +964 -0
  94. package/src/pages/functions/buildPlugin.ts +105 -0
  95. package/src/pages/functions/buildWorker.ts +151 -0
  96. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  97. package/src/pages/functions/filepath-routing.ts +189 -0
  98. package/src/pages/functions/identifiers.ts +78 -0
  99. package/src/pages/functions/routes.ts +151 -0
  100. package/src/pages/index.tsx +84 -0
  101. package/src/pages/projects.tsx +157 -0
  102. package/src/pages/publish.tsx +335 -0
  103. package/src/pages/types.ts +40 -0
  104. package/src/pages/upload.tsx +384 -0
  105. package/src/pages/utils.ts +12 -0
  106. package/src/parse.ts +202 -138
  107. package/src/paths.ts +6 -6
  108. package/src/preview.ts +31 -0
  109. package/src/proxy.ts +400 -402
  110. package/src/publish.ts +667 -621
  111. package/src/pubsub/index.ts +286 -0
  112. package/src/pubsub/pubsub-commands.tsx +577 -0
  113. package/src/r2.ts +19 -19
  114. package/src/selfsigned.d.ts +23 -23
  115. package/src/sites.tsx +271 -225
  116. package/src/tail/filters.ts +108 -108
  117. package/src/tail/index.ts +217 -217
  118. package/src/tail/printing.ts +45 -45
  119. package/src/update-check.ts +11 -11
  120. package/src/user/choose-account.tsx +60 -0
  121. package/src/user/env-vars.ts +46 -0
  122. package/src/user/generate-auth-url.ts +33 -0
  123. package/src/user/generate-random-state.ts +16 -0
  124. package/src/user/index.ts +3 -0
  125. package/src/user/user.tsx +1161 -0
  126. package/src/whoami.tsx +61 -42
  127. package/src/worker-namespace.ts +190 -0
  128. package/src/worker.ts +110 -100
  129. package/src/zones.ts +39 -36
  130. package/templates/checked-fetch.js +17 -0
  131. package/templates/new-worker-scheduled.js +3 -3
  132. package/templates/new-worker-scheduled.ts +15 -15
  133. package/templates/new-worker.js +3 -3
  134. package/templates/new-worker.ts +15 -15
  135. package/templates/no-op-worker.js +10 -0
  136. package/templates/pages-template-plugin.ts +155 -0
  137. package/templates/pages-template-worker.ts +161 -0
  138. package/templates/static-asset-facade.js +31 -31
  139. package/templates/tsconfig.json +95 -95
  140. package/wrangler-dist/cli.js +55383 -54138
  141. package/pages/functions/buildPlugin.ts +0 -105
  142. package/pages/functions/buildWorker.ts +0 -151
  143. package/pages/functions/filepath-routing.ts +0 -189
  144. package/pages/functions/identifiers.ts +0 -78
  145. package/pages/functions/routes.ts +0 -156
  146. package/pages/functions/template-plugin.ts +0 -147
  147. package/pages/functions/template-worker.ts +0 -143
  148. package/src/pages.tsx +0 -2093
  149. package/src/user.tsx +0 -1214
@@ -0,0 +1,1161 @@
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 os from "node:os";
213
+ import path from "node:path";
214
+ import url from "node:url";
215
+ import { TextEncoder } from "node:util";
216
+ import TOML from "@iarna/toml";
217
+ import { HostURL } from "@webcontainer/env";
218
+ import { render } from "ink";
219
+ import Table from "ink-table";
220
+ import React from "react";
221
+ import { fetch } from "undici";
222
+ import {
223
+ getConfigCache,
224
+ purgeConfigCaches,
225
+ saveToConfigCache,
226
+ } from "../config-cache";
227
+ import isInteractive from "../is-interactive";
228
+ import { logger } from "../logger";
229
+ import openInBrowser from "../open-in-browser";
230
+ import { parseTOML, readFileSync } from "../parse";
231
+ import { ChooseAccount, getAccountChoices } from "./choose-account";
232
+ import { getAuthFromEnv } from "./env-vars";
233
+ import { generateAuthUrl } from "./generate-auth-url";
234
+ import { generateRandomState } from "./generate-random-state";
235
+ import type { ApiCredentials } from "./env-vars";
236
+ import type { ParsedUrlQuery } from "node:querystring";
237
+
238
+ /**
239
+ * An implementation of rfc6749#section-4.1 and rfc7636.
240
+ */
241
+
242
+ interface PKCECodes {
243
+ codeChallenge: string;
244
+ codeVerifier: string;
245
+ }
246
+
247
+ /**
248
+ * The module level state of the authentication flow.
249
+ */
250
+ interface State extends AuthTokens {
251
+ authorizationCode?: string;
252
+ codeChallenge?: string;
253
+ codeVerifier?: string;
254
+ hasAuthCodeBeenExchangedForAccessToken?: boolean;
255
+ stateQueryParam?: string;
256
+ scopes?: Scope[];
257
+ }
258
+
259
+ /**
260
+ * The tokens related to authentication.
261
+ */
262
+ interface AuthTokens {
263
+ accessToken?: AccessToken;
264
+ refreshToken?: RefreshToken;
265
+ /** @deprecated - this field was only provided by the deprecated `wrangler1 config` command. */
266
+ apiToken?: string;
267
+ }
268
+
269
+ /**
270
+ * The path to the config file that holds user authentication data,
271
+ * relative to the user's home directory.
272
+ */
273
+ export const USER_AUTH_CONFIG_FILE = ".wrangler/config/default.toml";
274
+
275
+ /**
276
+ * The data that may be read from the `USER_CONFIG_FILE`.
277
+ */
278
+ export interface UserAuthConfig {
279
+ oauth_token?: string;
280
+ refresh_token?: string;
281
+ expiration_time?: string;
282
+ /** @deprecated - this field was only provided by the deprecated `wrangler1 config` command. */
283
+ api_token?: string;
284
+ }
285
+
286
+ interface RefreshToken {
287
+ value: string;
288
+ }
289
+
290
+ interface AccessToken {
291
+ value: string;
292
+ expiry: string;
293
+ }
294
+
295
+ const Scopes = {
296
+ "account:read":
297
+ "See your account info such as account details, analytics, and memberships.",
298
+ "user:read":
299
+ "See your user info such as name, email address, and account memberships.",
300
+ "workers:write":
301
+ "See and change Cloudflare Workers data such as zones, KV storage, namespaces, scripts, and routes.",
302
+ "workers_kv:write":
303
+ "See and change Cloudflare Workers KV Storage data such as keys and namespaces.",
304
+ "workers_routes:write":
305
+ "See and change Cloudflare Workers data such as filters and routes.",
306
+ "workers_scripts:write":
307
+ "See and change Cloudflare Workers scripts, durable objects, subdomains, triggers, and tail data.",
308
+ "workers_tail:read": "See Cloudflare Workers tail and script data.",
309
+ "pages:write":
310
+ "See and change Cloudflare Pages projects, settings and deployments.",
311
+ "zone:read": "Grants read level access to account zone.",
312
+ } as const;
313
+
314
+ /**
315
+ * The possible keys for a Scope.
316
+ *
317
+ * "offline_access" is automatically included.
318
+ */
319
+ type Scope = keyof typeof Scopes;
320
+
321
+ const ScopeKeys = Object.keys(Scopes) as Scope[];
322
+
323
+ export function validateScopeKeys(
324
+ scopes: string[]
325
+ ): scopes is typeof ScopeKeys {
326
+ return scopes.every((scope) => scope in Scopes);
327
+ }
328
+
329
+ const CLIENT_ID = "54d11594-84e4-41aa-b438-e81b8fa78ee7";
330
+ const AUTH_URL = "https://dash.cloudflare.com/oauth2/auth";
331
+ const TOKEN_URL = "https://dash.cloudflare.com/oauth2/token";
332
+ const REVOKE_URL = "https://dash.cloudflare.com/oauth2/revoke";
333
+
334
+ /**
335
+ * To allow OAuth callbacks in environments such as WebContainer we need to
336
+ * create a host URL which only resolves `localhost` to a WebContainer
337
+ * hostname if the process is running in a WebContainer. On local this will
338
+ * be a no-op and it leaves the URL unmodified.
339
+ *
340
+ * @see https://www.npmjs.com/package/@webcontainer/env
341
+ */
342
+ const CALLBACK_URL = HostURL.parse("http://localhost:8976/oauth/callback").href;
343
+
344
+ let LocalState: State = {
345
+ ...getAuthTokens(),
346
+ };
347
+
348
+ /**
349
+ * Compute the current auth tokens.
350
+ */
351
+ function getAuthTokens(config?: UserAuthConfig): AuthTokens | undefined {
352
+ // get refreshToken/accessToken from fs if exists
353
+ try {
354
+ // if the environment variable is available, we don't need to do anything here
355
+ if (getAuthFromEnv()) return;
356
+
357
+ // otherwise try loading from the user auth config file.
358
+ const { oauth_token, refresh_token, expiration_time, api_token } =
359
+ config || readAuthConfigFile();
360
+
361
+ if (oauth_token) {
362
+ return {
363
+ accessToken: {
364
+ value: oauth_token,
365
+ // If there is no `expiration_time` field then set it to an old date, to cause it to expire immediately.
366
+ expiry: expiration_time ?? "2000-01-01:00:00:00+00:00",
367
+ },
368
+ refreshToken: { value: refresh_token ?? "" },
369
+ };
370
+ } else if (api_token) {
371
+ return { apiToken: api_token };
372
+ }
373
+ } catch {
374
+ return undefined;
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Run the initialisation of the auth state, in the case that something changed.
380
+ *
381
+ * This runs automatically whenever `writeAuthConfigFile` is run, so generally
382
+ * you won't need to call it yourself.
383
+ */
384
+ export function reinitialiseAuthTokens(): void;
385
+
386
+ /**
387
+ * Reinitialise auth state from an in-memory config, skipping
388
+ * over the part where we write a file and then read it back into memory
389
+ */
390
+ export function reinitialiseAuthTokens(config: UserAuthConfig): void;
391
+
392
+ export function reinitialiseAuthTokens(config?: UserAuthConfig): void {
393
+ LocalState = {
394
+ ...getAuthTokens(config),
395
+ };
396
+ }
397
+
398
+ export function getAPIToken(): ApiCredentials | undefined {
399
+ if ("apiToken" in LocalState) {
400
+ logger.warn(
401
+ "It looks like you have used Wrangler 1's `config` command to login with an API token.\n" +
402
+ "This is no longer supported in the current version of Wrangler.\n" +
403
+ "If you wish to authenticate via an API token then please set the `CLOUDFLARE_API_TOKEN` environment variable."
404
+ );
405
+ }
406
+
407
+ const localAPIToken = getAuthFromEnv();
408
+ if (localAPIToken) return localAPIToken;
409
+
410
+ const storedAccessToken = LocalState.accessToken?.value;
411
+ if (storedAccessToken) return { apiToken: storedAccessToken };
412
+
413
+ if (!process.stdout.isTTY) {
414
+ throw new Error(
415
+ "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/api/tokens/create/ for instructions on how to create an api token, and assign its value to CLOUDFLARE_API_TOKEN."
416
+ );
417
+ }
418
+ }
419
+
420
+ interface AccessContext {
421
+ token?: AccessToken;
422
+ scopes?: Scope[];
423
+ refreshToken?: RefreshToken;
424
+ }
425
+
426
+ /**
427
+ * A list of OAuth2AuthCodePKCE errors.
428
+ */
429
+ // To "namespace" all errors.
430
+ class ErrorOAuth2 extends Error {
431
+ toString(): string {
432
+ return "ErrorOAuth2";
433
+ }
434
+ }
435
+
436
+ // For really unknown errors.
437
+ class ErrorUnknown extends ErrorOAuth2 {
438
+ toString(): string {
439
+ return "ErrorUnknown";
440
+ }
441
+ }
442
+
443
+ // Some generic, internal errors that can happen.
444
+ class ErrorNoAuthCode extends ErrorOAuth2 {
445
+ toString(): string {
446
+ return "ErrorNoAuthCode";
447
+ }
448
+ }
449
+ class ErrorInvalidReturnedStateParam extends ErrorOAuth2 {
450
+ toString(): string {
451
+ return "ErrorInvalidReturnedStateParam";
452
+ }
453
+ }
454
+ class ErrorInvalidJson extends ErrorOAuth2 {
455
+ toString(): string {
456
+ return "ErrorInvalidJson";
457
+ }
458
+ }
459
+
460
+ // Errors that occur across many endpoints
461
+ class ErrorInvalidScope extends ErrorOAuth2 {
462
+ toString(): string {
463
+ return "ErrorInvalidScope";
464
+ }
465
+ }
466
+ class ErrorInvalidRequest extends ErrorOAuth2 {
467
+ toString(): string {
468
+ return "ErrorInvalidRequest";
469
+ }
470
+ }
471
+ class ErrorInvalidToken extends ErrorOAuth2 {
472
+ toString(): string {
473
+ return "ErrorInvalidToken";
474
+ }
475
+ }
476
+
477
+ /**
478
+ * Possible authorization grant errors given by the redirection from the
479
+ * authorization server.
480
+ */
481
+ class ErrorAuthenticationGrant extends ErrorOAuth2 {
482
+ toString(): string {
483
+ return "ErrorAuthenticationGrant";
484
+ }
485
+ }
486
+ class ErrorUnauthorizedClient extends ErrorAuthenticationGrant {
487
+ toString(): string {
488
+ return "ErrorUnauthorizedClient";
489
+ }
490
+ }
491
+ class ErrorAccessDenied extends ErrorAuthenticationGrant {
492
+ toString(): string {
493
+ return "ErrorAccessDenied";
494
+ }
495
+ }
496
+ class ErrorUnsupportedResponseType extends ErrorAuthenticationGrant {
497
+ toString(): string {
498
+ return "ErrorUnsupportedResponseType";
499
+ }
500
+ }
501
+ class ErrorServerError extends ErrorAuthenticationGrant {
502
+ toString(): string {
503
+ return "ErrorServerError";
504
+ }
505
+ }
506
+ class ErrorTemporarilyUnavailable extends ErrorAuthenticationGrant {
507
+ toString(): string {
508
+ return "ErrorTemporarilyUnavailable";
509
+ }
510
+ }
511
+
512
+ /**
513
+ * A list of possible access token response errors.
514
+ */
515
+ class ErrorAccessTokenResponse extends ErrorOAuth2 {
516
+ toString(): string {
517
+ return "ErrorAccessTokenResponse";
518
+ }
519
+ }
520
+ class ErrorInvalidClient extends ErrorAccessTokenResponse {
521
+ toString(): string {
522
+ return "ErrorInvalidClient";
523
+ }
524
+ }
525
+ class ErrorInvalidGrant extends ErrorAccessTokenResponse {
526
+ toString(): string {
527
+ return "ErrorInvalidGrant";
528
+ }
529
+ }
530
+ class ErrorUnsupportedGrantType extends ErrorAccessTokenResponse {
531
+ toString(): string {
532
+ return "ErrorUnsupportedGrantType";
533
+ }
534
+ }
535
+
536
+ const RawErrorToErrorClassMap: { [_: string]: typeof ErrorOAuth2 } = {
537
+ invalid_request: ErrorInvalidRequest,
538
+ invalid_grant: ErrorInvalidGrant,
539
+ unauthorized_client: ErrorUnauthorizedClient,
540
+ access_denied: ErrorAccessDenied,
541
+ unsupported_response_type: ErrorUnsupportedResponseType,
542
+ invalid_scope: ErrorInvalidScope,
543
+ server_error: ErrorServerError,
544
+ temporarily_unavailable: ErrorTemporarilyUnavailable,
545
+ invalid_client: ErrorInvalidClient,
546
+ unsupported_grant_type: ErrorUnsupportedGrantType,
547
+ invalid_json: ErrorInvalidJson,
548
+ invalid_token: ErrorInvalidToken,
549
+ };
550
+
551
+ /**
552
+ * Translate the raw error strings returned from the server into error classes.
553
+ */
554
+ function toErrorClass(rawError: string): ErrorOAuth2 {
555
+ return new (RawErrorToErrorClassMap[rawError] || ErrorUnknown)();
556
+ }
557
+
558
+ /**
559
+ * The maximum length for a code verifier for the best security we can offer.
560
+ * Please note the NOTE section of RFC 7636 § 4.1 - the length must be >= 43,
561
+ * but <= 128, **after** base64 url encoding. This means 32 code verifier bytes
562
+ * encoded will be 43 bytes, or 96 bytes encoded will be 128 bytes. So 96 bytes
563
+ * is the highest valid value that can be used.
564
+ */
565
+ const RECOMMENDED_CODE_VERIFIER_LENGTH = 96;
566
+
567
+ /**
568
+ * A sensible length for the state's length, for anti-csrf.
569
+ */
570
+ const RECOMMENDED_STATE_LENGTH = 32;
571
+
572
+ /**
573
+ * Character set to generate code verifier defined in rfc7636.
574
+ */
575
+ export const PKCE_CHARSET =
576
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
577
+
578
+ /**
579
+ * OAuth 2.0 client that ONLY supports authorization code flow, with PKCE.
580
+ */
581
+
582
+ /**
583
+ * If there is an error, it will be passed back as a rejected Promise.
584
+ * If there is no code, the user should be redirected via
585
+ * [fetchAuthorizationCode].
586
+ */
587
+ function isReturningFromAuthServer(query: ParsedUrlQuery): boolean {
588
+ if (query.error) {
589
+ if (Array.isArray(query.error)) {
590
+ throw toErrorClass(query.error[0]);
591
+ }
592
+ throw toErrorClass(query.error);
593
+ }
594
+
595
+ const code = query.code;
596
+ if (!code) {
597
+ return false;
598
+ }
599
+
600
+ const state = LocalState;
601
+
602
+ const stateQueryParam = query.state;
603
+ if (stateQueryParam !== state.stateQueryParam) {
604
+ logger.warn(
605
+ "Received query string parameter doesn't match the one sent! Possible malicious activity somewhere."
606
+ );
607
+ throw new ErrorInvalidReturnedStateParam();
608
+ }
609
+ assert(!Array.isArray(code));
610
+ state.authorizationCode = code;
611
+ state.hasAuthCodeBeenExchangedForAccessToken = false;
612
+ return true;
613
+ }
614
+
615
+ export async function getAuthURL(scopes = ScopeKeys): Promise<string> {
616
+ const { codeChallenge, codeVerifier } = await generatePKCECodes();
617
+ const stateQueryParam = generateRandomState(RECOMMENDED_STATE_LENGTH);
618
+
619
+ Object.assign(LocalState, {
620
+ codeChallenge,
621
+ codeVerifier,
622
+ stateQueryParam,
623
+ });
624
+
625
+ return generateAuthUrl({
626
+ authUrl: AUTH_URL,
627
+ clientId: CLIENT_ID,
628
+ callbackUrl: CALLBACK_URL,
629
+ scopes,
630
+ stateQueryParam,
631
+ codeChallenge,
632
+ });
633
+ }
634
+
635
+ type TokenResponse =
636
+ | {
637
+ access_token: string;
638
+ expires_in: number;
639
+ refresh_token: string;
640
+ scope: string;
641
+ }
642
+ | {
643
+ error: string;
644
+ };
645
+
646
+ /**
647
+ * Refresh an access token from the remote service.
648
+ */
649
+ async function exchangeRefreshTokenForAccessToken(): Promise<AccessContext> {
650
+ if (!LocalState.refreshToken) {
651
+ logger.warn("No refresh token is present.");
652
+ }
653
+
654
+ const body =
655
+ `grant_type=refresh_token&` +
656
+ `refresh_token=${LocalState.refreshToken?.value}&` +
657
+ `client_id=${CLIENT_ID}`;
658
+
659
+ const response = await fetch(TOKEN_URL, {
660
+ method: "POST",
661
+ body,
662
+ headers: {
663
+ "Content-Type": "application/x-www-form-urlencoded",
664
+ },
665
+ });
666
+
667
+ if (response.status >= 400) {
668
+ let tokenExchangeResErr = undefined;
669
+
670
+ try {
671
+ tokenExchangeResErr = await response.text();
672
+ tokenExchangeResErr = JSON.parse(tokenExchangeResErr);
673
+ } catch (e) {
674
+ // If it can't parse to JSON ignore the error
675
+ }
676
+
677
+ if (tokenExchangeResErr !== undefined) {
678
+ // We will throw the parsed error if it parsed correctly, otherwise we throw an unknown error.
679
+ throw typeof tokenExchangeResErr === "string"
680
+ ? new Error(tokenExchangeResErr)
681
+ : tokenExchangeResErr;
682
+ } else {
683
+ throw new ErrorUnknown(
684
+ "Failed to parse Error from exchangeRefreshTokenForAccessToken"
685
+ );
686
+ }
687
+ } else {
688
+ try {
689
+ const json = (await response.json()) as TokenResponse;
690
+ if ("error" in json) {
691
+ throw json.error;
692
+ }
693
+
694
+ const { access_token, expires_in, refresh_token, scope } = json;
695
+ let scopes: Scope[] = [];
696
+
697
+ const accessToken: AccessToken = {
698
+ value: access_token,
699
+ expiry: new Date(Date.now() + expires_in * 1000).toISOString(),
700
+ };
701
+ LocalState.accessToken = accessToken;
702
+
703
+ if (refresh_token) {
704
+ LocalState.refreshToken = {
705
+ value: refresh_token,
706
+ };
707
+ }
708
+
709
+ if (scope) {
710
+ // Multiple scopes are passed and delimited by spaces,
711
+ // despite using the singular name "scope".
712
+ scopes = scope.split(" ") as Scope[];
713
+ LocalState.scopes = scopes;
714
+ }
715
+
716
+ const accessContext: AccessContext = {
717
+ token: accessToken,
718
+ scopes,
719
+ refreshToken: LocalState.refreshToken,
720
+ };
721
+ return accessContext;
722
+ } catch (error) {
723
+ if (typeof error === "string") {
724
+ throw toErrorClass(error);
725
+ } else {
726
+ throw error;
727
+ }
728
+ }
729
+ }
730
+ }
731
+
732
+ /**
733
+ * Fetch an access token from the remote service.
734
+ */
735
+ async function exchangeAuthCodeForAccessToken(): Promise<AccessContext> {
736
+ const { authorizationCode, codeVerifier = "" } = LocalState;
737
+
738
+ if (!codeVerifier) {
739
+ logger.warn("No code verifier is being sent.");
740
+ } else if (!authorizationCode) {
741
+ logger.warn("No authorization grant code is being passed.");
742
+ }
743
+
744
+ const body =
745
+ `grant_type=authorization_code&` +
746
+ `code=${encodeURIComponent(authorizationCode || "")}&` +
747
+ `redirect_uri=${encodeURIComponent(CALLBACK_URL)}&` +
748
+ `client_id=${encodeURIComponent(CLIENT_ID)}&` +
749
+ `code_verifier=${codeVerifier}`;
750
+
751
+ const response = await fetch(TOKEN_URL, {
752
+ method: "POST",
753
+ body,
754
+ headers: {
755
+ "Content-Type": "application/x-www-form-urlencoded",
756
+ },
757
+ });
758
+ if (!response.ok) {
759
+ const { error } = (await response.json()) as { error: string };
760
+ // .catch((_) => ({ error: "invalid_json" }));
761
+ if (error === "invalid_grant") {
762
+ logger.log("Expired! Auth code or refresh token needs to be renewed.");
763
+ // alert("Redirecting to auth server to obtain a new auth grant code.");
764
+ // TODO: return refreshAuthCodeOrRefreshToken();
765
+ }
766
+ throw toErrorClass(error);
767
+ }
768
+ const json = (await response.json()) as TokenResponse;
769
+ if ("error" in json) {
770
+ throw new Error(json.error);
771
+ }
772
+ const { access_token, expires_in, refresh_token, scope } = json;
773
+ let scopes: Scope[] = [];
774
+ LocalState.hasAuthCodeBeenExchangedForAccessToken = true;
775
+
776
+ const expiryDate = new Date(Date.now() + expires_in * 1000);
777
+ const accessToken: AccessToken = {
778
+ value: access_token,
779
+ expiry: expiryDate.toISOString(),
780
+ };
781
+ LocalState.accessToken = accessToken;
782
+
783
+ if (refresh_token) {
784
+ LocalState.refreshToken = {
785
+ value: refresh_token,
786
+ };
787
+ }
788
+
789
+ if (scope) {
790
+ // Multiple scopes are passed and delimited by spaces,
791
+ // despite using the singular name "scope".
792
+ scopes = scope.split(" ") as Scope[];
793
+ LocalState.scopes = scopes;
794
+ }
795
+
796
+ const accessContext: AccessContext = {
797
+ token: accessToken,
798
+ scopes,
799
+ refreshToken: LocalState.refreshToken,
800
+ };
801
+ return accessContext;
802
+ }
803
+
804
+ /**
805
+ * Implements *base64url-encode* (RFC 4648 § 5) without padding, which is NOT
806
+ * the same as regular base64 encoding.
807
+ */
808
+ function base64urlEncode(value: string): string {
809
+ let base64 = btoa(value);
810
+ base64 = base64.replace(/\+/g, "-");
811
+ base64 = base64.replace(/\//g, "_");
812
+ base64 = base64.replace(/=/g, "");
813
+ return base64;
814
+ }
815
+
816
+ /**
817
+ * Generates a code_verifier and code_challenge, as specified in rfc7636.
818
+ */
819
+
820
+ async function generatePKCECodes(): Promise<PKCECodes> {
821
+ const output = new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);
822
+ // @ts-expect-error crypto's types aren't there yet
823
+ crypto.getRandomValues(output);
824
+ const codeVerifier = base64urlEncode(
825
+ Array.from(output)
826
+ .map((num: number) => PKCE_CHARSET[num % PKCE_CHARSET.length])
827
+ .join("")
828
+ );
829
+ // @ts-expect-error crypto's types aren't there yet
830
+ const buffer = await crypto.subtle.digest(
831
+ "SHA-256",
832
+ new TextEncoder().encode(codeVerifier)
833
+ );
834
+ const hash = new Uint8Array(buffer);
835
+ let binary = "";
836
+ const hashLength = hash.byteLength;
837
+ for (let i = 0; i < hashLength; i++) {
838
+ binary += String.fromCharCode(hash[i]);
839
+ }
840
+ const codeChallenge = base64urlEncode(binary);
841
+ return { codeChallenge, codeVerifier };
842
+ }
843
+
844
+ /**
845
+ * Writes a a wrangler config file (auth credentials) to disk,
846
+ * and updates the user auth state with the new credentials.
847
+ */
848
+ export function writeAuthConfigFile(config: UserAuthConfig) {
849
+ mkdirSync(path.join(os.homedir(), ".wrangler/config/"), {
850
+ recursive: true,
851
+ });
852
+ writeFileSync(
853
+ path.join(os.homedir(), USER_AUTH_CONFIG_FILE),
854
+ TOML.stringify(config as TOML.JsonMap),
855
+ { encoding: "utf-8" }
856
+ );
857
+
858
+ reinitialiseAuthTokens();
859
+ }
860
+
861
+ export function readAuthConfigFile(): UserAuthConfig {
862
+ const toml = parseTOML(
863
+ readFileSync(path.join(os.homedir(), USER_AUTH_CONFIG_FILE))
864
+ );
865
+ return toml;
866
+ }
867
+
868
+ type LoginProps = {
869
+ scopes?: Scope[];
870
+ };
871
+
872
+ export async function loginOrRefreshIfRequired(): Promise<boolean> {
873
+ // TODO: if there already is a token, then try refreshing
874
+ // TODO: ask permission before opening browser
875
+ if (!getAPIToken()) {
876
+ // Not logged in.
877
+ // If we are not interactive, we cannot ask the user to login
878
+ return isInteractive() && (await login());
879
+ } else if (isAccessTokenExpired()) {
880
+ // We're logged in, but the refresh token seems to have expired,
881
+ // so let's try to refresh it
882
+ const didRefresh = await refreshToken();
883
+ if (didRefresh) {
884
+ // The token was refreshed, so we're done here
885
+ return true;
886
+ } else {
887
+ // If the refresh token isn't valid, then we ask the user to login again
888
+ return isInteractive() && (await login());
889
+ }
890
+ } else {
891
+ return true;
892
+ }
893
+ }
894
+
895
+ export async function login(props?: LoginProps): Promise<boolean> {
896
+ logger.log("Attempting to login via OAuth...");
897
+ const urlToOpen = await getAuthURL(props?.scopes);
898
+ let server: http.Server;
899
+ let loginTimeoutHandle: NodeJS.Timeout;
900
+ const timerPromise = new Promise<boolean>((resolve) => {
901
+ loginTimeoutHandle = setTimeout(() => {
902
+ logger.error(
903
+ "Timed out waiting for authorization code, please try again."
904
+ );
905
+ server.close();
906
+ clearTimeout(loginTimeoutHandle);
907
+ resolve(false);
908
+ }, 60000); // wait for 60 seconds for the user to authorize
909
+ });
910
+
911
+ const loginPromise = new Promise<boolean>((resolve, reject) => {
912
+ server = http.createServer(async (req, res) => {
913
+ function finish(status: boolean, error?: Error) {
914
+ clearTimeout(loginTimeoutHandle);
915
+ server.close((closeErr?: Error) => {
916
+ if (error || closeErr) {
917
+ reject(error || closeErr);
918
+ } else resolve(status);
919
+ });
920
+ }
921
+
922
+ assert(req.url, "This request doesn't have a URL"); // This should never happen
923
+ const { pathname, query } = url.parse(req.url, true);
924
+ switch (pathname) {
925
+ case "/oauth/callback": {
926
+ let hasAuthCode = false;
927
+ try {
928
+ hasAuthCode = isReturningFromAuthServer(query);
929
+ } catch (err: unknown) {
930
+ if (err instanceof ErrorAccessDenied) {
931
+ res.writeHead(307, {
932
+ Location:
933
+ "https://welcome.developers.workers.dev/wrangler-oauth-consent-denied",
934
+ });
935
+ res.end(() => {
936
+ finish(false);
937
+ });
938
+ logger.error(
939
+ "Error: Consent denied. You must grant consent to Wrangler in order to login.\n" +
940
+ "If you don't want to do this consider passing an API token via the `CLOUDFLARE_API_TOKEN` environment variable"
941
+ );
942
+
943
+ return;
944
+ } else {
945
+ finish(false, err as Error);
946
+ return;
947
+ }
948
+ }
949
+ if (!hasAuthCode) {
950
+ // render an error page here
951
+ finish(false, new ErrorNoAuthCode());
952
+ return;
953
+ } else {
954
+ const exchange = await exchangeAuthCodeForAccessToken();
955
+ writeAuthConfigFile({
956
+ oauth_token: exchange.token?.value ?? "",
957
+ expiration_time: exchange.token?.expiry,
958
+ refresh_token: exchange.refreshToken?.value,
959
+ });
960
+ res.writeHead(307, {
961
+ Location:
962
+ "https://welcome.developers.workers.dev/wrangler-oauth-consent-granted",
963
+ });
964
+ res.end(() => {
965
+ finish(true);
966
+ });
967
+ logger.log(`Successfully logged in.`);
968
+
969
+ purgeConfigCaches();
970
+
971
+ return;
972
+ }
973
+ }
974
+ }
975
+ });
976
+
977
+ server.listen(8976);
978
+ });
979
+
980
+ logger.log(`Opening a link in your default browser: ${urlToOpen}`);
981
+ await openInBrowser(urlToOpen);
982
+
983
+ return Promise.race([timerPromise, loginPromise]);
984
+ }
985
+
986
+ /**
987
+ * Checks to see if the access token has expired.
988
+ */
989
+ function isAccessTokenExpired(): boolean {
990
+ const { accessToken } = LocalState;
991
+ return Boolean(accessToken && new Date() >= new Date(accessToken.expiry));
992
+ }
993
+
994
+ async function refreshToken(): Promise<boolean> {
995
+ // refresh
996
+ try {
997
+ const {
998
+ token: { value: oauth_token, expiry: expiration_time } = {
999
+ value: "",
1000
+ expiry: "",
1001
+ },
1002
+ refreshToken: { value: refresh_token } = {},
1003
+ } = await exchangeRefreshTokenForAccessToken();
1004
+ writeAuthConfigFile({ oauth_token, expiration_time, refresh_token });
1005
+ return true;
1006
+ } catch (err) {
1007
+ return false;
1008
+ }
1009
+ }
1010
+
1011
+ export async function logout(): Promise<void> {
1012
+ if (!LocalState.accessToken) {
1013
+ if (!LocalState.refreshToken) {
1014
+ logger.log("Not logged in, exiting...");
1015
+ return;
1016
+ }
1017
+
1018
+ const body =
1019
+ `client_id=${encodeURIComponent(CLIENT_ID)}&` +
1020
+ `token_type_hint=refresh_token&` +
1021
+ `token=${encodeURIComponent(LocalState.refreshToken?.value || "")}`;
1022
+
1023
+ const response = await fetch(REVOKE_URL, {
1024
+ method: "POST",
1025
+ body,
1026
+ headers: {
1027
+ "Content-Type": "application/x-www-form-urlencoded",
1028
+ },
1029
+ });
1030
+ await response.text(); // blank text? would be nice if it was something meaningful
1031
+ logger.log(
1032
+ "💁 Wrangler is configured with an OAuth token. The token has been successfully revoked"
1033
+ );
1034
+ }
1035
+ const body =
1036
+ `client_id=${encodeURIComponent(CLIENT_ID)}&` +
1037
+ `token_type_hint=refresh_token&` +
1038
+ `token=${encodeURIComponent(LocalState.refreshToken?.value || "")}`;
1039
+
1040
+ const response = await fetch(REVOKE_URL, {
1041
+ method: "POST",
1042
+ body,
1043
+ headers: {
1044
+ "Content-Type": "application/x-www-form-urlencoded",
1045
+ },
1046
+ });
1047
+ await response.text(); // blank text? would be nice if it was something meaningful
1048
+ rmSync(path.join(os.homedir(), USER_AUTH_CONFIG_FILE));
1049
+ logger.log(`Successfully logged out.`);
1050
+ }
1051
+
1052
+ export function listScopes(message = "💁 Available scopes:"): void {
1053
+ logger.log(message);
1054
+ const data = ScopeKeys.map((scope: Scope) => ({
1055
+ Scope: scope,
1056
+ Description: Scopes[scope],
1057
+ }));
1058
+ render(<Table data={data} />);
1059
+ // TODO: maybe a good idea to show usage here
1060
+ }
1061
+
1062
+ export async function getAccountId(): Promise<string | undefined> {
1063
+ const apiToken = getAPIToken();
1064
+ if (!apiToken) return;
1065
+
1066
+ // check if we have a cached value
1067
+ const cachedAccount = getAccountFromCache();
1068
+ if (cachedAccount) {
1069
+ return cachedAccount.id;
1070
+ }
1071
+ const accounts = await getAccountChoices();
1072
+ if (accounts.length === 1) {
1073
+ saveAccountToCache({ id: accounts[0].id, name: accounts[0].name });
1074
+ return accounts[0].id;
1075
+ }
1076
+
1077
+ if (isInteractive()) {
1078
+ const account = await new Promise<{ id: string; name: string }>(
1079
+ (resolve, reject) => {
1080
+ const { unmount } = render(
1081
+ <ChooseAccount
1082
+ accounts={accounts}
1083
+ onSelect={async (selected) => {
1084
+ saveAccountToCache(selected);
1085
+ resolve(selected);
1086
+ unmount();
1087
+ }}
1088
+ onError={(err) => {
1089
+ reject(err);
1090
+ unmount();
1091
+ }}
1092
+ />
1093
+ );
1094
+ }
1095
+ );
1096
+ return account.id;
1097
+ }
1098
+
1099
+ throw new Error(
1100
+ "More than one account available but unable to select one in non-interactive mode.\n" +
1101
+ `Please set the appropriate \`account_id\` in your \`wrangler.toml\` file.\n` +
1102
+ `Available accounts are ("<name>" - "<id>"):\n` +
1103
+ accounts
1104
+ .map((account) => ` "${account.name}" - "${account.id}")`)
1105
+ .join("\n")
1106
+ );
1107
+ }
1108
+
1109
+ /**
1110
+ * Ensure that a user is logged in, and a valid account_id is available.
1111
+ */
1112
+ export async function requireAuth(config: {
1113
+ account_id?: string;
1114
+ }): Promise<string> {
1115
+ const loggedIn = await loginOrRefreshIfRequired();
1116
+ if (!loggedIn) {
1117
+ // didn't login, let's just quit
1118
+ throw new Error("Did not login, quitting...");
1119
+ }
1120
+ const accountId = config.account_id || (await getAccountId());
1121
+ if (!accountId) {
1122
+ throw new Error("No account id found, quitting...");
1123
+ }
1124
+
1125
+ return accountId;
1126
+ }
1127
+
1128
+ /**
1129
+ * Throw an error if there is no API token available.
1130
+ */
1131
+ export function requireApiToken(): ApiCredentials {
1132
+ const credentials = getAPIToken();
1133
+ if (!credentials) {
1134
+ throw new Error("No API token found.");
1135
+ }
1136
+ return credentials;
1137
+ }
1138
+
1139
+ /**
1140
+ * Save the given account details to a cache
1141
+ */
1142
+ export function saveAccountToCache(account: {
1143
+ id: string;
1144
+ name: string;
1145
+ }): void {
1146
+ saveToConfigCache<{ account: { id: string; name: string } }>(
1147
+ "wrangler-account.json",
1148
+ { account }
1149
+ );
1150
+ }
1151
+
1152
+ /**
1153
+ * Fetch the given account details from a cache if available
1154
+ */
1155
+ export function getAccountFromCache():
1156
+ | undefined
1157
+ | { id: string; name: string } {
1158
+ return getConfigCache<{ account: { id: string; name: string } }>(
1159
+ "wrangler-account.json"
1160
+ ).account;
1161
+ }