@cloudflare/workers-auth 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,2154 @@
1
+ import { __name } from './chunk-PAWJFY3S.mjs';
2
+ import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { getEnvironmentVariableFactory, getCloudflareApiEnvironmentFromEnv, UserError, getGlobalWranglerConfigPath, parseTOML, readFileSync, getCloudflareComplianceRegion } from '@cloudflare/workers-utils';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { fetch } from 'undici';
7
+ import assert2 from 'node:assert';
8
+ import http from 'node:http';
9
+ import url from 'node:url';
10
+ import { webcrypto } from 'node:crypto';
11
+ import { TextEncoder } from 'node:util';
12
+
13
+ // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/error.js
14
+ function getLineColFromPtr(string, ptr) {
15
+ let lines = string.slice(0, ptr).split(/\r\n|\n|\r/g);
16
+ return [lines.length, lines.pop().length + 1];
17
+ }
18
+ __name(getLineColFromPtr, "getLineColFromPtr");
19
+ function makeCodeBlock(string, line, column) {
20
+ let lines = string.split(/\r\n|\n|\r/g);
21
+ let codeblock = "";
22
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
23
+ for (let i = line - 1; i <= line + 1; i++) {
24
+ let l = lines[i - 1];
25
+ if (!l)
26
+ continue;
27
+ codeblock += i.toString().padEnd(numberLen, " ");
28
+ codeblock += ": ";
29
+ codeblock += l;
30
+ codeblock += "\n";
31
+ if (i === line) {
32
+ codeblock += " ".repeat(numberLen + column + 2);
33
+ codeblock += "^\n";
34
+ }
35
+ }
36
+ return codeblock;
37
+ }
38
+ __name(makeCodeBlock, "makeCodeBlock");
39
+ var TomlError = class extends Error {
40
+ static {
41
+ __name(this, "TomlError");
42
+ }
43
+ line;
44
+ column;
45
+ codeblock;
46
+ constructor(message, options) {
47
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
48
+ const codeblock = makeCodeBlock(options.toml, line, column);
49
+ super(`Invalid TOML document: ${message}
50
+
51
+ ${codeblock}`, options);
52
+ this.line = line;
53
+ this.column = column;
54
+ this.codeblock = codeblock;
55
+ }
56
+ };
57
+
58
+ // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/util.js
59
+ function isEscaped(str, ptr) {
60
+ let i = 0;
61
+ while (str[ptr - ++i] === "\\")
62
+ ;
63
+ return --i && i % 2;
64
+ }
65
+ __name(isEscaped, "isEscaped");
66
+ function indexOfNewline(str, start = 0, end = str.length) {
67
+ let idx = str.indexOf("\n", start);
68
+ if (str[idx - 1] === "\r")
69
+ idx--;
70
+ return idx <= end ? idx : -1;
71
+ }
72
+ __name(indexOfNewline, "indexOfNewline");
73
+ function skipComment(str, ptr) {
74
+ for (let i = ptr; i < str.length; i++) {
75
+ let c = str[i];
76
+ if (c === "\n")
77
+ return i;
78
+ if (c === "\r" && str[i + 1] === "\n")
79
+ return i + 1;
80
+ if (c < " " && c !== " " || c === "\x7F") {
81
+ throw new TomlError("control characters are not allowed in comments", {
82
+ toml: str,
83
+ ptr
84
+ });
85
+ }
86
+ }
87
+ return str.length;
88
+ }
89
+ __name(skipComment, "skipComment");
90
+ function skipVoid(str, ptr, banNewLines, banComments) {
91
+ let c;
92
+ while ((c = str[ptr]) === " " || c === " " || !banNewLines && (c === "\n" || c === "\r" && str[ptr + 1] === "\n"))
93
+ ptr++;
94
+ return banComments || c !== "#" ? ptr : skipVoid(str, skipComment(str, ptr), banNewLines);
95
+ }
96
+ __name(skipVoid, "skipVoid");
97
+ function skipUntil(str, ptr, sep, end, banNewLines = false) {
98
+ if (!end) {
99
+ ptr = indexOfNewline(str, ptr);
100
+ return ptr < 0 ? str.length : ptr;
101
+ }
102
+ for (let i = ptr; i < str.length; i++) {
103
+ let c = str[i];
104
+ if (c === "#") {
105
+ i = indexOfNewline(str, i);
106
+ } else if (c === sep) {
107
+ return i + 1;
108
+ } else if (c === end || banNewLines && (c === "\n" || c === "\r" && str[i + 1] === "\n")) {
109
+ return i;
110
+ }
111
+ }
112
+ throw new TomlError("cannot find end of structure", {
113
+ toml: str,
114
+ ptr
115
+ });
116
+ }
117
+ __name(skipUntil, "skipUntil");
118
+ function getStringEnd(str, seek) {
119
+ let first = str[seek];
120
+ let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2] ? str.slice(seek, seek + 3) : first;
121
+ seek += target.length - 1;
122
+ do
123
+ seek = str.indexOf(target, ++seek);
124
+ while (seek > -1 && first !== "'" && isEscaped(str, seek));
125
+ if (seek > -1) {
126
+ seek += target.length;
127
+ if (target.length > 1) {
128
+ if (str[seek] === first)
129
+ seek++;
130
+ if (str[seek] === first)
131
+ seek++;
132
+ }
133
+ }
134
+ return seek;
135
+ }
136
+ __name(getStringEnd, "getStringEnd");
137
+
138
+ // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/date.js
139
+ var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}:\d{2}(?:\.\d+)?)?(Z|[-+]\d{2}:\d{2})?$/i;
140
+ var TomlDate = class _TomlDate extends Date {
141
+ static {
142
+ __name(this, "TomlDate");
143
+ }
144
+ #hasDate = false;
145
+ #hasTime = false;
146
+ #offset = null;
147
+ constructor(date) {
148
+ let hasDate = true;
149
+ let hasTime = true;
150
+ let offset = "Z";
151
+ if (typeof date === "string") {
152
+ let match = date.match(DATE_TIME_RE);
153
+ if (match) {
154
+ if (!match[1]) {
155
+ hasDate = false;
156
+ date = `0000-01-01T${date}`;
157
+ }
158
+ hasTime = !!match[2];
159
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
160
+ if (match[2] && +match[2] > 23) {
161
+ date = "";
162
+ } else {
163
+ offset = match[3] || null;
164
+ date = date.toUpperCase();
165
+ if (!offset && hasTime)
166
+ date += "Z";
167
+ }
168
+ } else {
169
+ date = "";
170
+ }
171
+ }
172
+ super(date);
173
+ if (!isNaN(this.getTime())) {
174
+ this.#hasDate = hasDate;
175
+ this.#hasTime = hasTime;
176
+ this.#offset = offset;
177
+ }
178
+ }
179
+ isDateTime() {
180
+ return this.#hasDate && this.#hasTime;
181
+ }
182
+ isLocal() {
183
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
184
+ }
185
+ isDate() {
186
+ return this.#hasDate && !this.#hasTime;
187
+ }
188
+ isTime() {
189
+ return this.#hasTime && !this.#hasDate;
190
+ }
191
+ isValid() {
192
+ return this.#hasDate || this.#hasTime;
193
+ }
194
+ toISOString() {
195
+ let iso = super.toISOString();
196
+ if (this.isDate())
197
+ return iso.slice(0, 10);
198
+ if (this.isTime())
199
+ return iso.slice(11, 23);
200
+ if (this.#offset === null)
201
+ return iso.slice(0, -1);
202
+ if (this.#offset === "Z")
203
+ return iso;
204
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
205
+ offset = this.#offset[0] === "-" ? offset : -offset;
206
+ let offsetDate = new Date(this.getTime() - offset * 6e4);
207
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
208
+ }
209
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
210
+ let date = new _TomlDate(jsDate);
211
+ date.#offset = offset;
212
+ return date;
213
+ }
214
+ static wrapAsLocalDateTime(jsDate) {
215
+ let date = new _TomlDate(jsDate);
216
+ date.#offset = null;
217
+ return date;
218
+ }
219
+ static wrapAsLocalDate(jsDate) {
220
+ let date = new _TomlDate(jsDate);
221
+ date.#hasTime = false;
222
+ date.#offset = null;
223
+ return date;
224
+ }
225
+ static wrapAsLocalTime(jsDate) {
226
+ let date = new _TomlDate(jsDate);
227
+ date.#hasDate = false;
228
+ date.#offset = null;
229
+ return date;
230
+ }
231
+ };
232
+
233
+ // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/primitive.js
234
+ var INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/;
235
+ var FLOAT_REGEX = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/;
236
+ var LEADING_ZERO = /^[+-]?0[0-9_]/;
237
+ var ESCAPE_REGEX = /^[0-9a-f]{4,8}$/i;
238
+ var ESC_MAP = {
239
+ b: "\b",
240
+ t: " ",
241
+ n: "\n",
242
+ f: "\f",
243
+ r: "\r",
244
+ '"': '"',
245
+ "\\": "\\"
246
+ };
247
+ function parseString(str, ptr = 0, endPtr = str.length) {
248
+ let isLiteral = str[ptr] === "'";
249
+ let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];
250
+ if (isMultiline) {
251
+ endPtr -= 2;
252
+ if (str[ptr += 2] === "\r")
253
+ ptr++;
254
+ if (str[ptr] === "\n")
255
+ ptr++;
256
+ }
257
+ let tmp = 0;
258
+ let isEscape;
259
+ let parsed = "";
260
+ let sliceStart = ptr;
261
+ while (ptr < endPtr - 1) {
262
+ let c = str[ptr++];
263
+ if (c === "\n" || c === "\r" && str[ptr] === "\n") {
264
+ if (!isMultiline) {
265
+ throw new TomlError("newlines are not allowed in strings", {
266
+ toml: str,
267
+ ptr: ptr - 1
268
+ });
269
+ }
270
+ } else if (c < " " && c !== " " || c === "\x7F") {
271
+ throw new TomlError("control characters are not allowed in strings", {
272
+ toml: str,
273
+ ptr: ptr - 1
274
+ });
275
+ }
276
+ if (isEscape) {
277
+ isEscape = false;
278
+ if (c === "u" || c === "U") {
279
+ let code = str.slice(ptr, ptr += c === "u" ? 4 : 8);
280
+ if (!ESCAPE_REGEX.test(code)) {
281
+ throw new TomlError("invalid unicode escape", {
282
+ toml: str,
283
+ ptr: tmp
284
+ });
285
+ }
286
+ try {
287
+ parsed += String.fromCodePoint(parseInt(code, 16));
288
+ } catch {
289
+ throw new TomlError("invalid unicode escape", {
290
+ toml: str,
291
+ ptr: tmp
292
+ });
293
+ }
294
+ } else if (isMultiline && (c === "\n" || c === " " || c === " " || c === "\r")) {
295
+ ptr = skipVoid(str, ptr - 1, true);
296
+ if (str[ptr] !== "\n" && str[ptr] !== "\r") {
297
+ throw new TomlError("invalid escape: only line-ending whitespace may be escaped", {
298
+ toml: str,
299
+ ptr: tmp
300
+ });
301
+ }
302
+ ptr = skipVoid(str, ptr);
303
+ } else if (c in ESC_MAP) {
304
+ parsed += ESC_MAP[c];
305
+ } else {
306
+ throw new TomlError("unrecognized escape sequence", {
307
+ toml: str,
308
+ ptr: tmp
309
+ });
310
+ }
311
+ sliceStart = ptr;
312
+ } else if (!isLiteral && c === "\\") {
313
+ tmp = ptr - 1;
314
+ isEscape = true;
315
+ parsed += str.slice(sliceStart, tmp);
316
+ }
317
+ }
318
+ return parsed + str.slice(sliceStart, endPtr - 1);
319
+ }
320
+ __name(parseString, "parseString");
321
+ function parseValue(value, toml, ptr, integersAsBigInt) {
322
+ if (value === "true")
323
+ return true;
324
+ if (value === "false")
325
+ return false;
326
+ if (value === "-inf")
327
+ return -Infinity;
328
+ if (value === "inf" || value === "+inf")
329
+ return Infinity;
330
+ if (value === "nan" || value === "+nan" || value === "-nan")
331
+ return NaN;
332
+ if (value === "-0")
333
+ return integersAsBigInt ? 0n : 0;
334
+ let isInt = INT_REGEX.test(value);
335
+ if (isInt || FLOAT_REGEX.test(value)) {
336
+ if (LEADING_ZERO.test(value)) {
337
+ throw new TomlError("leading zeroes are not allowed", {
338
+ toml,
339
+ ptr
340
+ });
341
+ }
342
+ value = value.replace(/_/g, "");
343
+ let numeric = +value;
344
+ if (isNaN(numeric)) {
345
+ throw new TomlError("invalid number", {
346
+ toml,
347
+ ptr
348
+ });
349
+ }
350
+ if (isInt) {
351
+ if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {
352
+ throw new TomlError("integer value cannot be represented losslessly", {
353
+ toml,
354
+ ptr
355
+ });
356
+ }
357
+ if (isInt || integersAsBigInt === true)
358
+ numeric = BigInt(value);
359
+ }
360
+ return numeric;
361
+ }
362
+ const date = new TomlDate(value);
363
+ if (!date.isValid()) {
364
+ throw new TomlError("invalid value", {
365
+ toml,
366
+ ptr
367
+ });
368
+ }
369
+ return date;
370
+ }
371
+ __name(parseValue, "parseValue");
372
+
373
+ // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/extract.js
374
+ function sliceAndTrimEndOf(str, startPtr, endPtr, allowNewLines) {
375
+ let value = str.slice(startPtr, endPtr);
376
+ let commentIdx = value.indexOf("#");
377
+ if (commentIdx > -1) {
378
+ skipComment(str, commentIdx);
379
+ value = value.slice(0, commentIdx);
380
+ }
381
+ let trimmed = value.trimEnd();
382
+ if (!allowNewLines) {
383
+ let newlineIdx = value.indexOf("\n", trimmed.length);
384
+ if (newlineIdx > -1) {
385
+ throw new TomlError("newlines are not allowed in inline tables", {
386
+ toml: str,
387
+ ptr: startPtr + newlineIdx
388
+ });
389
+ }
390
+ }
391
+ return [trimmed, commentIdx];
392
+ }
393
+ __name(sliceAndTrimEndOf, "sliceAndTrimEndOf");
394
+ function extractValue(str, ptr, end, depth, integersAsBigInt) {
395
+ if (depth === 0) {
396
+ throw new TomlError("document contains excessively nested structures. aborting.", {
397
+ toml: str,
398
+ ptr
399
+ });
400
+ }
401
+ let c = str[ptr];
402
+ if (c === "[" || c === "{") {
403
+ let [value, endPtr2] = c === "[" ? parseArray(str, ptr, depth, integersAsBigInt) : parseInlineTable(str, ptr, depth, integersAsBigInt);
404
+ let newPtr = end ? skipUntil(str, endPtr2, ",", end) : endPtr2;
405
+ if (endPtr2 - newPtr && end === "}") {
406
+ let nextNewLine = indexOfNewline(str, endPtr2, newPtr);
407
+ if (nextNewLine > -1) {
408
+ throw new TomlError("newlines are not allowed in inline tables", {
409
+ toml: str,
410
+ ptr: nextNewLine
411
+ });
412
+ }
413
+ }
414
+ return [value, newPtr];
415
+ }
416
+ let endPtr;
417
+ if (c === '"' || c === "'") {
418
+ endPtr = getStringEnd(str, ptr);
419
+ let parsed = parseString(str, ptr, endPtr);
420
+ if (end) {
421
+ endPtr = skipVoid(str, endPtr, end !== "]");
422
+ if (str[endPtr] && str[endPtr] !== "," && str[endPtr] !== end && str[endPtr] !== "\n" && str[endPtr] !== "\r") {
423
+ throw new TomlError("unexpected character encountered", {
424
+ toml: str,
425
+ ptr: endPtr
426
+ });
427
+ }
428
+ endPtr += +(str[endPtr] === ",");
429
+ }
430
+ return [parsed, endPtr];
431
+ }
432
+ endPtr = skipUntil(str, ptr, ",", end);
433
+ let slice = sliceAndTrimEndOf(str, ptr, endPtr - +(str[endPtr - 1] === ","), end === "]");
434
+ if (!slice[0]) {
435
+ throw new TomlError("incomplete key-value declaration: no value specified", {
436
+ toml: str,
437
+ ptr
438
+ });
439
+ }
440
+ if (end && slice[1] > -1) {
441
+ endPtr = skipVoid(str, ptr + slice[1]);
442
+ endPtr += +(str[endPtr] === ",");
443
+ }
444
+ return [
445
+ parseValue(slice[0], str, ptr, integersAsBigInt),
446
+ endPtr
447
+ ];
448
+ }
449
+ __name(extractValue, "extractValue");
450
+
451
+ // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/struct.js
452
+ var KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \t]*$/;
453
+ function parseKey(str, ptr, end = "=") {
454
+ let dot = ptr - 1;
455
+ let parsed = [];
456
+ let endPtr = str.indexOf(end, ptr);
457
+ if (endPtr < 0) {
458
+ throw new TomlError("incomplete key-value: cannot find end of key", {
459
+ toml: str,
460
+ ptr
461
+ });
462
+ }
463
+ do {
464
+ let c = str[ptr = ++dot];
465
+ if (c !== " " && c !== " ") {
466
+ if (c === '"' || c === "'") {
467
+ if (c === str[ptr + 1] && c === str[ptr + 2]) {
468
+ throw new TomlError("multiline strings are not allowed in keys", {
469
+ toml: str,
470
+ ptr
471
+ });
472
+ }
473
+ let eos = getStringEnd(str, ptr);
474
+ if (eos < 0) {
475
+ throw new TomlError("unfinished string encountered", {
476
+ toml: str,
477
+ ptr
478
+ });
479
+ }
480
+ dot = str.indexOf(".", eos);
481
+ let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);
482
+ let newLine = indexOfNewline(strEnd);
483
+ if (newLine > -1) {
484
+ throw new TomlError("newlines are not allowed in keys", {
485
+ toml: str,
486
+ ptr: ptr + dot + newLine
487
+ });
488
+ }
489
+ if (strEnd.trimStart()) {
490
+ throw new TomlError("found extra tokens after the string part", {
491
+ toml: str,
492
+ ptr: eos
493
+ });
494
+ }
495
+ if (endPtr < eos) {
496
+ endPtr = str.indexOf(end, eos);
497
+ if (endPtr < 0) {
498
+ throw new TomlError("incomplete key-value: cannot find end of key", {
499
+ toml: str,
500
+ ptr
501
+ });
502
+ }
503
+ }
504
+ parsed.push(parseString(str, ptr, eos));
505
+ } else {
506
+ dot = str.indexOf(".", ptr);
507
+ let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);
508
+ if (!KEY_PART_RE.test(part)) {
509
+ throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys", {
510
+ toml: str,
511
+ ptr
512
+ });
513
+ }
514
+ parsed.push(part.trimEnd());
515
+ }
516
+ }
517
+ } while (dot + 1 && dot < endPtr);
518
+ return [parsed, skipVoid(str, endPtr + 1, true, true)];
519
+ }
520
+ __name(parseKey, "parseKey");
521
+ function parseInlineTable(str, ptr, depth, integersAsBigInt) {
522
+ let res = {};
523
+ let seen = /* @__PURE__ */ new Set();
524
+ let c;
525
+ let comma = 0;
526
+ ptr++;
527
+ while ((c = str[ptr++]) !== "}" && c) {
528
+ let err = { toml: str, ptr: ptr - 1 };
529
+ if (c === "\n") {
530
+ throw new TomlError("newlines are not allowed in inline tables", err);
531
+ } else if (c === "#") {
532
+ throw new TomlError("inline tables cannot contain comments", err);
533
+ } else if (c === ",") {
534
+ throw new TomlError("expected key-value, found comma", err);
535
+ } else if (c !== " " && c !== " ") {
536
+ let k;
537
+ let t = res;
538
+ let hasOwn = false;
539
+ let [key, keyEndPtr] = parseKey(str, ptr - 1);
540
+ for (let i = 0; i < key.length; i++) {
541
+ if (i)
542
+ t = hasOwn ? t[k] : t[k] = {};
543
+ k = key[i];
544
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
545
+ throw new TomlError("trying to redefine an already defined value", {
546
+ toml: str,
547
+ ptr
548
+ });
549
+ }
550
+ if (!hasOwn && k === "__proto__") {
551
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
552
+ }
553
+ }
554
+ if (hasOwn) {
555
+ throw new TomlError("trying to redefine an already defined value", {
556
+ toml: str,
557
+ ptr
558
+ });
559
+ }
560
+ let [value, valueEndPtr] = extractValue(str, keyEndPtr, "}", depth - 1, integersAsBigInt);
561
+ seen.add(value);
562
+ t[k] = value;
563
+ ptr = valueEndPtr;
564
+ comma = str[ptr - 1] === "," ? ptr - 1 : 0;
565
+ }
566
+ }
567
+ if (comma) {
568
+ throw new TomlError("trailing commas are not allowed in inline tables", {
569
+ toml: str,
570
+ ptr: comma
571
+ });
572
+ }
573
+ if (!c) {
574
+ throw new TomlError("unfinished table encountered", {
575
+ toml: str,
576
+ ptr
577
+ });
578
+ }
579
+ return [res, ptr];
580
+ }
581
+ __name(parseInlineTable, "parseInlineTable");
582
+ function parseArray(str, ptr, depth, integersAsBigInt) {
583
+ let res = [];
584
+ let c;
585
+ ptr++;
586
+ while ((c = str[ptr++]) !== "]" && c) {
587
+ if (c === ",") {
588
+ throw new TomlError("expected value, found comma", {
589
+ toml: str,
590
+ ptr: ptr - 1
591
+ });
592
+ } else if (c === "#")
593
+ ptr = skipComment(str, ptr);
594
+ else if (c !== " " && c !== " " && c !== "\n" && c !== "\r") {
595
+ let e = extractValue(str, ptr - 1, "]", depth - 1, integersAsBigInt);
596
+ res.push(e[0]);
597
+ ptr = e[1];
598
+ }
599
+ }
600
+ if (!c) {
601
+ throw new TomlError("unfinished array encountered", {
602
+ toml: str,
603
+ ptr
604
+ });
605
+ }
606
+ return [res, ptr];
607
+ }
608
+ __name(parseArray, "parseArray");
609
+
610
+ // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/parse.js
611
+ function peekTable(key, table, meta, type) {
612
+ let t = table;
613
+ let m = meta;
614
+ let k;
615
+ let hasOwn = false;
616
+ let state;
617
+ for (let i = 0; i < key.length; i++) {
618
+ if (i) {
619
+ t = hasOwn ? t[k] : t[k] = {};
620
+ m = (state = m[k]).c;
621
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
622
+ return null;
623
+ }
624
+ if (state.t === 2) {
625
+ let l = t.length - 1;
626
+ t = t[l];
627
+ m = m[l].c;
628
+ }
629
+ }
630
+ k = key[i];
631
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
632
+ return null;
633
+ }
634
+ if (!hasOwn) {
635
+ if (k === "__proto__") {
636
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
637
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
638
+ }
639
+ m[k] = {
640
+ t: i < key.length - 1 && type === 2 ? 3 : type,
641
+ d: false,
642
+ i: 0,
643
+ c: {}
644
+ };
645
+ }
646
+ }
647
+ state = m[k];
648
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
649
+ return null;
650
+ }
651
+ if (type === 2) {
652
+ if (!state.d) {
653
+ state.d = true;
654
+ t[k] = [];
655
+ }
656
+ t[k].push(t = {});
657
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: {} };
658
+ }
659
+ if (state.d) {
660
+ return null;
661
+ }
662
+ state.d = true;
663
+ if (type === 1) {
664
+ t = hasOwn ? t[k] : t[k] = {};
665
+ } else if (type === 0 && hasOwn) {
666
+ return null;
667
+ }
668
+ return [k, t, state.c];
669
+ }
670
+ __name(peekTable, "peekTable");
671
+ function parse(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
672
+ let res = {};
673
+ let meta = {};
674
+ let tbl = res;
675
+ let m = meta;
676
+ for (let ptr = skipVoid(toml, 0); ptr < toml.length; ) {
677
+ if (toml[ptr] === "[") {
678
+ let isTableArray = toml[++ptr] === "[";
679
+ let k = parseKey(toml, ptr += +isTableArray, "]");
680
+ if (isTableArray) {
681
+ if (toml[k[1] - 1] !== "]") {
682
+ throw new TomlError("expected end of table declaration", {
683
+ toml,
684
+ ptr: k[1] - 1
685
+ });
686
+ }
687
+ k[1]++;
688
+ }
689
+ let p = peekTable(
690
+ k[0],
691
+ res,
692
+ meta,
693
+ isTableArray ? 2 : 1
694
+ /* Type.EXPLICIT */
695
+ );
696
+ if (!p) {
697
+ throw new TomlError("trying to redefine an already defined table or value", {
698
+ toml,
699
+ ptr
700
+ });
701
+ }
702
+ m = p[2];
703
+ tbl = p[1];
704
+ ptr = k[1];
705
+ } else {
706
+ let k = parseKey(toml, ptr);
707
+ let p = peekTable(
708
+ k[0],
709
+ tbl,
710
+ m,
711
+ 0
712
+ /* Type.DOTTED */
713
+ );
714
+ if (!p) {
715
+ throw new TomlError("trying to redefine an already defined table or value", {
716
+ toml,
717
+ ptr
718
+ });
719
+ }
720
+ let v = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);
721
+ p[1][p[0]] = v[0];
722
+ ptr = v[1];
723
+ }
724
+ ptr = skipVoid(toml, ptr, true);
725
+ if (toml[ptr] && toml[ptr] !== "\n" && toml[ptr] !== "\r") {
726
+ throw new TomlError("each key-value declaration must be followed by an end-of-line", {
727
+ toml,
728
+ ptr
729
+ });
730
+ }
731
+ ptr = skipVoid(toml, ptr);
732
+ }
733
+ return res;
734
+ }
735
+ __name(parse, "parse");
736
+
737
+ // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/stringify.js
738
+ var BARE_KEY = /^[a-z0-9-_]+$/i;
739
+ function extendedTypeOf(obj) {
740
+ let type = typeof obj;
741
+ if (type === "object") {
742
+ if (Array.isArray(obj))
743
+ return "array";
744
+ if (obj instanceof Date)
745
+ return "date";
746
+ }
747
+ return type;
748
+ }
749
+ __name(extendedTypeOf, "extendedTypeOf");
750
+ function isArrayOfTables(obj) {
751
+ for (let i = 0; i < obj.length; i++) {
752
+ if (extendedTypeOf(obj[i]) !== "object")
753
+ return false;
754
+ }
755
+ return obj.length != 0;
756
+ }
757
+ __name(isArrayOfTables, "isArrayOfTables");
758
+ function formatString(s) {
759
+ return JSON.stringify(s).replace(/\x7f/g, "\\u007f");
760
+ }
761
+ __name(formatString, "formatString");
762
+ function stringifyValue(val, type, depth, numberAsFloat) {
763
+ if (depth === 0) {
764
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
765
+ }
766
+ if (type === "number") {
767
+ if (isNaN(val))
768
+ return "nan";
769
+ if (val === Infinity)
770
+ return "inf";
771
+ if (val === -Infinity)
772
+ return "-inf";
773
+ if (numberAsFloat && Number.isInteger(val))
774
+ return val.toFixed(1);
775
+ return val.toString();
776
+ }
777
+ if (type === "bigint" || type === "boolean") {
778
+ return val.toString();
779
+ }
780
+ if (type === "string") {
781
+ return formatString(val);
782
+ }
783
+ if (type === "date") {
784
+ if (isNaN(val.getTime())) {
785
+ throw new TypeError("cannot serialize invalid date");
786
+ }
787
+ return val.toISOString();
788
+ }
789
+ if (type === "object") {
790
+ return stringifyInlineTable(val, depth, numberAsFloat);
791
+ }
792
+ if (type === "array") {
793
+ return stringifyArray(val, depth, numberAsFloat);
794
+ }
795
+ }
796
+ __name(stringifyValue, "stringifyValue");
797
+ function stringifyInlineTable(obj, depth, numberAsFloat) {
798
+ let keys = Object.keys(obj);
799
+ if (keys.length === 0)
800
+ return "{}";
801
+ let res = "{ ";
802
+ for (let i = 0; i < keys.length; i++) {
803
+ let k = keys[i];
804
+ if (i)
805
+ res += ", ";
806
+ res += BARE_KEY.test(k) ? k : formatString(k);
807
+ res += " = ";
808
+ res += stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat);
809
+ }
810
+ return res + " }";
811
+ }
812
+ __name(stringifyInlineTable, "stringifyInlineTable");
813
+ function stringifyArray(array, depth, numberAsFloat) {
814
+ if (array.length === 0)
815
+ return "[]";
816
+ let res = "[ ";
817
+ for (let i = 0; i < array.length; i++) {
818
+ if (i)
819
+ res += ", ";
820
+ if (array[i] === null || array[i] === void 0) {
821
+ throw new TypeError("arrays cannot contain null or undefined values");
822
+ }
823
+ res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat);
824
+ }
825
+ return res + " ]";
826
+ }
827
+ __name(stringifyArray, "stringifyArray");
828
+ function stringifyArrayTable(array, key, depth, numberAsFloat) {
829
+ if (depth === 0) {
830
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
831
+ }
832
+ let res = "";
833
+ for (let i = 0; i < array.length; i++) {
834
+ res += `${res && "\n"}[[${key}]]
835
+ `;
836
+ res += stringifyTable(0, array[i], key, depth, numberAsFloat);
837
+ }
838
+ return res;
839
+ }
840
+ __name(stringifyArrayTable, "stringifyArrayTable");
841
+ function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat) {
842
+ if (depth === 0) {
843
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
844
+ }
845
+ let preamble = "";
846
+ let tables = "";
847
+ let keys = Object.keys(obj);
848
+ for (let i = 0; i < keys.length; i++) {
849
+ let k = keys[i];
850
+ if (obj[k] !== null && obj[k] !== void 0) {
851
+ let type = extendedTypeOf(obj[k]);
852
+ if (type === "symbol" || type === "function") {
853
+ throw new TypeError(`cannot serialize values of type '${type}'`);
854
+ }
855
+ let key = BARE_KEY.test(k) ? k : formatString(k);
856
+ if (type === "array" && isArrayOfTables(obj[k])) {
857
+ tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat);
858
+ } else if (type === "object") {
859
+ let tblKey = prefix ? `${prefix}.${key}` : key;
860
+ tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat);
861
+ } else {
862
+ preamble += key;
863
+ preamble += " = ";
864
+ preamble += stringifyValue(obj[k], type, depth, numberAsFloat);
865
+ preamble += "\n";
866
+ }
867
+ }
868
+ }
869
+ if (tableKey && (preamble || !tables))
870
+ preamble = preamble ? `[${tableKey}]
871
+ ${preamble}` : `[${tableKey}]`;
872
+ return preamble && tables ? `${preamble}
873
+ ${tables}` : preamble || tables;
874
+ }
875
+ __name(stringifyTable, "stringifyTable");
876
+ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false } = {}) {
877
+ if (extendedTypeOf(obj) !== "object") {
878
+ throw new TypeError("stringify can only be called with an object");
879
+ }
880
+ let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat);
881
+ if (str[str.length - 1] !== "\n")
882
+ return str + "\n";
883
+ return str;
884
+ }
885
+ __name(stringify, "stringify");
886
+
887
+ // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/index.js
888
+ var dist_default = { parse, stringify, TomlDate, TomlError };
889
+
890
+ // src/auth-config-file.ts
891
+ var USER_AUTH_CONFIG_PATH = "config";
892
+ function getAuthConfigFilePath() {
893
+ const environment = getCloudflareApiEnvironmentFromEnv();
894
+ const filePath = `${USER_AUTH_CONFIG_PATH}/${environment === "production" ? "default.toml" : `${environment}.toml`}`;
895
+ return path.join(getGlobalWranglerConfigPath(), filePath);
896
+ }
897
+ __name(getAuthConfigFilePath, "getAuthConfigFilePath");
898
+ function writeAuthConfigFile(config) {
899
+ const configPath = getAuthConfigFilePath();
900
+ mkdirSync(path.dirname(configPath), {
901
+ recursive: true
902
+ });
903
+ writeFileSync(configPath, dist_default.stringify(config), {
904
+ encoding: "utf-8"
905
+ });
906
+ }
907
+ __name(writeAuthConfigFile, "writeAuthConfigFile");
908
+ function readAuthConfigFile() {
909
+ return parseTOML(readFileSync(getAuthConfigFilePath()));
910
+ }
911
+ __name(readAuthConfigFile, "readAuthConfigFile");
912
+ var getClientIdFromEnv = getEnvironmentVariableFactory({
913
+ variableName: "WRANGLER_CLIENT_ID",
914
+ defaultValue: /* @__PURE__ */ __name(() => getCloudflareApiEnvironmentFromEnv() === "staging" ? "4b2ea6cc-9421-4761-874b-ce550e0e3def" : "54d11594-84e4-41aa-b438-e81b8fa78ee7", "defaultValue")
915
+ });
916
+ var getAuthDomainFromEnv = getEnvironmentVariableFactory({
917
+ variableName: "WRANGLER_AUTH_DOMAIN",
918
+ defaultValue: /* @__PURE__ */ __name(() => getCloudflareApiEnvironmentFromEnv() === "staging" ? "dash.staging.cloudflare.com" : "dash.cloudflare.com", "defaultValue")
919
+ });
920
+ var getAuthUrlFromEnv = getEnvironmentVariableFactory({
921
+ variableName: "WRANGLER_AUTH_URL",
922
+ defaultValue: /* @__PURE__ */ __name(() => `https://${getAuthDomainFromEnv()}/oauth2/auth`, "defaultValue")
923
+ });
924
+ var getTokenUrlFromEnv = getEnvironmentVariableFactory({
925
+ variableName: "WRANGLER_TOKEN_URL",
926
+ defaultValue: /* @__PURE__ */ __name(() => `https://${getAuthDomainFromEnv()}/oauth2/token`, "defaultValue")
927
+ });
928
+ var getRevokeUrlFromEnv = getEnvironmentVariableFactory({
929
+ variableName: "WRANGLER_REVOKE_URL",
930
+ defaultValue: /* @__PURE__ */ __name(() => `https://${getAuthDomainFromEnv()}/oauth2/revoke`, "defaultValue")
931
+ });
932
+ var getAccessClientIdFromEnv = getEnvironmentVariableFactory({
933
+ variableName: "CLOUDFLARE_ACCESS_CLIENT_ID"
934
+ });
935
+ var getAccessClientSecretFromEnv = getEnvironmentVariableFactory({
936
+ variableName: "CLOUDFLARE_ACCESS_CLIENT_SECRET"
937
+ });
938
+ var getCfAuthorizationTokenFromEnv = getEnvironmentVariableFactory({
939
+ variableName: "WRANGLER_CF_AUTHORIZATION_TOKEN"
940
+ });
941
+
942
+ // src/access.ts
943
+ var headersCache = {};
944
+ var usesAccessCache = /* @__PURE__ */ new Map();
945
+ function clearAccessCaches() {
946
+ for (const key of Object.keys(headersCache)) {
947
+ delete headersCache[key];
948
+ }
949
+ usesAccessCache.clear();
950
+ }
951
+ __name(clearAccessCaches, "clearAccessCaches");
952
+ async function domainUsesAccess(domain, logger) {
953
+ logger.debug("Checking if domain has Access enabled:", domain);
954
+ if (usesAccessCache.has(domain)) {
955
+ logger.debug(
956
+ "Using cached Access switch for:",
957
+ domain,
958
+ usesAccessCache.get(domain)
959
+ );
960
+ return usesAccessCache.get(domain) ?? false;
961
+ }
962
+ logger.debug("Access switch not cached for:", domain);
963
+ try {
964
+ const controller = new AbortController();
965
+ const cancel = setTimeout(() => {
966
+ controller.abort();
967
+ }, 1e3);
968
+ const output = await fetch(`https://${domain}`, {
969
+ redirect: "manual",
970
+ signal: controller.signal
971
+ });
972
+ clearTimeout(cancel);
973
+ const usesAccess = !!(output.status === 302 && output.headers.get("location")?.includes("cloudflareaccess.com"));
974
+ logger.debug("Caching access switch for:", domain);
975
+ usesAccessCache.set(domain, usesAccess);
976
+ return usesAccess;
977
+ } catch {
978
+ usesAccessCache.set(domain, false);
979
+ return false;
980
+ }
981
+ }
982
+ __name(domainUsesAccess, "domainUsesAccess");
983
+ async function getAccessHeaders(domain, options) {
984
+ const logger = options.logger;
985
+ const isNonInteractiveOrCI = options.isNonInteractiveOrCI;
986
+ const clientId = getAccessClientIdFromEnv();
987
+ const clientSecret = getAccessClientSecretFromEnv();
988
+ if (clientId && clientSecret) {
989
+ logger.debug("Using Access Service Token headers for domain:", domain);
990
+ const headers = {
991
+ "CF-Access-Client-Id": clientId,
992
+ "CF-Access-Client-Secret": clientSecret
993
+ };
994
+ headersCache[domain] = headers;
995
+ return headers;
996
+ }
997
+ if (clientId !== void 0 || clientSecret !== void 0) {
998
+ logger.warn(
999
+ `Both CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET must be set to use Access Service Token authentication. Only ${clientId !== void 0 ? "CLOUDFLARE_ACCESS_CLIENT_ID" : "CLOUDFLARE_ACCESS_CLIENT_SECRET"} was found.`
1000
+ );
1001
+ }
1002
+ if (!await domainUsesAccess(domain, logger)) {
1003
+ return {};
1004
+ }
1005
+ logger.debug("Getting Access headers for domain:", domain);
1006
+ if (headersCache[domain]) {
1007
+ logger.debug("Using cached Access headers for domain:", domain);
1008
+ return headersCache[domain];
1009
+ }
1010
+ if (isNonInteractiveOrCI()) {
1011
+ throw new UserError(
1012
+ `The domain "${domain}" is behind Cloudflare Access, but no Access Service Token credentials were found and the current environment is non-interactive.
1013
+ Set the CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET environment variables to authenticate with an Access Service Token.
1014
+ See https://developers.cloudflare.com/cloudflare-one/access-controls/service-credentials/service-tokens/`,
1015
+ {
1016
+ telemetryMessage: "user access missing service token non interactive"
1017
+ }
1018
+ );
1019
+ }
1020
+ logger.debug("Spawning cloudflared to get Access token for domain:");
1021
+ const output = spawnSync("cloudflared", ["access", "login", domain]);
1022
+ if (output.error) {
1023
+ throw new UserError(
1024
+ "To use Wrangler with Cloudflare Access, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation",
1025
+ { telemetryMessage: "user access missing cloudflared" }
1026
+ );
1027
+ }
1028
+ const stringOutput = output.stdout.toString();
1029
+ logger.debug("cloudflared output:", stringOutput);
1030
+ const matches = stringOutput.match(/fetched your token:\n\n(.*)/m);
1031
+ if (matches && matches.length >= 2) {
1032
+ const headers = { Cookie: `CF_Authorization=${matches[1]}` };
1033
+ headersCache[domain] = headers;
1034
+ logger.debug("Caching Access headers for domain:", domain);
1035
+ return headers;
1036
+ }
1037
+ throw new Error("Failed to authenticate with Cloudflare Access");
1038
+ }
1039
+ __name(getAccessHeaders, "getAccessHeaders");
1040
+ async function getCloudflareAccessHeaders(options) {
1041
+ const cfAuthToken = getCfAuthorizationTokenFromEnv();
1042
+ if (cfAuthToken !== void 0) {
1043
+ options.logger.debug(
1044
+ "Using WRANGLER_CF_AUTHORIZATION_TOKEN from environment"
1045
+ );
1046
+ return { Cookie: `CF_Authorization=${cfAuthToken}` };
1047
+ }
1048
+ return getAccessHeaders(getAuthDomainFromEnv(), options);
1049
+ }
1050
+ __name(getCloudflareAccessHeaders, "getCloudflareAccessHeaders");
1051
+ var ErrorOAuth2 = class extends UserError {
1052
+ static {
1053
+ __name(this, "ErrorOAuth2");
1054
+ }
1055
+ toString() {
1056
+ return "ErrorOAuth2";
1057
+ }
1058
+ };
1059
+ var ErrorUnknown = class extends UserError {
1060
+ static {
1061
+ __name(this, "ErrorUnknown");
1062
+ }
1063
+ toString() {
1064
+ return "ErrorUnknown";
1065
+ }
1066
+ };
1067
+ var ErrorNoAuthCode = class extends ErrorOAuth2 {
1068
+ static {
1069
+ __name(this, "ErrorNoAuthCode");
1070
+ }
1071
+ toString() {
1072
+ return "ErrorNoAuthCode";
1073
+ }
1074
+ };
1075
+ var ErrorInvalidReturnedStateParam = class extends ErrorOAuth2 {
1076
+ static {
1077
+ __name(this, "ErrorInvalidReturnedStateParam");
1078
+ }
1079
+ toString() {
1080
+ return "ErrorInvalidReturnedStateParam";
1081
+ }
1082
+ };
1083
+ var ErrorInvalidJson = class extends ErrorOAuth2 {
1084
+ static {
1085
+ __name(this, "ErrorInvalidJson");
1086
+ }
1087
+ toString() {
1088
+ return "ErrorInvalidJson";
1089
+ }
1090
+ };
1091
+ var ErrorInvalidScope = class extends ErrorOAuth2 {
1092
+ static {
1093
+ __name(this, "ErrorInvalidScope");
1094
+ }
1095
+ toString() {
1096
+ return "ErrorInvalidScope";
1097
+ }
1098
+ };
1099
+ var ErrorInvalidRequest = class extends ErrorOAuth2 {
1100
+ static {
1101
+ __name(this, "ErrorInvalidRequest");
1102
+ }
1103
+ toString() {
1104
+ return "ErrorInvalidRequest";
1105
+ }
1106
+ };
1107
+ var ErrorInvalidToken = class extends ErrorOAuth2 {
1108
+ static {
1109
+ __name(this, "ErrorInvalidToken");
1110
+ }
1111
+ toString() {
1112
+ return "ErrorInvalidToken";
1113
+ }
1114
+ };
1115
+ var ErrorAuthenticationGrant = class extends ErrorOAuth2 {
1116
+ static {
1117
+ __name(this, "ErrorAuthenticationGrant");
1118
+ }
1119
+ toString() {
1120
+ return "ErrorAuthenticationGrant";
1121
+ }
1122
+ };
1123
+ var ErrorUnauthorizedClient = class extends ErrorAuthenticationGrant {
1124
+ static {
1125
+ __name(this, "ErrorUnauthorizedClient");
1126
+ }
1127
+ toString() {
1128
+ return "ErrorUnauthorizedClient";
1129
+ }
1130
+ };
1131
+ var ErrorAccessDenied = class extends ErrorAuthenticationGrant {
1132
+ static {
1133
+ __name(this, "ErrorAccessDenied");
1134
+ }
1135
+ toString() {
1136
+ return "ErrorAccessDenied";
1137
+ }
1138
+ };
1139
+ var ErrorUnsupportedResponseType = class extends ErrorAuthenticationGrant {
1140
+ static {
1141
+ __name(this, "ErrorUnsupportedResponseType");
1142
+ }
1143
+ toString() {
1144
+ return "ErrorUnsupportedResponseType";
1145
+ }
1146
+ };
1147
+ var ErrorServerError = class extends ErrorAuthenticationGrant {
1148
+ static {
1149
+ __name(this, "ErrorServerError");
1150
+ }
1151
+ toString() {
1152
+ return "ErrorServerError";
1153
+ }
1154
+ };
1155
+ var ErrorTemporarilyUnavailable = class extends ErrorAuthenticationGrant {
1156
+ static {
1157
+ __name(this, "ErrorTemporarilyUnavailable");
1158
+ }
1159
+ toString() {
1160
+ return "ErrorTemporarilyUnavailable";
1161
+ }
1162
+ };
1163
+ var ErrorAccessTokenResponse = class extends ErrorOAuth2 {
1164
+ static {
1165
+ __name(this, "ErrorAccessTokenResponse");
1166
+ }
1167
+ toString() {
1168
+ return "ErrorAccessTokenResponse";
1169
+ }
1170
+ };
1171
+ var ErrorInvalidClient = class extends ErrorAccessTokenResponse {
1172
+ static {
1173
+ __name(this, "ErrorInvalidClient");
1174
+ }
1175
+ toString() {
1176
+ return "ErrorInvalidClient";
1177
+ }
1178
+ };
1179
+ var ErrorInvalidGrant = class extends ErrorAccessTokenResponse {
1180
+ static {
1181
+ __name(this, "ErrorInvalidGrant");
1182
+ }
1183
+ toString() {
1184
+ return "ErrorInvalidGrant";
1185
+ }
1186
+ };
1187
+ var ErrorUnsupportedGrantType = class extends ErrorAccessTokenResponse {
1188
+ static {
1189
+ __name(this, "ErrorUnsupportedGrantType");
1190
+ }
1191
+ toString() {
1192
+ return "ErrorUnsupportedGrantType";
1193
+ }
1194
+ };
1195
+ function toErrorClass(rawError) {
1196
+ switch (rawError) {
1197
+ case "invalid_request":
1198
+ return new ErrorInvalidRequest(rawError, {
1199
+ telemetryMessage: "user oauth invalid request"
1200
+ });
1201
+ case "invalid_grant":
1202
+ return new ErrorInvalidGrant(rawError, {
1203
+ telemetryMessage: "user oauth invalid grant"
1204
+ });
1205
+ case "unauthorized_client":
1206
+ return new ErrorUnauthorizedClient(rawError, {
1207
+ telemetryMessage: "user oauth unauthorized client"
1208
+ });
1209
+ case "access_denied":
1210
+ return new ErrorAccessDenied(rawError, {
1211
+ telemetryMessage: "user oauth access denied"
1212
+ });
1213
+ case "unsupported_response_type":
1214
+ return new ErrorUnsupportedResponseType(rawError, {
1215
+ telemetryMessage: "user oauth unsupported response type"
1216
+ });
1217
+ case "invalid_scope":
1218
+ return new ErrorInvalidScope(rawError, {
1219
+ telemetryMessage: "user oauth invalid scope"
1220
+ });
1221
+ case "server_error":
1222
+ return new ErrorServerError(rawError, {
1223
+ telemetryMessage: "user oauth server error"
1224
+ });
1225
+ case "temporarily_unavailable":
1226
+ return new ErrorTemporarilyUnavailable(rawError, {
1227
+ telemetryMessage: "user oauth temporarily unavailable"
1228
+ });
1229
+ case "invalid_client":
1230
+ return new ErrorInvalidClient(rawError, {
1231
+ telemetryMessage: "user oauth invalid client"
1232
+ });
1233
+ case "unsupported_grant_type":
1234
+ return new ErrorUnsupportedGrantType(rawError, {
1235
+ telemetryMessage: "user oauth unsupported grant type"
1236
+ });
1237
+ case "invalid_json":
1238
+ return new ErrorInvalidJson(rawError, {
1239
+ telemetryMessage: "user oauth invalid json"
1240
+ });
1241
+ case "invalid_token":
1242
+ return new ErrorInvalidToken(rawError, {
1243
+ telemetryMessage: "user oauth invalid token"
1244
+ });
1245
+ default:
1246
+ return new ErrorUnknown(rawError, {
1247
+ telemetryMessage: "user oauth unknown error"
1248
+ });
1249
+ }
1250
+ }
1251
+ __name(toErrorClass, "toErrorClass");
1252
+
1253
+ // ../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/esm/index.js
1254
+ function dedent(templ) {
1255
+ var values = [];
1256
+ for (var _i = 1; _i < arguments.length; _i++) {
1257
+ values[_i - 1] = arguments[_i];
1258
+ }
1259
+ var strings = Array.from(typeof templ === "string" ? [templ] : templ);
1260
+ strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
1261
+ var indentLengths = strings.reduce(function(arr, str) {
1262
+ var matches = str.match(/\n([\t ]+|(?!\s).)/g);
1263
+ if (matches) {
1264
+ return arr.concat(matches.map(function(match) {
1265
+ var _a, _b;
1266
+ return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
1267
+ }));
1268
+ }
1269
+ return arr;
1270
+ }, []);
1271
+ if (indentLengths.length) {
1272
+ var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
1273
+ strings = strings.map(function(str) {
1274
+ return str.replace(pattern_1, "\n");
1275
+ });
1276
+ }
1277
+ strings[0] = strings[0].replace(/^\r?\n/, "");
1278
+ var string = strings[0];
1279
+ values.forEach(function(value, i) {
1280
+ var endentations = string.match(/(?:^|\n)( *)$/);
1281
+ var endentation = endentations ? endentations[1] : "";
1282
+ var indentedValue = value;
1283
+ if (typeof value === "string" && value.includes("\n")) {
1284
+ indentedValue = String(value).split("\n").map(function(str, i2) {
1285
+ return i2 === 0 ? str : "" + endentation + str;
1286
+ }).join("\n");
1287
+ }
1288
+ string += indentedValue + strings[i + 1];
1289
+ });
1290
+ return string;
1291
+ }
1292
+ __name(dedent, "dedent");
1293
+ var esm_default = dedent;
1294
+
1295
+ // src/generate-auth-url.ts
1296
+ var OAUTH_CALLBACK_URL = "http://localhost:8976/oauth/callback";
1297
+ var generateAuthUrl = /* @__PURE__ */ __name(({
1298
+ authUrl,
1299
+ clientId,
1300
+ scopes,
1301
+ stateQueryParam,
1302
+ codeChallenge
1303
+ }) => {
1304
+ return authUrl + `?response_type=code&client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(OAUTH_CALLBACK_URL)}&scope=${encodeURIComponent([...scopes, "offline_access"].join(" "))}&state=${stateQueryParam}&code_challenge=${encodeURIComponent(codeChallenge)}&code_challenge_method=S256`;
1305
+ }, "generateAuthUrl");
1306
+ var RECOMMENDED_CODE_VERIFIER_LENGTH = 96;
1307
+ var RECOMMENDED_STATE_LENGTH = 32;
1308
+ var PKCE_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
1309
+ function base64urlEncode(value) {
1310
+ let base64 = btoa(value);
1311
+ base64 = base64.replace(/\+/g, "-");
1312
+ base64 = base64.replace(/\//g, "_");
1313
+ base64 = base64.replace(/=/g, "");
1314
+ return base64;
1315
+ }
1316
+ __name(base64urlEncode, "base64urlEncode");
1317
+ async function generatePKCECodes() {
1318
+ const output = new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);
1319
+ webcrypto.getRandomValues(output);
1320
+ const codeVerifier = base64urlEncode(
1321
+ Array.from(output).map((num) => PKCE_CHARSET[num % PKCE_CHARSET.length]).join("")
1322
+ );
1323
+ const buffer = await webcrypto.subtle.digest(
1324
+ "SHA-256",
1325
+ new TextEncoder().encode(codeVerifier)
1326
+ );
1327
+ const hash = new Uint8Array(buffer);
1328
+ let binary = "";
1329
+ const hashLength = hash.byteLength;
1330
+ for (let i = 0; i < hashLength; i++) {
1331
+ binary += String.fromCharCode(hash[i]);
1332
+ }
1333
+ const codeChallenge = base64urlEncode(binary);
1334
+ return { codeChallenge, codeVerifier };
1335
+ }
1336
+ __name(generatePKCECodes, "generatePKCECodes");
1337
+
1338
+ // src/state.ts
1339
+ var hasWarnedAboutDeprecatedV1ApiToken = false;
1340
+ function readStoredAuthState(options) {
1341
+ const { configOverride, warningLogger } = options ?? {};
1342
+ let parsed;
1343
+ try {
1344
+ parsed = configOverride ?? readAuthConfigFile();
1345
+ } catch {
1346
+ return {};
1347
+ }
1348
+ const { oauth_token, refresh_token, expiration_time, scopes, api_token } = parsed;
1349
+ if (oauth_token) {
1350
+ return {
1351
+ accessToken: {
1352
+ value: oauth_token,
1353
+ // If there is no `expiration_time` field then set it to an old date, to cause it to expire immediately.
1354
+ expiry: expiration_time ?? "2000-01-01:00:00:00+00:00"
1355
+ },
1356
+ refreshToken: { value: refresh_token ?? "" },
1357
+ scopes
1358
+ };
1359
+ }
1360
+ if (api_token) {
1361
+ if (!hasWarnedAboutDeprecatedV1ApiToken && warningLogger) {
1362
+ hasWarnedAboutDeprecatedV1ApiToken = true;
1363
+ warningLogger.warn(
1364
+ `It looks like you have used Wrangler v1's \`config\` command to login with an API token
1365
+ from ${configOverride === void 0 ? getAuthConfigFilePath() : "in-memory config"}.
1366
+ This is no longer supported in the current version of Wrangler.
1367
+ If you wish to authenticate via an API token then please set the \`CLOUDFLARE_API_TOKEN\` environment variable.`
1368
+ );
1369
+ }
1370
+ return { deprecatedApiToken: api_token };
1371
+ }
1372
+ return {};
1373
+ }
1374
+ __name(readStoredAuthState, "readStoredAuthState");
1375
+
1376
+ // src/token-exchange.ts
1377
+ function isReturningFromAuthServer(query, state, logger) {
1378
+ if (query.error) {
1379
+ if (Array.isArray(query.error)) {
1380
+ throw toErrorClass(query.error[0]);
1381
+ }
1382
+ throw toErrorClass(query.error);
1383
+ }
1384
+ const code = query.code;
1385
+ if (!code) {
1386
+ return false;
1387
+ }
1388
+ const stateQueryParam = query.state;
1389
+ if (stateQueryParam !== state.stateQueryParam) {
1390
+ logger.warn(
1391
+ "Received query string parameter doesn't match the one sent! Possible malicious activity somewhere."
1392
+ );
1393
+ throw new ErrorInvalidReturnedStateParam("", {
1394
+ telemetryMessage: "user oauth invalid returned state"
1395
+ });
1396
+ }
1397
+ assert2(!Array.isArray(code));
1398
+ state.authorizationCode = code;
1399
+ state.hasAuthCodeBeenExchangedForAccessToken = false;
1400
+ return true;
1401
+ }
1402
+ __name(isReturningFromAuthServer, "isReturningFromAuthServer");
1403
+ async function getAuthURL(scopes, clientId, state, generators) {
1404
+ const { codeChallenge, codeVerifier } = await generatePKCECodes();
1405
+ const stateQueryParam = generators.generateRandomState(
1406
+ RECOMMENDED_STATE_LENGTH
1407
+ );
1408
+ Object.assign(state, {
1409
+ codeChallenge,
1410
+ codeVerifier,
1411
+ stateQueryParam
1412
+ });
1413
+ return generators.generateAuthUrl({
1414
+ authUrl: getAuthUrlFromEnv(),
1415
+ clientId,
1416
+ scopes,
1417
+ stateQueryParam,
1418
+ codeChallenge
1419
+ });
1420
+ }
1421
+ __name(getAuthURL, "getAuthURL");
1422
+ async function exchangeRefreshTokenForAccessToken(logger, isNonInteractiveOrCI) {
1423
+ const storedRefreshToken = readStoredAuthState({
1424
+ warningLogger: logger
1425
+ }).refreshToken;
1426
+ if (!storedRefreshToken) {
1427
+ logger.warn("No refresh token is present.");
1428
+ }
1429
+ const params = new URLSearchParams({
1430
+ grant_type: "refresh_token",
1431
+ refresh_token: storedRefreshToken?.value ?? "",
1432
+ client_id: getClientIdFromEnv()
1433
+ });
1434
+ const response = await fetchAuthToken(params, logger, isNonInteractiveOrCI);
1435
+ if (response.status >= 400) {
1436
+ let tokenExchangeResErr = void 0;
1437
+ try {
1438
+ tokenExchangeResErr = await getJSONFromResponse(response, logger);
1439
+ } catch (e) {
1440
+ logger.error(e);
1441
+ }
1442
+ if (tokenExchangeResErr !== void 0) {
1443
+ throw typeof tokenExchangeResErr === "string" ? new Error(tokenExchangeResErr) : tokenExchangeResErr;
1444
+ } else {
1445
+ throw new ErrorUnknown(
1446
+ "Failed to parse Error from exchangeRefreshTokenForAccessToken",
1447
+ { telemetryMessage: "user oauth refresh token exchange parse error" }
1448
+ );
1449
+ }
1450
+ } else {
1451
+ try {
1452
+ const json = await getJSONFromResponse(
1453
+ response,
1454
+ logger
1455
+ );
1456
+ if ("error" in json) {
1457
+ throw json.error;
1458
+ }
1459
+ const { access_token, expires_in, refresh_token, scope } = json;
1460
+ const accessToken = {
1461
+ value: access_token,
1462
+ expiry: new Date(Date.now() + expires_in * 1e3).toISOString()
1463
+ };
1464
+ const scopes = scope ? scope.split(" ") : [];
1465
+ const accessContext = {
1466
+ token: accessToken,
1467
+ scopes,
1468
+ refreshToken: refresh_token ? { value: refresh_token } : storedRefreshToken
1469
+ };
1470
+ return accessContext;
1471
+ } catch (error) {
1472
+ if (typeof error === "string") {
1473
+ throw toErrorClass(error);
1474
+ } else {
1475
+ throw error;
1476
+ }
1477
+ }
1478
+ }
1479
+ }
1480
+ __name(exchangeRefreshTokenForAccessToken, "exchangeRefreshTokenForAccessToken");
1481
+ async function exchangeAuthCodeForAccessToken(state, logger, isNonInteractiveOrCI) {
1482
+ const { authorizationCode, codeVerifier = "" } = state;
1483
+ if (!codeVerifier) {
1484
+ logger.warn("No code verifier is being sent.");
1485
+ } else if (!authorizationCode) {
1486
+ logger.warn("No authorization grant code is being passed.");
1487
+ }
1488
+ const params = new URLSearchParams({
1489
+ grant_type: `authorization_code`,
1490
+ code: authorizationCode ?? "",
1491
+ redirect_uri: OAUTH_CALLBACK_URL,
1492
+ client_id: getClientIdFromEnv(),
1493
+ code_verifier: codeVerifier
1494
+ });
1495
+ const response = await fetchAuthToken(params, logger, isNonInteractiveOrCI);
1496
+ if (!response.ok) {
1497
+ const { error } = await getJSONFromResponse(response, logger);
1498
+ if (error === "invalid_grant") {
1499
+ logger.log("Expired! Auth code or refresh token needs to be renewed.");
1500
+ }
1501
+ throw toErrorClass(error);
1502
+ }
1503
+ const json = await getJSONFromResponse(response, logger);
1504
+ if ("error" in json) {
1505
+ throw new Error(json.error);
1506
+ }
1507
+ const { access_token, expires_in, refresh_token, scope } = json;
1508
+ state.hasAuthCodeBeenExchangedForAccessToken = true;
1509
+ const expiryDate = new Date(Date.now() + expires_in * 1e3);
1510
+ const accessToken = {
1511
+ value: access_token,
1512
+ expiry: expiryDate.toISOString()
1513
+ };
1514
+ const scopes = scope ? scope.split(" ") : [];
1515
+ const accessContext = {
1516
+ token: accessToken,
1517
+ scopes,
1518
+ refreshToken: refresh_token ? { value: refresh_token } : void 0
1519
+ };
1520
+ return accessContext;
1521
+ }
1522
+ __name(exchangeAuthCodeForAccessToken, "exchangeAuthCodeForAccessToken");
1523
+ async function fetchAuthToken(body, logger, isNonInteractiveOrCI) {
1524
+ const headers = {
1525
+ "Content-Type": "application/x-www-form-urlencoded"
1526
+ };
1527
+ logger.debug(
1528
+ "fetching auth token",
1529
+ `grant_type=${body.get("grant_type") ?? "<unknown>"}`
1530
+ );
1531
+ if (await domainUsesAccess(getAuthDomainFromEnv(), logger)) {
1532
+ logger.debug(
1533
+ "Using Cloudflare Access to get an access token for the auth request"
1534
+ );
1535
+ const accessHeaders = await getCloudflareAccessHeaders({
1536
+ logger,
1537
+ isNonInteractiveOrCI
1538
+ });
1539
+ Object.assign(headers, accessHeaders);
1540
+ }
1541
+ logger.debug("Fetching auth token from", getTokenUrlFromEnv());
1542
+ try {
1543
+ const response = await fetch(getTokenUrlFromEnv(), {
1544
+ method: "POST",
1545
+ body: body.toString(),
1546
+ headers
1547
+ });
1548
+ if (!response.ok) {
1549
+ logger.error(
1550
+ "Failed to fetch auth token:",
1551
+ response.status,
1552
+ response.statusText
1553
+ );
1554
+ }
1555
+ return response;
1556
+ } catch (e) {
1557
+ logger.error("Failed to fetch auth token:", e);
1558
+ throw e;
1559
+ }
1560
+ }
1561
+ __name(fetchAuthToken, "fetchAuthToken");
1562
+ async function getJSONFromResponse(response, logger) {
1563
+ const text = await response.text();
1564
+ try {
1565
+ return JSON.parse(text);
1566
+ } catch (e) {
1567
+ if (text.match(/<!DOCTYPE html>/)) {
1568
+ logger.error(
1569
+ "The body of the response was HTML rather than JSON. Check the debug logs to see the full body of the response."
1570
+ );
1571
+ if (text.match(/challenge-platform/)) {
1572
+ logger.error(
1573
+ `It looks like you might have hit a bot challenge page. This may be transient but if not, please contact Cloudflare to find out what can be done. When you contact Cloudflare, please provide your Ray ID: ${response.headers.get("cf-ray")}`
1574
+ );
1575
+ }
1576
+ }
1577
+ logger.debug("Full body of response\n\n", text);
1578
+ throw new Error(
1579
+ `Invalid JSON in response: status: ${response.status} ${response.statusText}`,
1580
+ { cause: e }
1581
+ );
1582
+ }
1583
+ }
1584
+ __name(getJSONFromResponse, "getJSONFromResponse");
1585
+
1586
+ // src/callback-server.ts
1587
+ async function getOauthToken(options, state, ctx, generators) {
1588
+ const urlToOpen = await getAuthURL(
1589
+ options.scopes,
1590
+ options.clientId,
1591
+ state,
1592
+ generators
1593
+ );
1594
+ let server;
1595
+ let loginTimeoutHandle;
1596
+ const timerPromise = new Promise((_, reject) => {
1597
+ loginTimeoutHandle = setTimeout(() => {
1598
+ server.close();
1599
+ clearTimeout(loginTimeoutHandle);
1600
+ reject(
1601
+ new UserError(
1602
+ "Timed out waiting for authorization code, please try again.",
1603
+ { telemetryMessage: "user oauth authorization timeout" }
1604
+ )
1605
+ );
1606
+ }, 12e4);
1607
+ });
1608
+ const loginPromise = new Promise((resolve, reject) => {
1609
+ server = http.createServer(async (req, res) => {
1610
+ function finish(token, error) {
1611
+ clearTimeout(loginTimeoutHandle);
1612
+ server.close((closeErr) => {
1613
+ if (error || closeErr) {
1614
+ reject(error || closeErr);
1615
+ } else {
1616
+ assert2(token);
1617
+ resolve(token);
1618
+ }
1619
+ });
1620
+ }
1621
+ __name(finish, "finish");
1622
+ assert2(req.url, "This request doesn't have a URL");
1623
+ const { pathname, query } = url.parse(req.url, true);
1624
+ if (req.method !== "GET") {
1625
+ return res.end("OK");
1626
+ }
1627
+ switch (pathname) {
1628
+ case "/oauth/callback": {
1629
+ let hasAuthCode = false;
1630
+ try {
1631
+ hasAuthCode = isReturningFromAuthServer(query, state, ctx.logger);
1632
+ } catch (err) {
1633
+ if (err instanceof ErrorAccessDenied) {
1634
+ res.writeHead(307, {
1635
+ Location: options.denied.url
1636
+ });
1637
+ res.end(() => {
1638
+ finish(
1639
+ null,
1640
+ new UserError(options.denied.error, {
1641
+ telemetryMessage: "user oauth consent denied"
1642
+ })
1643
+ );
1644
+ });
1645
+ return;
1646
+ } else {
1647
+ finish(null, err);
1648
+ return;
1649
+ }
1650
+ }
1651
+ if (!hasAuthCode) {
1652
+ finish(
1653
+ null,
1654
+ new ErrorNoAuthCode("", {
1655
+ telemetryMessage: "user oauth missing auth code"
1656
+ })
1657
+ );
1658
+ return;
1659
+ } else {
1660
+ try {
1661
+ const exchange = await exchangeAuthCodeForAccessToken(
1662
+ state,
1663
+ ctx.logger,
1664
+ ctx.isNonInteractiveOrCI
1665
+ );
1666
+ res.writeHead(307, {
1667
+ Location: options.granted.url
1668
+ });
1669
+ res.end(() => {
1670
+ finish(exchange);
1671
+ });
1672
+ } catch (err) {
1673
+ finish(null, err);
1674
+ }
1675
+ return;
1676
+ }
1677
+ }
1678
+ }
1679
+ });
1680
+ if (options.callbackHost !== "localhost" || options.callbackPort !== 8976) {
1681
+ ctx.logger.log(
1682
+ `Temporary login server listening on ${options.callbackHost}:${options.callbackPort}`
1683
+ );
1684
+ ctx.logger.log(
1685
+ "Note that the OAuth login page will always redirect to `localhost:8976`.\nIf you have changed the callback host or port because you are running in a container, then ensure that you have port forwarding set up correctly."
1686
+ );
1687
+ }
1688
+ server.once("error", (err) => {
1689
+ clearTimeout(loginTimeoutHandle);
1690
+ if (err.code === "EADDRINUSE") {
1691
+ reject(
1692
+ new UserError(
1693
+ `The OAuth callback server could not bind to ${options.callbackHost}:${options.callbackPort} because the port is already in use. Stop the process using that port or pass a different \`--callback-port\`.`,
1694
+ { telemetryMessage: "user oauth callback port in use" }
1695
+ )
1696
+ );
1697
+ } else {
1698
+ reject(err);
1699
+ }
1700
+ });
1701
+ server.listen(options.callbackPort, options.callbackHost);
1702
+ });
1703
+ if (options.browser) {
1704
+ ctx.logger.log(`Opening a link in your default browser: ${urlToOpen}`);
1705
+ await ctx.openInBrowser(urlToOpen);
1706
+ } else {
1707
+ ctx.logger.log(`Visit this link to authenticate: ${urlToOpen}`);
1708
+ }
1709
+ return Promise.race([timerPromise, loginPromise]);
1710
+ }
1711
+ __name(getOauthToken, "getOauthToken");
1712
+ function generateRandomState(lengthOfState) {
1713
+ const output = new Uint32Array(lengthOfState);
1714
+ webcrypto.getRandomValues(output);
1715
+ return Array.from(output).map((num) => PKCE_CHARSET[num % PKCE_CHARSET.length]).join("");
1716
+ }
1717
+ __name(generateRandomState, "generateRandomState");
1718
+
1719
+ // src/flow.ts
1720
+ function createOAuthFlow(ctx) {
1721
+ const oauthFlowState = {};
1722
+ const generators = {
1723
+ generateAuthUrl: ctx.generateAuthUrl ?? generateAuthUrl,
1724
+ generateRandomState: ctx.generateRandomState ?? generateRandomState
1725
+ };
1726
+ async function login(props) {
1727
+ if (ctx.hasEnvCredentials()) {
1728
+ ctx.logger.error(
1729
+ "You are logged in with an API Token. Unset the CLOUDFLARE_API_TOKEN in the environment to log in via OAuth."
1730
+ );
1731
+ return false;
1732
+ }
1733
+ const complianceRegion = getCloudflareComplianceRegion(
1734
+ props.complianceConfig
1735
+ );
1736
+ if (complianceRegion === "fedramp_high") {
1737
+ const configurationSource = props.complianceConfig?.compliance_region ? "`compliance_region` configuration property" : "`CLOUDFLARE_API_ENVIRONMENT` environment variable";
1738
+ throw new UserError(
1739
+ esm_default`
1740
+ OAuth login is not supported in the \`${complianceRegion}\` compliance region.
1741
+ Please use a Cloudflare API token (\`CLOUDFLARE_API_TOKEN\` environment variable) or remove the ${configurationSource}.
1742
+ `,
1743
+ {
1744
+ telemetryMessage: "user login unsupported compliance region"
1745
+ }
1746
+ );
1747
+ }
1748
+ ctx.logger.log("Attempting to login via OAuth...");
1749
+ const oauth = await getOauthToken(
1750
+ {
1751
+ browser: props.browser ?? true,
1752
+ scopes: props.scopes,
1753
+ clientId: getClientIdFromEnv(),
1754
+ denied: {
1755
+ url: "https://welcome.developers.workers.dev/wrangler-oauth-consent-denied",
1756
+ error: "Error: Consent denied. You must grant consent to Wrangler in order to login.\nIf you don't want to do this consider passing an API token via the `CLOUDFLARE_API_TOKEN` environment variable"
1757
+ },
1758
+ granted: {
1759
+ url: "https://welcome.developers.workers.dev/wrangler-oauth-consent-granted"
1760
+ },
1761
+ callbackHost: props.callbackHost ?? "localhost",
1762
+ callbackPort: props.callbackPort ?? 8976
1763
+ },
1764
+ oauthFlowState,
1765
+ ctx,
1766
+ generators
1767
+ );
1768
+ writeAuthConfigFile({
1769
+ oauth_token: oauth.token?.value ?? "",
1770
+ expiration_time: oauth.token?.expiry,
1771
+ refresh_token: oauth.refreshToken?.value,
1772
+ scopes: oauth.scopes
1773
+ });
1774
+ ctx.logger.log(`Successfully logged in.`);
1775
+ ctx.purgeOnLoginOrLogout?.();
1776
+ return true;
1777
+ }
1778
+ __name(login, "login");
1779
+ function isRefreshNeeded() {
1780
+ if (ctx.hasEnvCredentials()) {
1781
+ return false;
1782
+ }
1783
+ const { accessToken } = readStoredAuthState({ warningLogger: ctx.logger });
1784
+ return Boolean(accessToken && /* @__PURE__ */ new Date() >= new Date(accessToken.expiry));
1785
+ }
1786
+ __name(isRefreshNeeded, "isRefreshNeeded");
1787
+ async function refreshToken() {
1788
+ try {
1789
+ const {
1790
+ token: { value: oauth_token, expiry: expiration_time } = {
1791
+ value: "",
1792
+ expiry: ""
1793
+ },
1794
+ refreshToken: { value: refresh_token } = {},
1795
+ scopes
1796
+ } = await exchangeRefreshTokenForAccessToken(
1797
+ ctx.logger,
1798
+ ctx.isNonInteractiveOrCI
1799
+ );
1800
+ writeAuthConfigFile({
1801
+ oauth_token,
1802
+ expiration_time,
1803
+ refresh_token,
1804
+ scopes
1805
+ });
1806
+ return true;
1807
+ } catch (e) {
1808
+ ctx.logger.debug(
1809
+ `Token refresh failed: ${e instanceof Error ? e.message : String(e)}`
1810
+ );
1811
+ return false;
1812
+ }
1813
+ }
1814
+ __name(refreshToken, "refreshToken");
1815
+ async function loginOrRefreshIfRequired(props) {
1816
+ if (ctx.hasEnvCredentials()) {
1817
+ return true;
1818
+ }
1819
+ const stored = readStoredAuthState({ warningLogger: ctx.logger });
1820
+ if (!stored.accessToken && !stored.deprecatedApiToken) {
1821
+ return !ctx.isNonInteractiveOrCI() && await login(props);
1822
+ } else if (isRefreshNeeded()) {
1823
+ const didRefresh = await refreshToken();
1824
+ if (didRefresh) {
1825
+ return true;
1826
+ } else {
1827
+ return !ctx.isNonInteractiveOrCI() && await login(props);
1828
+ }
1829
+ } else {
1830
+ return true;
1831
+ }
1832
+ }
1833
+ __name(loginOrRefreshIfRequired, "loginOrRefreshIfRequired");
1834
+ async function logout() {
1835
+ if (ctx.hasEnvCredentials()) {
1836
+ ctx.logger.log(
1837
+ "You are logged in with an API Token. Unset the CLOUDFLARE_API_TOKEN in the environment to log out."
1838
+ );
1839
+ return;
1840
+ }
1841
+ const storedRefreshToken = readStoredAuthState({
1842
+ warningLogger: ctx.logger
1843
+ }).refreshToken;
1844
+ if (!storedRefreshToken) {
1845
+ ctx.logger.log("Not logged in, exiting...");
1846
+ return;
1847
+ }
1848
+ const body = `client_id=${encodeURIComponent(getClientIdFromEnv())}&token_type_hint=refresh_token&token=${encodeURIComponent(storedRefreshToken.value || "")}`;
1849
+ const response = await fetch(getRevokeUrlFromEnv(), {
1850
+ method: "POST",
1851
+ body,
1852
+ headers: {
1853
+ "Content-Type": "application/x-www-form-urlencoded"
1854
+ }
1855
+ });
1856
+ await response.text();
1857
+ rmSync(getAuthConfigFilePath());
1858
+ ctx.logger.log(`Successfully logged out.`);
1859
+ ctx.purgeOnLoginOrLogout?.();
1860
+ }
1861
+ __name(logout, "logout");
1862
+ async function getOAuthTokenFromLocalState() {
1863
+ let stored = readStoredAuthState({ warningLogger: ctx.logger });
1864
+ if (!stored.accessToken) {
1865
+ return void 0;
1866
+ }
1867
+ const expired = stored.accessToken && /* @__PURE__ */ new Date() >= new Date(stored.accessToken.expiry);
1868
+ if (expired) {
1869
+ const didRefresh = await refreshToken();
1870
+ if (!didRefresh) {
1871
+ return void 0;
1872
+ }
1873
+ stored = readStoredAuthState({ warningLogger: ctx.logger });
1874
+ }
1875
+ return stored.accessToken?.value;
1876
+ }
1877
+ __name(getOAuthTokenFromLocalState, "getOAuthTokenFromLocalState");
1878
+ return {
1879
+ login,
1880
+ logout,
1881
+ loginOrRefreshIfRequired,
1882
+ getOAuthTokenFromLocalState,
1883
+ isRefreshNeeded,
1884
+ refreshToken
1885
+ };
1886
+ }
1887
+ __name(createOAuthFlow, "createOAuthFlow");
1888
+ /*! Bundled license information:
1889
+
1890
+ smol-toml/dist/error.js:
1891
+ (*!
1892
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1893
+ * SPDX-License-Identifier: BSD-3-Clause
1894
+ *
1895
+ * Redistribution and use in source and binary forms, with or without
1896
+ * modification, are permitted provided that the following conditions are met:
1897
+ *
1898
+ * 1. Redistributions of source code must retain the above copyright notice, this
1899
+ * list of conditions and the following disclaimer.
1900
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1901
+ * this list of conditions and the following disclaimer in the
1902
+ * documentation and/or other materials provided with the distribution.
1903
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1904
+ * may be used to endorse or promote products derived from this software without
1905
+ * specific prior written permission.
1906
+ *
1907
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1908
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1909
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1910
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1911
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1912
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1913
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1914
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1915
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1916
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1917
+ *)
1918
+
1919
+ smol-toml/dist/util.js:
1920
+ (*!
1921
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1922
+ * SPDX-License-Identifier: BSD-3-Clause
1923
+ *
1924
+ * Redistribution and use in source and binary forms, with or without
1925
+ * modification, are permitted provided that the following conditions are met:
1926
+ *
1927
+ * 1. Redistributions of source code must retain the above copyright notice, this
1928
+ * list of conditions and the following disclaimer.
1929
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1930
+ * this list of conditions and the following disclaimer in the
1931
+ * documentation and/or other materials provided with the distribution.
1932
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1933
+ * may be used to endorse or promote products derived from this software without
1934
+ * specific prior written permission.
1935
+ *
1936
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1937
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1938
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1939
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1940
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1941
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1942
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1943
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1944
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1945
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1946
+ *)
1947
+
1948
+ smol-toml/dist/date.js:
1949
+ (*!
1950
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1951
+ * SPDX-License-Identifier: BSD-3-Clause
1952
+ *
1953
+ * Redistribution and use in source and binary forms, with or without
1954
+ * modification, are permitted provided that the following conditions are met:
1955
+ *
1956
+ * 1. Redistributions of source code must retain the above copyright notice, this
1957
+ * list of conditions and the following disclaimer.
1958
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1959
+ * this list of conditions and the following disclaimer in the
1960
+ * documentation and/or other materials provided with the distribution.
1961
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1962
+ * may be used to endorse or promote products derived from this software without
1963
+ * specific prior written permission.
1964
+ *
1965
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1966
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1967
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1968
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1969
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1970
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1971
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1972
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1973
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1974
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1975
+ *)
1976
+
1977
+ smol-toml/dist/primitive.js:
1978
+ (*!
1979
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1980
+ * SPDX-License-Identifier: BSD-3-Clause
1981
+ *
1982
+ * Redistribution and use in source and binary forms, with or without
1983
+ * modification, are permitted provided that the following conditions are met:
1984
+ *
1985
+ * 1. Redistributions of source code must retain the above copyright notice, this
1986
+ * list of conditions and the following disclaimer.
1987
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1988
+ * this list of conditions and the following disclaimer in the
1989
+ * documentation and/or other materials provided with the distribution.
1990
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1991
+ * may be used to endorse or promote products derived from this software without
1992
+ * specific prior written permission.
1993
+ *
1994
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1995
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1996
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1997
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1998
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1999
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2000
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2001
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2002
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2003
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2004
+ *)
2005
+
2006
+ smol-toml/dist/extract.js:
2007
+ (*!
2008
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2009
+ * SPDX-License-Identifier: BSD-3-Clause
2010
+ *
2011
+ * Redistribution and use in source and binary forms, with or without
2012
+ * modification, are permitted provided that the following conditions are met:
2013
+ *
2014
+ * 1. Redistributions of source code must retain the above copyright notice, this
2015
+ * list of conditions and the following disclaimer.
2016
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2017
+ * this list of conditions and the following disclaimer in the
2018
+ * documentation and/or other materials provided with the distribution.
2019
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2020
+ * may be used to endorse or promote products derived from this software without
2021
+ * specific prior written permission.
2022
+ *
2023
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2024
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2025
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2026
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2027
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2028
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2029
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2030
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2031
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2032
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2033
+ *)
2034
+
2035
+ smol-toml/dist/struct.js:
2036
+ (*!
2037
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2038
+ * SPDX-License-Identifier: BSD-3-Clause
2039
+ *
2040
+ * Redistribution and use in source and binary forms, with or without
2041
+ * modification, are permitted provided that the following conditions are met:
2042
+ *
2043
+ * 1. Redistributions of source code must retain the above copyright notice, this
2044
+ * list of conditions and the following disclaimer.
2045
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2046
+ * this list of conditions and the following disclaimer in the
2047
+ * documentation and/or other materials provided with the distribution.
2048
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2049
+ * may be used to endorse or promote products derived from this software without
2050
+ * specific prior written permission.
2051
+ *
2052
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2053
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2054
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2055
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2056
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2057
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2058
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2059
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2060
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2061
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2062
+ *)
2063
+
2064
+ smol-toml/dist/parse.js:
2065
+ (*!
2066
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2067
+ * SPDX-License-Identifier: BSD-3-Clause
2068
+ *
2069
+ * Redistribution and use in source and binary forms, with or without
2070
+ * modification, are permitted provided that the following conditions are met:
2071
+ *
2072
+ * 1. Redistributions of source code must retain the above copyright notice, this
2073
+ * list of conditions and the following disclaimer.
2074
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2075
+ * this list of conditions and the following disclaimer in the
2076
+ * documentation and/or other materials provided with the distribution.
2077
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2078
+ * may be used to endorse or promote products derived from this software without
2079
+ * specific prior written permission.
2080
+ *
2081
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2082
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2083
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2084
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2085
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2086
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2087
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2088
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2089
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2090
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2091
+ *)
2092
+
2093
+ smol-toml/dist/stringify.js:
2094
+ (*!
2095
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2096
+ * SPDX-License-Identifier: BSD-3-Clause
2097
+ *
2098
+ * Redistribution and use in source and binary forms, with or without
2099
+ * modification, are permitted provided that the following conditions are met:
2100
+ *
2101
+ * 1. Redistributions of source code must retain the above copyright notice, this
2102
+ * list of conditions and the following disclaimer.
2103
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2104
+ * this list of conditions and the following disclaimer in the
2105
+ * documentation and/or other materials provided with the distribution.
2106
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2107
+ * may be used to endorse or promote products derived from this software without
2108
+ * specific prior written permission.
2109
+ *
2110
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2111
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2112
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2113
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2114
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2115
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2116
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2117
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2118
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2119
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2120
+ *)
2121
+
2122
+ smol-toml/dist/index.js:
2123
+ (*!
2124
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2125
+ * SPDX-License-Identifier: BSD-3-Clause
2126
+ *
2127
+ * Redistribution and use in source and binary forms, with or without
2128
+ * modification, are permitted provided that the following conditions are met:
2129
+ *
2130
+ * 1. Redistributions of source code must retain the above copyright notice, this
2131
+ * list of conditions and the following disclaimer.
2132
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2133
+ * this list of conditions and the following disclaimer in the
2134
+ * documentation and/or other materials provided with the distribution.
2135
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2136
+ * may be used to endorse or promote products derived from this software without
2137
+ * specific prior written permission.
2138
+ *
2139
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2140
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2141
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2142
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2143
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2144
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2145
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2146
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2147
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2148
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2149
+ *)
2150
+ */
2151
+
2152
+ export { ErrorAccessDenied, ErrorAccessTokenResponse, ErrorAuthenticationGrant, ErrorInvalidClient, ErrorInvalidGrant, ErrorInvalidJson, ErrorInvalidRequest, ErrorInvalidReturnedStateParam, ErrorInvalidScope, ErrorInvalidToken, ErrorNoAuthCode, ErrorOAuth2, ErrorServerError, ErrorTemporarilyUnavailable, ErrorUnauthorizedClient, ErrorUnknown, ErrorUnsupportedGrantType, ErrorUnsupportedResponseType, OAUTH_CALLBACK_URL, PKCE_CHARSET, RECOMMENDED_CODE_VERIFIER_LENGTH, RECOMMENDED_STATE_LENGTH, base64urlEncode, clearAccessCaches, createOAuthFlow, domainUsesAccess, generateAuthUrl, generatePKCECodes, generateRandomState, getAccessClientIdFromEnv, getAccessClientSecretFromEnv, getAccessHeaders, getAuthConfigFilePath, getAuthDomainFromEnv, getAuthUrlFromEnv, getCfAuthorizationTokenFromEnv, getClientIdFromEnv, getCloudflareAccessHeaders, getRevokeUrlFromEnv, getTokenUrlFromEnv, readAuthConfigFile, readStoredAuthState, toErrorClass, writeAuthConfigFile };
2153
+ //# sourceMappingURL=index.mjs.map
2154
+ //# sourceMappingURL=index.mjs.map