wrangler 0.0.0-e6733a3 → 0.0.0-e6ada079

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.

Potentially problematic release.


This version of wrangler might be problematic. Click here for more details.

Files changed (119) hide show
  1. package/README.md +47 -16
  2. package/bin/wrangler.js +94 -31
  3. package/config-schema.json +3100 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +154 -82
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +170 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-pretty-error.ts +40 -0
  21. package/templates/middleware/middleware-scheduled.ts +15 -0
  22. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  23. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  24. package/templates/modules-watch-stub.js +4 -0
  25. package/templates/new-worker-scheduled.js +17 -0
  26. package/templates/new-worker-scheduled.ts +32 -0
  27. package/templates/new-worker.js +15 -0
  28. package/templates/new-worker.ts +33 -0
  29. package/templates/no-op-worker.js +10 -0
  30. package/templates/pages-dev-pipeline.ts +32 -0
  31. package/templates/pages-dev-util.ts +55 -0
  32. package/templates/pages-shim.ts +9 -0
  33. package/templates/pages-template-plugin.ts +190 -0
  34. package/templates/pages-template-worker.ts +198 -0
  35. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  36. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  37. package/templates/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +22 -0
  39. package/templates/tsconfig.json +8 -0
  40. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +240 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +26391 -0
  45. package/wrangler-dist/cli.js +204293 -116652
  46. package/wrangler-dist/wasm-sync.wasm +0 -0
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/pages/functions/buildWorker.ts +0 -62
  52. package/pages/functions/filepath-routing.test.ts +0 -39
  53. package/pages/functions/filepath-routing.ts +0 -221
  54. package/pages/functions/identifiers.ts +0 -78
  55. package/pages/functions/routes.ts +0 -158
  56. package/pages/functions/template-worker.ts +0 -144
  57. package/src/__tests__/clipboardy-mock.js +0 -4
  58. package/src/__tests__/dev.test.tsx +0 -66
  59. package/src/__tests__/index.test.ts +0 -287
  60. package/src/__tests__/jest.setup.ts +0 -22
  61. package/src/__tests__/kv.test.ts +0 -1098
  62. package/src/__tests__/mock-cfetch.ts +0 -171
  63. package/src/__tests__/mock-dialogs.ts +0 -65
  64. package/src/__tests__/run-in-tmp.ts +0 -19
  65. package/src/__tests__/run-wrangler.ts +0 -32
  66. package/src/api/form_data.ts +0 -131
  67. package/src/api/preview.ts +0 -128
  68. package/src/api/worker.ts +0 -155
  69. package/src/cfetch/index.ts +0 -102
  70. package/src/cfetch/internal.ts +0 -69
  71. package/src/cli.ts +0 -9
  72. package/src/config.ts +0 -487
  73. package/src/dev.tsx +0 -771
  74. package/src/dialogs.tsx +0 -77
  75. package/src/index.tsx +0 -1974
  76. package/src/inspect.ts +0 -524
  77. package/src/kv.tsx +0 -267
  78. package/src/module-collection.ts +0 -64
  79. package/src/pages.tsx +0 -1031
  80. package/src/proxy.ts +0 -294
  81. package/src/publish.ts +0 -358
  82. package/src/sites.tsx +0 -114
  83. package/src/tail.tsx +0 -73
  84. package/src/user.tsx +0 -1025
  85. package/static-asset-facade.js +0 -47
  86. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  87. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  88. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  89. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  90. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  91. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  92. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  93. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  94. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  95. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  96. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  97. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  98. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  99. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  100. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  101. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  102. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  103. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  104. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  105. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  106. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  107. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  108. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  109. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  110. package/vendor/wrangler-mime/LICENSE +0 -21
  111. package/vendor/wrangler-mime/Mime.js +0 -97
  112. package/vendor/wrangler-mime/README.md +0 -187
  113. package/vendor/wrangler-mime/cli.js +0 -46
  114. package/vendor/wrangler-mime/index.js +0 -4
  115. package/vendor/wrangler-mime/lite.js +0 -4
  116. package/vendor/wrangler-mime/package.json +0 -52
  117. package/vendor/wrangler-mime/types/other.js +0 -1
  118. package/vendor/wrangler-mime/types/standard.js +0 -1
  119. package/wrangler-dist/cli.js.map +0 -7
package/src/user.tsx DELETED
@@ -1,1025 +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 React from "react";
209
- import { render, Text } from "ink";
210
- import Table from "ink-table";
211
- import SelectInput from "ink-select-input";
212
- import fetch from "node-fetch";
213
- import { webcrypto as crypto } from "node:crypto";
214
- import { TextEncoder } from "node:util";
215
- import open from "open";
216
- import url from "node:url";
217
- import http from "node:http";
218
- import { readFile, writeFile, rm, mkdir } from "node:fs/promises";
219
- import path from "node:path";
220
- import process from "node:process";
221
- import os from "node:os";
222
- import TOML from "@iarna/toml";
223
- import assert from "node:assert";
224
- import type { ParsedUrlQuery } from "node:querystring";
225
- import { CF_API_BASE_URL } from "./cfetch";
226
- import type { Response } from "node-fetch";
227
-
228
- /**
229
- * An implementation of rfc6749#section-4.1 and rfc7636.
230
- */
231
-
232
- interface PKCECodes {
233
- codeChallenge: string;
234
- codeVerifier: string;
235
- }
236
-
237
- interface State {
238
- accessToken?: AccessToken; // persist
239
- authorizationCode?: string;
240
- codeChallenge?: string;
241
- codeVerifier?: string;
242
- hasAuthCodeBeenExchangedForAccessToken?: boolean;
243
- refreshToken?: RefreshToken; // persist
244
- stateQueryParam?: string;
245
- scopes?: Scope[];
246
- }
247
-
248
- interface RefreshToken {
249
- value: string;
250
- }
251
-
252
- interface AccessToken {
253
- value: string;
254
- expiry: string;
255
- }
256
-
257
- type Scope =
258
- | "account:read"
259
- | "user:read"
260
- | "workers:write"
261
- | "workers_kv:write"
262
- | "workers_routes:write"
263
- | "workers_scripts:write"
264
- | "workers_tail:read"
265
- | "zone:read"
266
- | "offline_access"; // this should be included by default
267
-
268
- const Scopes: Scope[] = [
269
- "account:read",
270
- "user:read",
271
- "workers:write",
272
- "workers_kv:write",
273
- "workers_routes:write",
274
- "workers_scripts:write",
275
- "workers_tail:read",
276
- "zone:read",
277
- ];
278
-
279
- const ScopeDescriptions = [
280
- "See your account info such as account details, analytics, and memberships.",
281
- "See your user info such as name, email address, and account memberships.",
282
- "See and change Cloudflare Workers data such as zones, KV storage, namespaces, scripts, and routes.",
283
- "See and change Cloudflare Workers KV Storage data such as keys and namespaces.",
284
- "See and change Cloudflare Workers data such as filters and routes.",
285
- "See and change Cloudflare Workers scripts, durable objects, subdomains, triggers, and tail data.",
286
- "See Cloudflare Workers tail and script data.",
287
- "Grants read level access to account zone.",
288
- ];
289
-
290
- const CLIENT_ID = "54d11594-84e4-41aa-b438-e81b8fa78ee7";
291
- const AUTH_URL = "https://dash.cloudflare.com/oauth2/auth";
292
- const TOKEN_URL = "https://dash.cloudflare.com/oauth2/token";
293
- const CALLBACK_URL = "http://localhost:8976/oauth/callback";
294
- const REVOKE_URL = "https://dash.cloudflare.com/oauth2/revoke";
295
-
296
- const LocalState: State = {};
297
- let initialised = false;
298
-
299
- // we do this because we have some async stuff
300
- // TODO: this should just happen in the top level
301
- // abd we should fiure out how to do top level await
302
- export async function initialise(): Promise<void> {
303
- // get refreshtoken/accesstoken from fs if exists
304
- try {
305
- // if CF_API_TOKEN available, use that
306
- if (process.env.CF_API_TOKEN) {
307
- LocalState.accessToken = {
308
- value: process.env.CF_API_TOKEN,
309
- expiry: "3021-12-31T23:59:59+00:00",
310
- };
311
- initialised = true;
312
- return;
313
- }
314
-
315
- const toml = TOML.parse(
316
- await readFile(path.join(os.homedir(), ".wrangler/config/default.toml"), {
317
- encoding: "utf-8",
318
- })
319
- );
320
- const { oauth_token, refresh_token, expiration_time } = toml as {
321
- oauth_token: string;
322
- refresh_token: string;
323
- expiration_time: string;
324
- };
325
- if (oauth_token) {
326
- LocalState.accessToken = { value: oauth_token, expiry: expiration_time };
327
- }
328
- if (refresh_token) {
329
- LocalState.refreshToken = { value: refresh_token };
330
- }
331
- } catch (err) {
332
- // no config yet, let's chill
333
- // console.error(err);
334
- }
335
- initialised = true;
336
- }
337
-
338
- // ugh. TODO: see fix from above.
339
- function throwIfNotInitialised() {
340
- if (initialised === false) {
341
- throw new Error(
342
- "did you forget to call initialise() from the user module?"
343
- );
344
- }
345
- }
346
-
347
- export function getAPIToken(): string {
348
- if (process.env.CF_API_TOKEN) {
349
- return process.env.CF_API_TOKEN;
350
- }
351
-
352
- throwIfNotInitialised();
353
- return LocalState.accessToken?.value;
354
- }
355
-
356
- interface AccessContext {
357
- token?: AccessToken;
358
- scopes?: Scope[];
359
- refreshToken?: RefreshToken;
360
- }
361
-
362
- /**
363
- * A list of OAuth2AuthCodePKCE errors.
364
- */
365
- // To "namespace" all errors.
366
- class ErrorOAuth2 extends Error {
367
- toString(): string {
368
- return "ErrorOAuth2";
369
- }
370
- }
371
-
372
- // For really unknown errors.
373
- class ErrorUnknown extends ErrorOAuth2 {
374
- toString(): string {
375
- return "ErrorUnknown";
376
- }
377
- }
378
-
379
- // Some generic, internal errors that can happen.
380
- class ErrorNoAuthCode extends ErrorOAuth2 {
381
- toString(): string {
382
- return "ErrorNoAuthCode";
383
- }
384
- }
385
- class ErrorInvalidReturnedStateParam extends ErrorOAuth2 {
386
- toString(): string {
387
- return "ErrorInvalidReturnedStateParam";
388
- }
389
- }
390
- class ErrorInvalidJson extends ErrorOAuth2 {
391
- toString(): string {
392
- return "ErrorInvalidJson";
393
- }
394
- }
395
-
396
- // Errors that occur across many endpoints
397
- class ErrorInvalidScope extends ErrorOAuth2 {
398
- toString(): string {
399
- return "ErrorInvalidScope";
400
- }
401
- }
402
- class ErrorInvalidRequest extends ErrorOAuth2 {
403
- toString(): string {
404
- return "ErrorInvalidRequest";
405
- }
406
- }
407
- class ErrorInvalidToken extends ErrorOAuth2 {
408
- toString(): string {
409
- return "ErrorInvalidToken";
410
- }
411
- }
412
-
413
- /**
414
- * Possible authorization grant errors given by the redirection from the
415
- * authorization server.
416
- */
417
- class ErrorAuthenticationGrant extends ErrorOAuth2 {
418
- toString(): string {
419
- return "ErrorAuthenticationGrant";
420
- }
421
- }
422
- class ErrorUnauthorizedClient extends ErrorAuthenticationGrant {
423
- toString(): string {
424
- return "ErrorUnauthorizedClient";
425
- }
426
- }
427
- class ErrorAccessDenied extends ErrorAuthenticationGrant {
428
- toString(): string {
429
- return "ErrorAccessDenied";
430
- }
431
- }
432
- class ErrorUnsupportedResponseType extends ErrorAuthenticationGrant {
433
- toString(): string {
434
- return "ErrorUnsupportedResponseType";
435
- }
436
- }
437
- class ErrorServerError extends ErrorAuthenticationGrant {
438
- toString(): string {
439
- return "ErrorServerError";
440
- }
441
- }
442
- class ErrorTemporarilyUnavailable extends ErrorAuthenticationGrant {
443
- toString(): string {
444
- return "ErrorTemporarilyUnavailable";
445
- }
446
- }
447
-
448
- /**
449
- * A list of possible access token response errors.
450
- */
451
- class ErrorAccessTokenResponse extends ErrorOAuth2 {
452
- toString(): string {
453
- return "ErrorAccessTokenResponse";
454
- }
455
- }
456
- class ErrorInvalidClient extends ErrorAccessTokenResponse {
457
- toString(): string {
458
- return "ErrorInvalidClient";
459
- }
460
- }
461
- class ErrorInvalidGrant extends ErrorAccessTokenResponse {
462
- toString(): string {
463
- return "ErrorInvalidGrant";
464
- }
465
- }
466
- class ErrorUnsupportedGrantType extends ErrorAccessTokenResponse {
467
- toString(): string {
468
- return "ErrorUnsupportedGrantType";
469
- }
470
- }
471
-
472
- const RawErrorToErrorClassMap: { [_: string]: typeof ErrorOAuth2 } = {
473
- invalid_request: ErrorInvalidRequest,
474
- invalid_grant: ErrorInvalidGrant,
475
- unauthorized_client: ErrorUnauthorizedClient,
476
- access_denied: ErrorAccessDenied,
477
- unsupported_response_type: ErrorUnsupportedResponseType,
478
- invalid_scope: ErrorInvalidScope,
479
- server_error: ErrorServerError,
480
- temporarily_unavailable: ErrorTemporarilyUnavailable,
481
- invalid_client: ErrorInvalidClient,
482
- unsupported_grant_type: ErrorUnsupportedGrantType,
483
- invalid_json: ErrorInvalidJson,
484
- invalid_token: ErrorInvalidToken,
485
- };
486
-
487
- /**
488
- * Translate the raw error strings returned from the server into error classes.
489
- */
490
- function toErrorClass(rawError: string): ErrorOAuth2 {
491
- return new (RawErrorToErrorClassMap[rawError] || ErrorUnknown)();
492
- }
493
-
494
- /**
495
- * The maximum length for a code verifier for the best security we can offer.
496
- * Please note the NOTE section of RFC 7636 § 4.1 - the length must be >= 43,
497
- * but <= 128, **after** base64 url encoding. This means 32 code verifier bytes
498
- * encoded will be 43 bytes, or 96 bytes encoded will be 128 bytes. So 96 bytes
499
- * is the highest valid value that can be used.
500
- */
501
- const RECOMMENDED_CODE_VERIFIER_LENGTH = 96;
502
-
503
- /**
504
- * A sensible length for the state's length, for anti-csrf.
505
- */
506
- const RECOMMENDED_STATE_LENGTH = 32;
507
-
508
- /**
509
- * Character set to generate code verifier defined in rfc7636.
510
- */
511
- const PKCE_CHARSET =
512
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
513
-
514
- /**
515
- * OAuth 2.0 client that ONLY supports authorization code flow, with PKCE.
516
- */
517
-
518
- /**
519
- * If there is an error, it will be passed back as a rejected Promise.
520
- * If there is no code, the user should be redirected via
521
- * [fetchAuthorizationCode].
522
- */
523
- function isReturningFromAuthServer(query: ParsedUrlQuery): boolean {
524
- if (query.error) {
525
- if (Array.isArray(query.error)) {
526
- throw toErrorClass(query.error[0]);
527
- }
528
- throw toErrorClass(query.error);
529
- }
530
-
531
- const code = query.code;
532
- if (!code) {
533
- return false;
534
- }
535
-
536
- const state = LocalState;
537
-
538
- const stateQueryParam = query.state;
539
- if (stateQueryParam !== state.stateQueryParam) {
540
- console.warn(
541
- "state query string parameter doesn't match the one sent! Possible malicious activity somewhere."
542
- );
543
- throw new ErrorInvalidReturnedStateParam();
544
- }
545
- assert(!Array.isArray(code));
546
- state.authorizationCode = code;
547
- state.hasAuthCodeBeenExchangedForAccessToken = false;
548
- return true;
549
- }
550
-
551
- export async function getAuthURL(scopes?: string[]): Promise<string> {
552
- const { codeChallenge, codeVerifier } = await generatePKCECodes();
553
- const stateQueryParam = generateRandomState(RECOMMENDED_STATE_LENGTH);
554
-
555
- Object.assign(LocalState, {
556
- codeChallenge,
557
- codeVerifier,
558
- stateQueryParam,
559
- });
560
-
561
- // TODO: verify that the scopes passed are legit
562
-
563
- return (
564
- AUTH_URL +
565
- `?response_type=code&` +
566
- `client_id=${encodeURIComponent(CLIENT_ID)}&` +
567
- `redirect_uri=${encodeURIComponent(CALLBACK_URL)}&` +
568
- `scope=${encodeURIComponent(
569
- (scopes || Scopes).concat("offline_access").join(" ")
570
- )}&` +
571
- `state=${stateQueryParam}&` +
572
- `code_challenge=${encodeURIComponent(codeChallenge)}&` +
573
- `code_challenge_method=S256`
574
- );
575
- }
576
-
577
- /**
578
- * Refresh an access token from the remote service.
579
- */
580
- async function exchangeRefreshTokenForAccessToken(): Promise<AccessContext> {
581
- if (!LocalState.refreshToken) {
582
- console.warn("No refresh token is present.");
583
- }
584
-
585
- const body =
586
- `grant_type=refresh_token&` +
587
- `refresh_token=${LocalState.refreshToken?.value}&` +
588
- `client_id=${CLIENT_ID}`;
589
-
590
- const response = await fetch(TOKEN_URL, {
591
- method: "POST",
592
- body,
593
- headers: {
594
- "Content-Type": "application/x-www-form-urlencoded",
595
- },
596
- });
597
- if (response.status >= 400) {
598
- throw await response.json();
599
- } else {
600
- try {
601
- const json = await response.json();
602
- const { access_token, expires_in, refresh_token, scope } = json as {
603
- access_token: string;
604
- expires_in: number;
605
- refresh_token: string;
606
- scope: string;
607
- };
608
- let scopes: Scope[] = [];
609
-
610
- const accessToken: AccessToken = {
611
- value: access_token,
612
- expiry: new Date(Date.now() + expires_in * 1000).toISOString(),
613
- };
614
- LocalState.accessToken = accessToken;
615
-
616
- if (refresh_token) {
617
- LocalState.refreshToken = {
618
- value: refresh_token,
619
- };
620
- }
621
-
622
- if (scope) {
623
- // Multiple scopes are passed and delimited by spaces,
624
- // despite using the singular name "scope".
625
- scopes = scope.split(" ") as Scope[];
626
- LocalState.scopes = scopes;
627
- }
628
-
629
- const accessContext: AccessContext = {
630
- token: accessToken,
631
- scopes,
632
- refreshToken: LocalState.refreshToken,
633
- };
634
- return accessContext;
635
- } catch (err) {
636
- const error = err?.error || "There was a network error.";
637
- switch (error) {
638
- case "invalid_grant":
639
- console.log(
640
- "Expired! Auth code or refresh token needs to be renewed."
641
- );
642
- // alert("Redirecting to auth server to obtain a new auth grant code.");
643
- // TODO: return refreshAuthCodeOrRefreshToken();
644
- break;
645
- default:
646
- break;
647
- }
648
- throw toErrorClass(error);
649
- }
650
- }
651
- }
652
-
653
- /**
654
- * Fetch an access token from the remote service.
655
- */
656
- async function exchangeAuthCodeForAccessToken(): Promise<AccessContext> {
657
- const { authorizationCode, codeVerifier = "" } = LocalState;
658
-
659
- if (!codeVerifier) {
660
- console.warn("No code verifier is being sent.");
661
- } else if (!authorizationCode) {
662
- console.warn("No authorization grant code is being passed.");
663
- }
664
-
665
- const body =
666
- `grant_type=authorization_code&` +
667
- `code=${encodeURIComponent(authorizationCode || "")}&` +
668
- `redirect_uri=${encodeURIComponent(CALLBACK_URL)}&` +
669
- `client_id=${encodeURIComponent(CLIENT_ID)}&` +
670
- `code_verifier=${codeVerifier}`;
671
-
672
- const response = await fetch(TOKEN_URL, {
673
- method: "POST",
674
- body,
675
- headers: {
676
- "Content-Type": "application/x-www-form-urlencoded",
677
- },
678
- });
679
- if (!response.ok) {
680
- const { error } = (await response.json()) as { error: string };
681
- // .catch((_) => ({ error: "invalid_json" }));
682
- if (error === "invalid_grant") {
683
- console.log("Expired! Auth code or refresh token needs to be renewed.");
684
- // alert("Redirecting to auth server to obtain a new auth grant code.");
685
- // TODO: return refreshAuthCodeOrRefreshToken();
686
- }
687
- throw toErrorClass(error);
688
- }
689
- const json = await response.json();
690
- const { access_token, expires_in, refresh_token, scope } = json as {
691
- access_token: string;
692
- expires_in: number;
693
- refresh_token: string;
694
- scope: string;
695
- };
696
- let scopes: Scope[] = [];
697
- LocalState.hasAuthCodeBeenExchangedForAccessToken = true;
698
-
699
- const expiryDate = new Date(Date.now() + expires_in * 1000);
700
- const accessToken: AccessToken = {
701
- value: access_token,
702
- expiry: expiryDate.toISOString(),
703
- };
704
- LocalState.accessToken = accessToken;
705
-
706
- if (refresh_token) {
707
- LocalState.refreshToken = {
708
- value: refresh_token,
709
- };
710
- }
711
-
712
- if (scope) {
713
- // Multiple scopes are passed and delimited by spaces,
714
- // despite using the singular name "scope".
715
- scopes = scope.split(" ") as Scope[];
716
- LocalState.scopes = scopes;
717
- }
718
-
719
- const accessContext: AccessContext = {
720
- token: accessToken,
721
- scopes,
722
- refreshToken: LocalState.refreshToken,
723
- };
724
- return accessContext;
725
- }
726
-
727
- /**
728
- * Implements *base64url-encode* (RFC 4648 § 5) without padding, which is NOT
729
- * the same as regular base64 encoding.
730
- */
731
- function base64urlEncode(value: string): string {
732
- let base64 = btoa(value);
733
- base64 = base64.replace(/\+/g, "-");
734
- base64 = base64.replace(/\//g, "_");
735
- base64 = base64.replace(/=/g, "");
736
- return base64;
737
- }
738
-
739
- /**
740
- * Generates a code_verifier and code_challenge, as specified in rfc7636.
741
- */
742
-
743
- async function generatePKCECodes(): Promise<PKCECodes> {
744
- const output = new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);
745
- // @ts-expect-error crypto's types aren't there yet
746
- crypto.getRandomValues(output);
747
- const codeVerifier = base64urlEncode(
748
- Array.from(output)
749
- .map((num: number) => PKCE_CHARSET[num % PKCE_CHARSET.length])
750
- .join("")
751
- );
752
- // @ts-expect-error crypto's types aren't there yet
753
- const buffer = await crypto.subtle.digest(
754
- "SHA-256",
755
- new TextEncoder().encode(codeVerifier)
756
- );
757
- const hash = new Uint8Array(buffer);
758
- let binary = "";
759
- const hashLength = hash.byteLength;
760
- for (let i = 0; i < hashLength; i++) {
761
- binary += String.fromCharCode(hash[i]);
762
- }
763
- const codeChallenge = base64urlEncode(binary);
764
- return { codeChallenge, codeVerifier };
765
- }
766
-
767
- /**
768
- * Generates random state to be passed for anti-csrf.
769
- */
770
- function generateRandomState(lengthOfState: number): string {
771
- const output = new Uint32Array(lengthOfState);
772
- // @ts-expect-error crypto's types aren't there yet
773
- crypto.getRandomValues(output);
774
- return Array.from(output)
775
- .map((num: number) => PKCE_CHARSET[num % PKCE_CHARSET.length])
776
- .join("");
777
- }
778
-
779
- async function writeToConfigFile(tokenData: AccessContext) {
780
- await mkdir(path.join(os.homedir(), ".wrangler/config/"), {
781
- recursive: true,
782
- });
783
- await writeFile(
784
- path.join(os.homedir(), ".wrangler/config/default.toml"),
785
- `
786
- oauth_token = "${tokenData.token?.value || ""}"
787
- refresh_token = "${tokenData.refreshToken?.value}"
788
- expiration_time = "${tokenData.token?.expiry}"
789
- `,
790
- { encoding: "utf-8" }
791
- );
792
- }
793
-
794
- type LoginProps = {
795
- scopes?: string[];
796
- };
797
-
798
- export async function loginOrRefreshIfRequired(): Promise<boolean> {
799
- // TODO: if there already is a token, then try refreshing
800
- // TODO: ask permission before opening browser
801
- if (!LocalState.accessToken) {
802
- // not logged in.
803
- return await login();
804
- } else if (isAccessTokenExpired()) {
805
- return await refreshToken();
806
- } else {
807
- return true;
808
- }
809
- }
810
-
811
- export async function login(props?: LoginProps): Promise<boolean> {
812
- const urlToOpen = await getAuthURL(props?.scopes);
813
- await open(urlToOpen);
814
- // TODO: log url only if on system where it's unreliable/unavailable
815
- // console.log(`💁 Opened ${urlToOpen}`);
816
- let server;
817
- let loginTimeoutHandle;
818
- const timerPromise = new Promise<boolean>((resolve) => {
819
- loginTimeoutHandle = setTimeout(() => {
820
- console.error("Timed out waiting for authorization code.");
821
- server.close();
822
- clearTimeout(loginTimeoutHandle);
823
- resolve(false);
824
- }, 60000); // wait for 30 seconds for the user to authorize
825
- });
826
-
827
- const loginPromise = new Promise<boolean>((resolve, reject) => {
828
- server = http.createServer(async (req, res) => {
829
- function finish(status: boolean, error?: Error) {
830
- clearTimeout(loginTimeoutHandle);
831
- server.close((closeErr?: Error) => {
832
- if (error || closeErr) {
833
- reject(error || closeErr);
834
- } else resolve(status);
835
- });
836
- }
837
-
838
- assert(req.url, "This request doesn't have a URL"); // This should never happen
839
- const { pathname, query } = url.parse(req.url, true);
840
- switch (pathname) {
841
- case "/oauth/callback": {
842
- let hasAuthCode = false;
843
- try {
844
- hasAuthCode = isReturningFromAuthServer(query);
845
- } catch (err: unknown) {
846
- if (err instanceof ErrorAccessDenied) {
847
- res.writeHead(307, {
848
- Location:
849
- "https://welcome.developers.workers.dev/wrangler-oauth-consent-denied",
850
- });
851
- res.end(() => {
852
- finish(false);
853
- });
854
- console.log(
855
- "Error: Consent denied. You must grant consent to Wrangler in order to login. If you don't want to do this consider passing an API token with CF_API_TOKEN variable"
856
- ); // TODO: implement wrangler config lol
857
-
858
- return;
859
- } else {
860
- finish(false, err as Error);
861
- return;
862
- }
863
- }
864
- if (!hasAuthCode) {
865
- // render an error page here
866
- finish(false, new ErrorNoAuthCode());
867
- return;
868
- } else {
869
- const tokenData = await exchangeAuthCodeForAccessToken();
870
- await writeToConfigFile(tokenData);
871
- res.writeHead(307, {
872
- Location:
873
- "https://welcome.developers.workers.dev/wrangler-oauth-consent-granted",
874
- });
875
- res.end(() => {
876
- finish(true);
877
- });
878
- console.log(
879
- `Successfully configured. You can find your configuration file at: ${os.homedir()}/.wrangler/config/default.toml`
880
- );
881
-
882
- return;
883
- }
884
- }
885
- }
886
- });
887
-
888
- server.listen(8976);
889
- });
890
-
891
- return Promise.race([timerPromise, loginPromise]);
892
- }
893
-
894
- /**
895
- * Checks to see if the access token has expired.
896
- */
897
- export function isAccessTokenExpired(): boolean {
898
- throwIfNotInitialised();
899
- const { accessToken } = LocalState;
900
- return Boolean(accessToken && new Date() >= new Date(accessToken.expiry));
901
- }
902
-
903
- export async function refreshToken(): Promise<boolean> {
904
- throwIfNotInitialised();
905
- // refresh
906
- try {
907
- const refreshed = await exchangeRefreshTokenForAccessToken();
908
- await writeToConfigFile(refreshed);
909
- return true;
910
- } catch (err) {
911
- console.error(err);
912
- return false;
913
- }
914
- }
915
-
916
- export async function logout(): Promise<void> {
917
- throwIfNotInitialised();
918
- if (!LocalState.refreshToken) {
919
- console.log("Not logged in, exiting...");
920
- return;
921
- }
922
- const body =
923
- `client_id=${encodeURIComponent(CLIENT_ID)}&` +
924
- `token_type_hint=refresh_token&` +
925
- `token=${encodeURIComponent(LocalState.refreshToken?.value || "")}`;
926
-
927
- const response = await fetch(REVOKE_URL, {
928
- method: "POST",
929
- body,
930
- headers: {
931
- "Content-Type": "application/x-www-form-urlencoded",
932
- },
933
- });
934
- await response.text(); // blank text? would be nice if it was something meaningful
935
- console.log(
936
- "💁 Wrangler is configured with an OAuth token. The token has been successfully revoked"
937
- );
938
- // delete the file
939
- await rm(path.join(os.homedir(), ".wrangler/config/default.toml"));
940
- console.log(
941
- `Removing ${os.homedir()}/.wrangler/config/default.toml.. success!`
942
- );
943
- }
944
-
945
- export function listScopes(): void {
946
- throwIfNotInitialised();
947
- console.log("💁 Available scopes:");
948
- const data = Scopes.map((scope, index) => ({
949
- Scope: scope,
950
- Description: ScopeDescriptions[index],
951
- }));
952
- render(<Table data={data} />);
953
- // TODO: maybe a good idea to show usage here
954
- }
955
-
956
- export async function getAccountId() {
957
- const apiToken = getAPIToken();
958
- if (!apiToken) return;
959
-
960
- if (process.env.CF_ACCOUNT_ID) {
961
- return process.env.CF_ACCOUNT_ID;
962
- }
963
-
964
- let response: Response;
965
- try {
966
- response = await fetch(`${CF_API_BASE_URL}/memberships`, {
967
- method: "GET",
968
- headers: {
969
- Authorization: "Bearer " + apiToken,
970
- },
971
- });
972
- } catch (err) {
973
- // probably offline
974
- }
975
- if (!response) return;
976
- let accountId: string;
977
- // @ts-expect-error need to type this response
978
- const responseJSON: {
979
- success: boolean;
980
- result: { id: string; account: { id: string; name: string } }[];
981
- } = await response.json();
982
-
983
- if (responseJSON.success === true) {
984
- if (responseJSON.result.length === 1) {
985
- accountId = responseJSON.result[0].account.id;
986
- } else {
987
- accountId = await new Promise((resolve) => {
988
- const accounts = responseJSON.result.map((x) => x.account);
989
- const { unmount } = render(
990
- <ChooseAccount
991
- accounts={accounts}
992
- onSelect={async (selected) => {
993
- resolve(selected.value.id);
994
- unmount();
995
- }}
996
- />
997
- );
998
- });
999
- }
1000
- }
1001
- return accountId;
1002
- }
1003
-
1004
- type ChooseAccountItem = {
1005
- id: string;
1006
- name: string;
1007
- };
1008
- export function ChooseAccount(props: {
1009
- accounts: ChooseAccountItem[];
1010
- onSelect: (item) => void;
1011
- }) {
1012
- return (
1013
- <>
1014
- <Text bold>Select an account from below:</Text>
1015
- <SelectInput
1016
- items={props.accounts.map((item) => ({
1017
- key: item.id,
1018
- label: item.name,
1019
- value: item,
1020
- }))}
1021
- onSelect={props.onSelect}
1022
- />
1023
- </>
1024
- );
1025
- }