@cloudflare/workers-auth 0.4.2 → 0.5.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.
@@ -0,0 +1,1356 @@
1
+ import { stringifyFile, parseFile, dedent, createCredentialStorageContext, createOAuthFlow, getAuthFromEnv, createProfileStore, getCloudflareAccountIdFromEnv, getAuthConfigFilePath, getEncryptedAuthConfigFilePath, scrubEncryptedCredentials, validateProfileName, getCloudflareAuthUseKeyringFromEnv } from './chunk-FX4KV7FS.mjs';
2
+ import { __name } from './chunk-O6YSETKJ.mjs';
3
+ import { existsSync, rmSync, mkdirSync, writeFileSync, chmodSync, readFileSync as readFileSync$1, readdirSync } from 'node:fs';
4
+ import path3 from 'node:path';
5
+ import { URLSearchParams } from 'node:url';
6
+ import { readFileSync, isNonInteractiveOrCI, createConfigCache, openInBrowser, UserError, fetchInternalBase, hasMorePages, throwFetchError, isCI, getCloudflareComplianceRegion } from '@cloudflare/workers-utils';
7
+
8
+ function createPreferences(getConfigPath) {
9
+ function getUserPreferencesPath() {
10
+ return path3.resolve(getConfigPath(), "preferences.json");
11
+ }
12
+ __name(getUserPreferencesPath, "getUserPreferencesPath");
13
+ function readUserPreferences() {
14
+ try {
15
+ const raw = readFileSync$1(getUserPreferencesPath(), "utf8");
16
+ const parsed = JSON.parse(raw);
17
+ if (typeof parsed === "object" && parsed !== null) {
18
+ return parsed;
19
+ }
20
+ return {};
21
+ } catch {
22
+ return {};
23
+ }
24
+ }
25
+ __name(readUserPreferences, "readUserPreferences");
26
+ function updateUserPreferences(update) {
27
+ const current = readUserPreferences();
28
+ const next = { ...current, ...update };
29
+ const filePath = getUserPreferencesPath();
30
+ mkdirSync(path3.dirname(filePath), { recursive: true });
31
+ writeFileSync(filePath, JSON.stringify(next, null, " "), {
32
+ encoding: "utf-8"
33
+ });
34
+ }
35
+ __name(updateUserPreferences, "updateUserPreferences");
36
+ return { readUserPreferences, updateUserPreferences };
37
+ }
38
+ __name(createPreferences, "createPreferences");
39
+ var millisecondsInMinute = 6e4;
40
+ var minutesInYear = 525600;
41
+ var minutesInMonth = 43200;
42
+ var minutesInDay = 1440;
43
+ var constructFromSymbol = Symbol.for("constructDateFrom");
44
+
45
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructFrom.js
46
+ function constructFrom(date, value) {
47
+ if (typeof date === "function") return date(value);
48
+ if (date && typeof date === "object" && constructFromSymbol in date)
49
+ return date[constructFromSymbol](value);
50
+ if (date instanceof Date) return new date.constructor(value);
51
+ return new Date(value);
52
+ }
53
+ __name(constructFrom, "constructFrom");
54
+
55
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/toDate.js
56
+ function toDate(argument, context) {
57
+ return constructFrom(context || argument, argument);
58
+ }
59
+ __name(toDate, "toDate");
60
+
61
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultOptions.js
62
+ var defaultOptions = {};
63
+ function getDefaultOptions() {
64
+ return defaultOptions;
65
+ }
66
+ __name(getDefaultOptions, "getDefaultOptions");
67
+
68
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.js
69
+ function getTimezoneOffsetInMilliseconds(date) {
70
+ const _date = toDate(date);
71
+ const utcDate = new Date(
72
+ Date.UTC(
73
+ _date.getFullYear(),
74
+ _date.getMonth(),
75
+ _date.getDate(),
76
+ _date.getHours(),
77
+ _date.getMinutes(),
78
+ _date.getSeconds(),
79
+ _date.getMilliseconds()
80
+ )
81
+ );
82
+ utcDate.setUTCFullYear(_date.getFullYear());
83
+ return +date - +utcDate;
84
+ }
85
+ __name(getTimezoneOffsetInMilliseconds, "getTimezoneOffsetInMilliseconds");
86
+
87
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/normalizeDates.js
88
+ function normalizeDates(context, ...dates) {
89
+ const normalize = constructFrom.bind(
90
+ null,
91
+ context || dates.find((date) => typeof date === "object")
92
+ );
93
+ return dates.map(normalize);
94
+ }
95
+ __name(normalizeDates, "normalizeDates");
96
+
97
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareAsc.js
98
+ function compareAsc(dateLeft, dateRight) {
99
+ const diff = +toDate(dateLeft) - +toDate(dateRight);
100
+ if (diff < 0) return -1;
101
+ else if (diff > 0) return 1;
102
+ return diff;
103
+ }
104
+ __name(compareAsc, "compareAsc");
105
+
106
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructNow.js
107
+ function constructNow(date) {
108
+ return constructFrom(date, Date.now());
109
+ }
110
+ __name(constructNow, "constructNow");
111
+
112
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getRoundingMethod.js
113
+ function getRoundingMethod(method) {
114
+ return (number) => {
115
+ const round = method ? Math[method] : Math.trunc;
116
+ const result = round(number);
117
+ return result === 0 ? 0 : result;
118
+ };
119
+ }
120
+ __name(getRoundingMethod, "getRoundingMethod");
121
+
122
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatDistance.js
123
+ var formatDistanceLocale = {
124
+ lessThanXSeconds: {
125
+ one: "less than a second",
126
+ other: "less than {{count}} seconds"
127
+ },
128
+ xSeconds: {
129
+ one: "1 second",
130
+ other: "{{count}} seconds"
131
+ },
132
+ halfAMinute: "half a minute",
133
+ lessThanXMinutes: {
134
+ one: "less than a minute",
135
+ other: "less than {{count}} minutes"
136
+ },
137
+ xMinutes: {
138
+ one: "1 minute",
139
+ other: "{{count}} minutes"
140
+ },
141
+ aboutXHours: {
142
+ one: "about 1 hour",
143
+ other: "about {{count}} hours"
144
+ },
145
+ xHours: {
146
+ one: "1 hour",
147
+ other: "{{count}} hours"
148
+ },
149
+ xDays: {
150
+ one: "1 day",
151
+ other: "{{count}} days"
152
+ },
153
+ aboutXWeeks: {
154
+ one: "about 1 week",
155
+ other: "about {{count}} weeks"
156
+ },
157
+ xWeeks: {
158
+ one: "1 week",
159
+ other: "{{count}} weeks"
160
+ },
161
+ aboutXMonths: {
162
+ one: "about 1 month",
163
+ other: "about {{count}} months"
164
+ },
165
+ xMonths: {
166
+ one: "1 month",
167
+ other: "{{count}} months"
168
+ },
169
+ aboutXYears: {
170
+ one: "about 1 year",
171
+ other: "about {{count}} years"
172
+ },
173
+ xYears: {
174
+ one: "1 year",
175
+ other: "{{count}} years"
176
+ },
177
+ overXYears: {
178
+ one: "over 1 year",
179
+ other: "over {{count}} years"
180
+ },
181
+ almostXYears: {
182
+ one: "almost 1 year",
183
+ other: "almost {{count}} years"
184
+ }
185
+ };
186
+ var formatDistance = /* @__PURE__ */ __name((token, count, options) => {
187
+ let result;
188
+ const tokenValue = formatDistanceLocale[token];
189
+ if (typeof tokenValue === "string") {
190
+ result = tokenValue;
191
+ } else if (count === 1) {
192
+ result = tokenValue.one;
193
+ } else {
194
+ result = tokenValue.other.replace("{{count}}", count.toString());
195
+ }
196
+ if (options?.addSuffix) {
197
+ if (options.comparison && options.comparison > 0) {
198
+ return "in " + result;
199
+ } else {
200
+ return result + " ago";
201
+ }
202
+ }
203
+ return result;
204
+ }, "formatDistance");
205
+
206
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildFormatLongFn.js
207
+ function buildFormatLongFn(args) {
208
+ return (options = {}) => {
209
+ const width = options.width ? String(options.width) : args.defaultWidth;
210
+ const format = args.formats[width] || args.formats[args.defaultWidth];
211
+ return format;
212
+ };
213
+ }
214
+ __name(buildFormatLongFn, "buildFormatLongFn");
215
+
216
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatLong.js
217
+ var dateFormats = {
218
+ full: "EEEE, MMMM do, y",
219
+ long: "MMMM do, y",
220
+ medium: "MMM d, y",
221
+ short: "MM/dd/yyyy"
222
+ };
223
+ var timeFormats = {
224
+ full: "h:mm:ss a zzzz",
225
+ long: "h:mm:ss a z",
226
+ medium: "h:mm:ss a",
227
+ short: "h:mm a"
228
+ };
229
+ var dateTimeFormats = {
230
+ full: "{{date}} 'at' {{time}}",
231
+ long: "{{date}} 'at' {{time}}",
232
+ medium: "{{date}}, {{time}}",
233
+ short: "{{date}}, {{time}}"
234
+ };
235
+ var formatLong = {
236
+ date: buildFormatLongFn({
237
+ formats: dateFormats,
238
+ defaultWidth: "full"
239
+ }),
240
+ time: buildFormatLongFn({
241
+ formats: timeFormats,
242
+ defaultWidth: "full"
243
+ }),
244
+ dateTime: buildFormatLongFn({
245
+ formats: dateTimeFormats,
246
+ defaultWidth: "full"
247
+ })
248
+ };
249
+
250
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatRelative.js
251
+ var formatRelativeLocale = {
252
+ lastWeek: "'last' eeee 'at' p",
253
+ yesterday: "'yesterday at' p",
254
+ today: "'today at' p",
255
+ tomorrow: "'tomorrow at' p",
256
+ nextWeek: "eeee 'at' p",
257
+ other: "P"
258
+ };
259
+ var formatRelative = /* @__PURE__ */ __name((token, _date, _baseDate, _options) => formatRelativeLocale[token], "formatRelative");
260
+
261
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildLocalizeFn.js
262
+ function buildLocalizeFn(args) {
263
+ return (value, options) => {
264
+ const context = options?.context ? String(options.context) : "standalone";
265
+ let valuesArray;
266
+ if (context === "formatting" && args.formattingValues) {
267
+ const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
268
+ const width = options?.width ? String(options.width) : defaultWidth;
269
+ valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
270
+ } else {
271
+ const defaultWidth = args.defaultWidth;
272
+ const width = options?.width ? String(options.width) : args.defaultWidth;
273
+ valuesArray = args.values[width] || args.values[defaultWidth];
274
+ }
275
+ const index = args.argumentCallback ? args.argumentCallback(value) : value;
276
+ return valuesArray[index];
277
+ };
278
+ }
279
+ __name(buildLocalizeFn, "buildLocalizeFn");
280
+
281
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/localize.js
282
+ var eraValues = {
283
+ narrow: ["B", "A"],
284
+ abbreviated: ["BC", "AD"],
285
+ wide: ["Before Christ", "Anno Domini"]
286
+ };
287
+ var quarterValues = {
288
+ narrow: ["1", "2", "3", "4"],
289
+ abbreviated: ["Q1", "Q2", "Q3", "Q4"],
290
+ wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]
291
+ };
292
+ var monthValues = {
293
+ narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
294
+ abbreviated: [
295
+ "Jan",
296
+ "Feb",
297
+ "Mar",
298
+ "Apr",
299
+ "May",
300
+ "Jun",
301
+ "Jul",
302
+ "Aug",
303
+ "Sep",
304
+ "Oct",
305
+ "Nov",
306
+ "Dec"
307
+ ],
308
+ wide: [
309
+ "January",
310
+ "February",
311
+ "March",
312
+ "April",
313
+ "May",
314
+ "June",
315
+ "July",
316
+ "August",
317
+ "September",
318
+ "October",
319
+ "November",
320
+ "December"
321
+ ]
322
+ };
323
+ var dayValues = {
324
+ narrow: ["S", "M", "T", "W", "T", "F", "S"],
325
+ short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
326
+ abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
327
+ wide: [
328
+ "Sunday",
329
+ "Monday",
330
+ "Tuesday",
331
+ "Wednesday",
332
+ "Thursday",
333
+ "Friday",
334
+ "Saturday"
335
+ ]
336
+ };
337
+ var dayPeriodValues = {
338
+ narrow: {
339
+ am: "a",
340
+ pm: "p",
341
+ midnight: "mi",
342
+ noon: "n",
343
+ morning: "morning",
344
+ afternoon: "afternoon",
345
+ evening: "evening",
346
+ night: "night"
347
+ },
348
+ abbreviated: {
349
+ am: "AM",
350
+ pm: "PM",
351
+ midnight: "midnight",
352
+ noon: "noon",
353
+ morning: "morning",
354
+ afternoon: "afternoon",
355
+ evening: "evening",
356
+ night: "night"
357
+ },
358
+ wide: {
359
+ am: "a.m.",
360
+ pm: "p.m.",
361
+ midnight: "midnight",
362
+ noon: "noon",
363
+ morning: "morning",
364
+ afternoon: "afternoon",
365
+ evening: "evening",
366
+ night: "night"
367
+ }
368
+ };
369
+ var formattingDayPeriodValues = {
370
+ narrow: {
371
+ am: "a",
372
+ pm: "p",
373
+ midnight: "mi",
374
+ noon: "n",
375
+ morning: "in the morning",
376
+ afternoon: "in the afternoon",
377
+ evening: "in the evening",
378
+ night: "at night"
379
+ },
380
+ abbreviated: {
381
+ am: "AM",
382
+ pm: "PM",
383
+ midnight: "midnight",
384
+ noon: "noon",
385
+ morning: "in the morning",
386
+ afternoon: "in the afternoon",
387
+ evening: "in the evening",
388
+ night: "at night"
389
+ },
390
+ wide: {
391
+ am: "a.m.",
392
+ pm: "p.m.",
393
+ midnight: "midnight",
394
+ noon: "noon",
395
+ morning: "in the morning",
396
+ afternoon: "in the afternoon",
397
+ evening: "in the evening",
398
+ night: "at night"
399
+ }
400
+ };
401
+ var ordinalNumber = /* @__PURE__ */ __name((dirtyNumber, _options) => {
402
+ const number = Number(dirtyNumber);
403
+ const rem100 = number % 100;
404
+ if (rem100 > 20 || rem100 < 10) {
405
+ switch (rem100 % 10) {
406
+ case 1:
407
+ return number + "st";
408
+ case 2:
409
+ return number + "nd";
410
+ case 3:
411
+ return number + "rd";
412
+ }
413
+ }
414
+ return number + "th";
415
+ }, "ordinalNumber");
416
+ var localize = {
417
+ ordinalNumber,
418
+ era: buildLocalizeFn({
419
+ values: eraValues,
420
+ defaultWidth: "wide"
421
+ }),
422
+ quarter: buildLocalizeFn({
423
+ values: quarterValues,
424
+ defaultWidth: "wide",
425
+ argumentCallback: /* @__PURE__ */ __name((quarter) => quarter - 1, "argumentCallback")
426
+ }),
427
+ month: buildLocalizeFn({
428
+ values: monthValues,
429
+ defaultWidth: "wide"
430
+ }),
431
+ day: buildLocalizeFn({
432
+ values: dayValues,
433
+ defaultWidth: "wide"
434
+ }),
435
+ dayPeriod: buildLocalizeFn({
436
+ values: dayPeriodValues,
437
+ defaultWidth: "wide",
438
+ formattingValues: formattingDayPeriodValues,
439
+ defaultFormattingWidth: "wide"
440
+ })
441
+ };
442
+
443
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchFn.js
444
+ function buildMatchFn(args) {
445
+ return (string, options = {}) => {
446
+ const width = options.width;
447
+ const matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
448
+ const matchResult = string.match(matchPattern);
449
+ if (!matchResult) {
450
+ return null;
451
+ }
452
+ const matchedString = matchResult[0];
453
+ const parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
454
+ const key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, (pattern) => pattern.test(matchedString)) : (
455
+ // [TODO] -- I challenge you to fix the type
456
+ findKey(parsePatterns, (pattern) => pattern.test(matchedString))
457
+ );
458
+ let value;
459
+ value = args.valueCallback ? args.valueCallback(key) : key;
460
+ value = options.valueCallback ? (
461
+ // [TODO] -- I challenge you to fix the type
462
+ options.valueCallback(value)
463
+ ) : value;
464
+ const rest = string.slice(matchedString.length);
465
+ return { value, rest };
466
+ };
467
+ }
468
+ __name(buildMatchFn, "buildMatchFn");
469
+ function findKey(object, predicate) {
470
+ for (const key in object) {
471
+ if (Object.prototype.hasOwnProperty.call(object, key) && predicate(object[key])) {
472
+ return key;
473
+ }
474
+ }
475
+ return void 0;
476
+ }
477
+ __name(findKey, "findKey");
478
+ function findIndex(array, predicate) {
479
+ for (let key = 0; key < array.length; key++) {
480
+ if (predicate(array[key])) {
481
+ return key;
482
+ }
483
+ }
484
+ return void 0;
485
+ }
486
+ __name(findIndex, "findIndex");
487
+
488
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchPatternFn.js
489
+ function buildMatchPatternFn(args) {
490
+ return (string, options = {}) => {
491
+ const matchResult = string.match(args.matchPattern);
492
+ if (!matchResult) return null;
493
+ const matchedString = matchResult[0];
494
+ const parseResult = string.match(args.parsePattern);
495
+ if (!parseResult) return null;
496
+ let value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
497
+ value = options.valueCallback ? options.valueCallback(value) : value;
498
+ const rest = string.slice(matchedString.length);
499
+ return { value, rest };
500
+ };
501
+ }
502
+ __name(buildMatchPatternFn, "buildMatchPatternFn");
503
+
504
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/match.js
505
+ var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
506
+ var parseOrdinalNumberPattern = /\d+/i;
507
+ var matchEraPatterns = {
508
+ narrow: /^(b|a)/i,
509
+ abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
510
+ wide: /^(before christ|before common era|anno domini|common era)/i
511
+ };
512
+ var parseEraPatterns = {
513
+ any: [/^b/i, /^(a|c)/i]
514
+ };
515
+ var matchQuarterPatterns = {
516
+ narrow: /^[1234]/i,
517
+ abbreviated: /^q[1234]/i,
518
+ wide: /^[1234](th|st|nd|rd)? quarter/i
519
+ };
520
+ var parseQuarterPatterns = {
521
+ any: [/1/i, /2/i, /3/i, /4/i]
522
+ };
523
+ var matchMonthPatterns = {
524
+ narrow: /^[jfmasond]/i,
525
+ abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
526
+ wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
527
+ };
528
+ var parseMonthPatterns = {
529
+ narrow: [
530
+ /^j/i,
531
+ /^f/i,
532
+ /^m/i,
533
+ /^a/i,
534
+ /^m/i,
535
+ /^j/i,
536
+ /^j/i,
537
+ /^a/i,
538
+ /^s/i,
539
+ /^o/i,
540
+ /^n/i,
541
+ /^d/i
542
+ ],
543
+ any: [
544
+ /^ja/i,
545
+ /^f/i,
546
+ /^mar/i,
547
+ /^ap/i,
548
+ /^may/i,
549
+ /^jun/i,
550
+ /^jul/i,
551
+ /^au/i,
552
+ /^s/i,
553
+ /^o/i,
554
+ /^n/i,
555
+ /^d/i
556
+ ]
557
+ };
558
+ var matchDayPatterns = {
559
+ narrow: /^[smtwf]/i,
560
+ short: /^(su|mo|tu|we|th|fr|sa)/i,
561
+ abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
562
+ wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
563
+ };
564
+ var parseDayPatterns = {
565
+ narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
566
+ any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
567
+ };
568
+ var matchDayPeriodPatterns = {
569
+ narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
570
+ any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
571
+ };
572
+ var parseDayPeriodPatterns = {
573
+ any: {
574
+ am: /^a/i,
575
+ pm: /^p/i,
576
+ midnight: /^mi/i,
577
+ noon: /^no/i,
578
+ morning: /morning/i,
579
+ afternoon: /afternoon/i,
580
+ evening: /evening/i,
581
+ night: /night/i
582
+ }
583
+ };
584
+ var match = {
585
+ ordinalNumber: buildMatchPatternFn({
586
+ matchPattern: matchOrdinalNumberPattern,
587
+ parsePattern: parseOrdinalNumberPattern,
588
+ valueCallback: /* @__PURE__ */ __name((value) => parseInt(value, 10), "valueCallback")
589
+ }),
590
+ era: buildMatchFn({
591
+ matchPatterns: matchEraPatterns,
592
+ defaultMatchWidth: "wide",
593
+ parsePatterns: parseEraPatterns,
594
+ defaultParseWidth: "any"
595
+ }),
596
+ quarter: buildMatchFn({
597
+ matchPatterns: matchQuarterPatterns,
598
+ defaultMatchWidth: "wide",
599
+ parsePatterns: parseQuarterPatterns,
600
+ defaultParseWidth: "any",
601
+ valueCallback: /* @__PURE__ */ __name((index) => index + 1, "valueCallback")
602
+ }),
603
+ month: buildMatchFn({
604
+ matchPatterns: matchMonthPatterns,
605
+ defaultMatchWidth: "wide",
606
+ parsePatterns: parseMonthPatterns,
607
+ defaultParseWidth: "any"
608
+ }),
609
+ day: buildMatchFn({
610
+ matchPatterns: matchDayPatterns,
611
+ defaultMatchWidth: "wide",
612
+ parsePatterns: parseDayPatterns,
613
+ defaultParseWidth: "any"
614
+ }),
615
+ dayPeriod: buildMatchFn({
616
+ matchPatterns: matchDayPeriodPatterns,
617
+ defaultMatchWidth: "any",
618
+ parsePatterns: parseDayPeriodPatterns,
619
+ defaultParseWidth: "any"
620
+ })
621
+ };
622
+
623
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US.js
624
+ var enUS = {
625
+ code: "en-US",
626
+ formatDistance,
627
+ formatLong,
628
+ formatRelative,
629
+ localize,
630
+ match,
631
+ options: {
632
+ weekStartsOn: 0,
633
+ firstWeekContainsDate: 1
634
+ }
635
+ };
636
+
637
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceStrict.js
638
+ function formatDistanceStrict(laterDate, earlierDate, options) {
639
+ const defaultOptions2 = getDefaultOptions();
640
+ const locale = options?.locale ?? defaultOptions2.locale ?? enUS;
641
+ const comparison = compareAsc(laterDate, earlierDate);
642
+ if (isNaN(comparison)) {
643
+ throw new RangeError("Invalid time value");
644
+ }
645
+ const localizeOptions = Object.assign({}, options, {
646
+ addSuffix: options?.addSuffix,
647
+ comparison
648
+ });
649
+ const [laterDate_, earlierDate_] = normalizeDates(
650
+ options?.in,
651
+ ...comparison > 0 ? [earlierDate, laterDate] : [laterDate, earlierDate]
652
+ );
653
+ const roundingMethod = getRoundingMethod(options?.roundingMethod ?? "round");
654
+ const milliseconds = earlierDate_.getTime() - laterDate_.getTime();
655
+ const minutes = milliseconds / millisecondsInMinute;
656
+ const timezoneOffset = getTimezoneOffsetInMilliseconds(earlierDate_) - getTimezoneOffsetInMilliseconds(laterDate_);
657
+ const dstNormalizedMinutes = (milliseconds - timezoneOffset) / millisecondsInMinute;
658
+ const defaultUnit = options?.unit;
659
+ let unit;
660
+ if (!defaultUnit) {
661
+ if (minutes < 1) {
662
+ unit = "second";
663
+ } else if (minutes < 60) {
664
+ unit = "minute";
665
+ } else if (minutes < minutesInDay) {
666
+ unit = "hour";
667
+ } else if (dstNormalizedMinutes < minutesInMonth) {
668
+ unit = "day";
669
+ } else if (dstNormalizedMinutes < minutesInYear) {
670
+ unit = "month";
671
+ } else {
672
+ unit = "year";
673
+ }
674
+ } else {
675
+ unit = defaultUnit;
676
+ }
677
+ if (unit === "second") {
678
+ const seconds = roundingMethod(milliseconds / 1e3);
679
+ return locale.formatDistance("xSeconds", seconds, localizeOptions);
680
+ } else if (unit === "minute") {
681
+ const roundedMinutes = roundingMethod(minutes);
682
+ return locale.formatDistance("xMinutes", roundedMinutes, localizeOptions);
683
+ } else if (unit === "hour") {
684
+ const hours = roundingMethod(minutes / 60);
685
+ return locale.formatDistance("xHours", hours, localizeOptions);
686
+ } else if (unit === "day") {
687
+ const days = roundingMethod(dstNormalizedMinutes / minutesInDay);
688
+ return locale.formatDistance("xDays", days, localizeOptions);
689
+ } else if (unit === "month") {
690
+ const months = roundingMethod(dstNormalizedMinutes / minutesInMonth);
691
+ return months === 12 && defaultUnit !== "month" ? locale.formatDistance("xYears", 1, localizeOptions) : locale.formatDistance("xMonths", months, localizeOptions);
692
+ } else {
693
+ const years = roundingMethod(dstNormalizedMinutes / minutesInYear);
694
+ return locale.formatDistance("xYears", years, localizeOptions);
695
+ }
696
+ }
697
+ __name(formatDistanceStrict, "formatDistanceStrict");
698
+
699
+ // ../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNowStrict.js
700
+ function formatDistanceToNowStrict(date, options) {
701
+ return formatDistanceStrict(date, constructNow(date), options);
702
+ }
703
+ __name(formatDistanceToNowStrict, "formatDistanceToNowStrict");
704
+ function createFileStorage(format, getPath) {
705
+ return {
706
+ read: /* @__PURE__ */ __name(() => {
707
+ const filePath = getPath();
708
+ if (!existsSync(filePath)) {
709
+ return void 0;
710
+ }
711
+ const contents = readFileSync(filePath);
712
+ try {
713
+ return parseFile(format, contents);
714
+ } catch {
715
+ return void 0;
716
+ }
717
+ }, "read"),
718
+ write(config) {
719
+ const configPath = getPath();
720
+ mkdirSync(path3.dirname(configPath), { recursive: true });
721
+ writeFileSync(configPath, stringifyFile(format, config), {
722
+ encoding: "utf-8",
723
+ mode: 384
724
+ });
725
+ chmodSync(configPath, 384);
726
+ },
727
+ clear() {
728
+ const configPath = getPath();
729
+ const existed = existsSync(configPath);
730
+ rmSync(configPath, { force: true });
731
+ return existed;
732
+ },
733
+ path: getPath
734
+ };
735
+ }
736
+ __name(createFileStorage, "createFileStorage");
737
+ function createTemporaryTermsPrompt(deps) {
738
+ const { logger, prompt } = deps;
739
+ return /* @__PURE__ */ __name(async function ensureTemporaryTermsAccepted(question, notice) {
740
+ if (isNonInteractiveOrCI()) {
741
+ logger.log(notice);
742
+ return true;
743
+ }
744
+ const answer = await prompt(question);
745
+ return typeof answer === "string" && answer.trim().toLowerCase() === "yes";
746
+ }, "ensureTemporaryTermsAccepted");
747
+ }
748
+ __name(createTemporaryTermsPrompt, "createTemporaryTermsPrompt");
749
+
750
+ // src/core/factory.ts
751
+ var MEMBERSHIPS_INACCESSIBLE_CODES = [9106, 1e4];
752
+ function getErrorCode(err) {
753
+ return err?.code;
754
+ }
755
+ __name(getErrorCode, "getErrorCode");
756
+ function isMembershipsInaccessible(err) {
757
+ const code = getErrorCode(err);
758
+ return code !== void 0 && MEMBERSHIPS_INACCESSIBLE_CODES.includes(code);
759
+ }
760
+ __name(isMembershipsInaccessible, "isMembershipsInaccessible");
761
+ function notLoggedInErrorBodies(loginCommand) {
762
+ return {
763
+ "no-credentials-non-interactive": `Could not authenticate because no credentials were found and the environment is non-interactive. Set a CLOUDFLARE_API_TOKEN environment variable or run \`${loginCommand}\` in an interactive terminal first.`,
764
+ "no-credentials-login-failed": `No credentials were found and the login attempt was unsuccessful. Run \`${loginCommand}\` to try again.`,
765
+ "token-expired-non-interactive": `Your auth token has expired and could not be refreshed, and the environment is non-interactive. Run \`${loginCommand}\` in an interactive terminal or set a CLOUDFLARE_API_TOKEN.`,
766
+ "token-expired-login-failed": `Your auth token has expired and could not be refreshed, and the login attempt was unsuccessful. Run \`${loginCommand}\` to try again.`
767
+ };
768
+ }
769
+ __name(notLoggedInErrorBodies, "notLoggedInErrorBodies");
770
+ function logTemporaryPreviewAccount(logger, temporaryPreviewAccount, cached) {
771
+ const claimExpiresAt = new Date(temporaryPreviewAccount.claim.expiresAt);
772
+ logger.log(
773
+ dedent`
774
+ Temporary account ready:
775
+ Account: ${temporaryPreviewAccount.account.name} (${cached ? "reused" : "created"})
776
+ Claim within: ${formatDistanceToNowStrict(claimExpiresAt)}
777
+ Claim URL: ${temporaryPreviewAccount.claim.url}
778
+ `
779
+ );
780
+ }
781
+ __name(logTemporaryPreviewAccount, "logTemporaryPreviewAccount");
782
+ function createCloudflareAuth(descriptor, ctx) {
783
+ const { logger } = ctx;
784
+ const cliName = descriptor.cliName;
785
+ const NOT_LOGGED_IN_ERROR_BODIES = notLoggedInErrorBodies(
786
+ descriptor.commands.login
787
+ );
788
+ const NOT_LOGGED_IN_WHOAMI_TIP = `
789
+ Run \`${descriptor.commands.whoami}\` to check your current authentication status.`;
790
+ const preferences = createPreferences(descriptor.getConfigPath);
791
+ const configCache = createConfigCache(
792
+ logger,
793
+ descriptor.cacheNamespace ? { namespace: descriptor.cacheNamespace } : void 0
794
+ );
795
+ const credentialStorage = createCredentialStorageContext({
796
+ serviceName: descriptor.keyringServiceName,
797
+ getConfigPath: descriptor.getConfigPath,
798
+ isKeyringEnabled: /* @__PURE__ */ __name(() => preferences.readUserPreferences().keyring_enabled === true, "isKeyringEnabled"),
799
+ logger,
800
+ isNonInteractiveOrCI: isNonInteractiveOrCI,
801
+ loginCommand: descriptor.commands.login,
802
+ format: descriptor.fileFormat
803
+ });
804
+ const allowGlobalAuthKey = descriptor.allowGlobalAuthKey ?? true;
805
+ const oauthFlow = createOAuthFlow({
806
+ logger,
807
+ isNonInteractiveOrCI: isNonInteractiveOrCI,
808
+ openInBrowser: /* @__PURE__ */ __name((url) => openInBrowser(url, logger), "openInBrowser"),
809
+ hasEnvCredentials: /* @__PURE__ */ __name(() => getAuthFromEnv({ allowGlobalAuthKey }) !== void 0, "hasEnvCredentials"),
810
+ purgeOnLoginOrLogout: configCache.purgeConfigCaches,
811
+ clientId: descriptor.clientId,
812
+ consent: descriptor.consent,
813
+ redirectUri: descriptor.redirectUri,
814
+ storageFactory: credentialStorage.storageFactory,
815
+ allowGlobalAuthKey,
816
+ temporary: {
817
+ // The temporary-preview-account cache is CLI-owned storage (a
818
+ // file under the global config dir, scoped to the Cloudflare API
819
+ // environment), so it's built here rather than injected.
820
+ storage: createFileStorage(
821
+ descriptor.fileFormat,
822
+ descriptor.getTemporaryAccountConfigPath
823
+ ),
824
+ prompt: createTemporaryTermsPrompt({ logger, prompt: ctx.prompt })
825
+ }
826
+ });
827
+ function setProfile(profile) {
828
+ oauthFlow.setProfile(profile);
829
+ }
830
+ __name(setProfile, "setProfile");
831
+ function getActiveProfile() {
832
+ return oauthFlow.getActiveProfile();
833
+ }
834
+ __name(getActiveProfile, "getActiveProfile");
835
+ function getCredentialStore() {
836
+ return credentialStorage.getActiveStore(oauthFlow.getActiveProfile());
837
+ }
838
+ __name(getCredentialStore, "getCredentialStore");
839
+ function setTemporaryAllowed(allowed) {
840
+ oauthFlow.setTemporaryAllowed(allowed);
841
+ }
842
+ __name(setTemporaryAllowed, "setTemporaryAllowed");
843
+ function getAPIToken() {
844
+ return oauthFlow.getAPIToken();
845
+ }
846
+ __name(getAPIToken, "getAPIToken");
847
+ function requireApiToken() {
848
+ return oauthFlow.requireApiToken();
849
+ }
850
+ __name(requireApiToken, "requireApiToken");
851
+ function withDefaultScopes(complianceConfig, props) {
852
+ return {
853
+ complianceConfig,
854
+ scopes: props?.scopes ?? descriptor.getDefaultScopeKeys(),
855
+ browser: props?.browser ?? true,
856
+ callbackHost: props?.callbackHost,
857
+ callbackPort: props?.callbackPort,
858
+ profile: props?.profile
859
+ };
860
+ }
861
+ __name(withDefaultScopes, "withDefaultScopes");
862
+ async function login(complianceConfig, props) {
863
+ return oauthFlow.login(withDefaultScopes(complianceConfig, props));
864
+ }
865
+ __name(login, "login");
866
+ async function logout(profile) {
867
+ return oauthFlow.logout(profile);
868
+ }
869
+ __name(logout, "logout");
870
+ async function loginOrRefreshIfRequired(complianceConfig, props) {
871
+ if (oauthFlow.getActiveTemporaryAccount()) {
872
+ return { loggedIn: true };
873
+ }
874
+ return oauthFlow.loginOrRefreshIfRequired(
875
+ withDefaultScopes(complianceConfig, props)
876
+ );
877
+ }
878
+ __name(loginOrRefreshIfRequired, "loginOrRefreshIfRequired");
879
+ async function getOAuthTokenFromLocalState() {
880
+ return oauthFlow.getOAuthTokenFromLocalState();
881
+ }
882
+ __name(getOAuthTokenFromLocalState, "getOAuthTokenFromLocalState");
883
+ function getScopes() {
884
+ return oauthFlow.getScopes();
885
+ }
886
+ __name(getScopes, "getScopes");
887
+ function readAuthCredentials() {
888
+ return credentialStorage.storageFactory(getActiveProfile()).read();
889
+ }
890
+ __name(readAuthCredentials, "readAuthCredentials");
891
+ function writeAuthCredentials(config) {
892
+ credentialStorage.storageFactory(getActiveProfile()).write(config);
893
+ }
894
+ __name(writeAuthCredentials, "writeAuthCredentials");
895
+ function getAccountCacheFileName() {
896
+ const profile = oauthFlow.getActiveProfile();
897
+ if (profile === "default") {
898
+ return `${descriptor.accountCachePrefix}.json`;
899
+ }
900
+ return `${descriptor.accountCachePrefix}-${profile}.json`;
901
+ }
902
+ __name(getAccountCacheFileName, "getAccountCacheFileName");
903
+ function saveAccountToCache(account) {
904
+ configCache.saveToConfigCache(
905
+ getAccountCacheFileName(),
906
+ { account }
907
+ );
908
+ }
909
+ __name(saveAccountToCache, "saveAccountToCache");
910
+ function getAccountFromCache() {
911
+ return configCache.getConfigCache(
912
+ getAccountCacheFileName()
913
+ ).account;
914
+ }
915
+ __name(getAccountFromCache, "getAccountFromCache");
916
+ async function fetchAccountsPaged(complianceConfig, resource) {
917
+ const result = await loginOrRefreshIfRequired(complianceConfig);
918
+ if (!result.loggedIn) {
919
+ throw new UserError(
920
+ `Not logged in. ${NOT_LOGGED_IN_ERROR_BODIES[result.reason]}${NOT_LOGGED_IN_WHOAMI_TIP}`,
921
+ { telemetryMessage: "cfetch auth login required" }
922
+ );
923
+ }
924
+ const credentials = requireApiToken();
925
+ const results = [];
926
+ let getMoreResults = true;
927
+ let page = 1;
928
+ let queryParams;
929
+ while (getMoreResults) {
930
+ queryParams = new URLSearchParams(queryParams);
931
+ queryParams.set("page", String(page));
932
+ const { response: json, status } = await fetchInternalBase(
933
+ complianceConfig,
934
+ resource,
935
+ {},
936
+ ctx.userAgent,
937
+ logger,
938
+ queryParams,
939
+ void 0,
940
+ credentials
941
+ );
942
+ if (json.success) {
943
+ results.push(...json.result);
944
+ if (hasMorePages(json.result_info)) {
945
+ page = page + 1;
946
+ } else {
947
+ getMoreResults = false;
948
+ }
949
+ } else {
950
+ throwFetchError(resource, json, status);
951
+ }
952
+ }
953
+ return results;
954
+ }
955
+ __name(fetchAccountsPaged, "fetchAccountsPaged");
956
+ async function fetchAllAccounts(complianceConfig, options = {}) {
957
+ const { throwOnEmpty = true } = options;
958
+ const [accountsRes, membershipsRes] = await Promise.allSettled([
959
+ fetchAccountsPaged(complianceConfig, `/accounts`),
960
+ fetchAccountsPaged(
961
+ complianceConfig,
962
+ `/memberships`
963
+ )
964
+ ]);
965
+ if (accountsRes.status === "rejected") {
966
+ throw accountsRes.reason;
967
+ }
968
+ if (membershipsRes.status === "rejected") {
969
+ if (isMembershipsInaccessible(membershipsRes.reason)) {
970
+ if (accountsRes.status === "fulfilled" && accountsRes.value.length > 0) {
971
+ return accountsRes.value;
972
+ }
973
+ const errCode = getErrorCode(membershipsRes.reason);
974
+ if (errCode === 9106) {
975
+ throw new UserError(
976
+ `Failed to automatically retrieve account IDs for the logged in user.
977
+ You may have incorrect permissions on your API token, or an environment variable such as CLOUDFLARE_API_TOKEN, CLOUDFLARE_API_KEY, or CLOUDFLARE_EMAIL may be set to an invalid value.
978
+ Check your environment and unset or correct any Cloudflare credential variables, or run \`${descriptor.commands.login}\` to re-authenticate.
979
+ You can also skip this account check by adding an \`account_id\` in your ${descriptor.getConfigFileLabel()} file, or by setting the value of CLOUDFLARE_ACCOUNT_ID`,
980
+ { telemetryMessage: "user account fetch permission denied" }
981
+ );
982
+ }
983
+ throw new UserError(
984
+ `Failed to automatically retrieve account IDs for the logged in user.
985
+ You may have incorrect permissions on your API token, or your authentication may have expired. Try running \`${descriptor.commands.login}\` to re-authenticate. You can also skip this account check by adding an \`account_id\` in your ${descriptor.getConfigFileLabel()} file, or by setting the value of CLOUDFLARE_ACCOUNT_ID`,
986
+ { telemetryMessage: "user account fetch permission denied" }
987
+ );
988
+ } else {
989
+ throw membershipsRes.reason;
990
+ }
991
+ }
992
+ const membershipIds = new Set(
993
+ membershipsRes.value.map((m) => m.account.id)
994
+ );
995
+ const usableAccounts = accountsRes.value.filter(
996
+ (a) => membershipIds.has(a.id)
997
+ );
998
+ if (usableAccounts.length === 0 && throwOnEmpty) {
999
+ throw new UserError(
1000
+ `Failed to automatically retrieve account IDs for the logged in user.
1001
+ In a non-interactive environment, it is mandatory to specify an account ID, either by assigning its value to CLOUDFLARE_ACCOUNT_ID, or as \`account_id\` in your ${descriptor.getConfigFileLabel()} file.
1002
+ Alternatively, try running \`${descriptor.commands.login}\` to re-authenticate.`,
1003
+ { telemetryMessage: "user account fetch empty" }
1004
+ );
1005
+ }
1006
+ return usableAccounts;
1007
+ }
1008
+ __name(fetchAllAccounts, "fetchAllAccounts");
1009
+ function getActiveAccountId(config) {
1010
+ const temporaryAccount = oauthFlow.getActiveTemporaryAccount();
1011
+ if (temporaryAccount) {
1012
+ return temporaryAccount.account.id;
1013
+ }
1014
+ if (config.account_id) {
1015
+ return config.account_id;
1016
+ }
1017
+ const envAccountId = getCloudflareAccountIdFromEnv();
1018
+ if (envAccountId) {
1019
+ return envAccountId;
1020
+ }
1021
+ return getAccountFromCache()?.id;
1022
+ }
1023
+ __name(getActiveAccountId, "getActiveAccountId");
1024
+ async function getOrSelectAccountId(config) {
1025
+ const activeAccountId = getActiveAccountId(config);
1026
+ if (activeAccountId) {
1027
+ return activeAccountId;
1028
+ }
1029
+ const accounts = await fetchAllAccounts(config);
1030
+ if (accounts.length === 1) {
1031
+ saveAccountToCache({ id: accounts[0].id, name: accounts[0].name });
1032
+ return accounts[0].id;
1033
+ }
1034
+ try {
1035
+ const accountID = await ctx.select("Select an account", {
1036
+ choices: accounts.map((account2) => ({
1037
+ title: account2.name,
1038
+ value: account2.id
1039
+ }))
1040
+ });
1041
+ const account = accounts.find((a) => a.id === accountID);
1042
+ if (!account) {
1043
+ throw new Error("Selected account not found in accounts list");
1044
+ }
1045
+ saveAccountToCache({ id: account.id, name: account.name });
1046
+ return accountID;
1047
+ } catch (e) {
1048
+ if (ctx.isNoDefaultValueProvidedError(e)) {
1049
+ const redactAccountName = isCI();
1050
+ throw new UserError(
1051
+ `More than one account available but unable to select one in non-interactive mode.
1052
+ Please set the appropriate \`account_id\` in your ${descriptor.getConfigFileLabel()} file or assign it to the \`CLOUDFLARE_ACCOUNT_ID\` environment variable.
1053
+ Available accounts are (\`<name>\`: \`<account_id>\`):
1054
+ ${accounts.map(
1055
+ (account) => ` \`${redactAccountName ? "(redacted)" : account.name}\`: \`${account.id}\``
1056
+ ).join("\n")}`,
1057
+ { telemetryMessage: "user account selection unavailable" }
1058
+ );
1059
+ }
1060
+ throw e;
1061
+ }
1062
+ }
1063
+ __name(getOrSelectAccountId, "getOrSelectAccountId");
1064
+ async function requireAuth(config) {
1065
+ if (oauthFlow.isTemporaryAllowed()) {
1066
+ if (getCloudflareComplianceRegion(config) !== "public") {
1067
+ throw new UserError(
1068
+ "Temporary accounts aren't available when the compliance region is not set to public.",
1069
+ {
1070
+ telemetryMessage: "user temporary account unavailable in compliance region"
1071
+ }
1072
+ );
1073
+ }
1074
+ if (getAPIToken()) {
1075
+ throw new UserError(
1076
+ "You're already authenticated with Cloudflare, so `--temporary` can't be used. Temporary preview accounts are only for unauthenticated use. Either remove `--temporary` to use your existing account, or log out (and unset CLOUDFLARE_API_TOKEN) first.",
1077
+ {
1078
+ telemetryMessage: "user temporary account already authenticated"
1079
+ }
1080
+ );
1081
+ }
1082
+ const { account: temporaryPreviewAccount, cached } = await oauthFlow.activateTemporaryAccount();
1083
+ logTemporaryPreviewAccount(logger, temporaryPreviewAccount, cached);
1084
+ return temporaryPreviewAccount.account.id;
1085
+ }
1086
+ const result = await loginOrRefreshIfRequired(config);
1087
+ if (!result.loggedIn) {
1088
+ if (result.reason === "no-credentials-non-interactive" || result.reason === "token-expired-non-interactive") {
1089
+ throw new UserError(
1090
+ `In a non-interactive environment, it's necessary to set a CLOUDFLARE_API_TOKEN environment variable for ${cliName} to work. Please go to https://developers.cloudflare.com/fundamentals/api/get-started/create-token/ for instructions on how to create an api token, and assign its value to CLOUDFLARE_API_TOKEN.`,
1091
+ { telemetryMessage: "user auth missing api token non interactive" }
1092
+ );
1093
+ } else {
1094
+ throw new UserError("Did not login, quitting...", {
1095
+ telemetryMessage: "user login cancelled"
1096
+ });
1097
+ }
1098
+ }
1099
+ const accountId = await getOrSelectAccountId(config);
1100
+ if (!accountId) {
1101
+ throw new UserError("No account id found, quitting...", {
1102
+ telemetryMessage: "user auth missing account id"
1103
+ });
1104
+ }
1105
+ return accountId;
1106
+ }
1107
+ __name(requireAuth, "requireAuth");
1108
+ return {
1109
+ setProfile,
1110
+ getActiveProfile,
1111
+ getCredentialStore,
1112
+ setTemporaryAllowed,
1113
+ getAPIToken,
1114
+ requireApiToken,
1115
+ login,
1116
+ logout,
1117
+ loginOrRefreshIfRequired,
1118
+ getOAuthTokenFromLocalState,
1119
+ getScopes,
1120
+ readAuthCredentials,
1121
+ writeAuthCredentials,
1122
+ getActiveAccountId,
1123
+ getOrSelectAccountId,
1124
+ getAccountFromCache,
1125
+ fetchAllAccounts,
1126
+ requireAuth
1127
+ };
1128
+ }
1129
+ __name(createCloudflareAuth, "createCloudflareAuth");
1130
+ var DIRECTORY_BINDINGS_FILE = "profiles/directory-bindings.json";
1131
+ var ENCRYPTED_PROFILE_CONFIG_EXTENSION = ".enc";
1132
+ function createCloudflareProfileStore(ctx) {
1133
+ const { logger, getConfigPath, keyringServiceName, format } = ctx;
1134
+ const plaintextExtension = `.${format}`;
1135
+ function plaintextPath(profile) {
1136
+ return getAuthConfigFilePath(getConfigPath(), profile, format);
1137
+ }
1138
+ __name(plaintextPath, "plaintextPath");
1139
+ function encryptedPath(profile) {
1140
+ return getEncryptedAuthConfigFilePath(getConfigPath(), profile);
1141
+ }
1142
+ __name(encryptedPath, "encryptedPath");
1143
+ function getProfileConfigDirectory() {
1144
+ return path3.dirname(plaintextPath("default"));
1145
+ }
1146
+ __name(getProfileConfigDirectory, "getProfileConfigDirectory");
1147
+ const configs = {
1148
+ exists(profile) {
1149
+ return existsSync(plaintextPath(profile)) || existsSync(encryptedPath(profile));
1150
+ },
1151
+ list() {
1152
+ const profilesDir = getProfileConfigDirectory();
1153
+ if (!existsSync(profilesDir)) {
1154
+ return [];
1155
+ }
1156
+ const names = /* @__PURE__ */ new Set();
1157
+ for (const file of readdirSync(profilesDir)) {
1158
+ if (file.endsWith(plaintextExtension)) {
1159
+ names.add(file.slice(0, -plaintextExtension.length));
1160
+ } else if (file.endsWith(ENCRYPTED_PROFILE_CONFIG_EXTENSION)) {
1161
+ names.add(file.slice(0, -ENCRYPTED_PROFILE_CONFIG_EXTENSION.length));
1162
+ }
1163
+ }
1164
+ return [...names];
1165
+ },
1166
+ delete(profile) {
1167
+ const { backendAvailable, encryptedFileExisted } = scrubEncryptedCredentials({
1168
+ serviceName: keyringServiceName,
1169
+ configPath: getConfigPath(),
1170
+ profile,
1171
+ format
1172
+ });
1173
+ createFileStorage(
1174
+ format,
1175
+ () => plaintextPath(profile)
1176
+ ).clear();
1177
+ if (encryptedFileExisted && !backendAvailable) {
1178
+ logger.warn(
1179
+ `Removed the credential files for profile "${profile}", but the keyring backend was not reachable on this host so its keyring entry could not be cleared. Clear it manually if it persists.`
1180
+ );
1181
+ }
1182
+ }
1183
+ };
1184
+ function getDirectoryBindingsPath() {
1185
+ return path3.join(getConfigPath(), DIRECTORY_BINDINGS_FILE);
1186
+ }
1187
+ __name(getDirectoryBindingsPath, "getDirectoryBindingsPath");
1188
+ const bindings = {
1189
+ read() {
1190
+ try {
1191
+ const raw = readFileSync$1(getDirectoryBindingsPath(), "utf-8");
1192
+ return JSON.parse(raw);
1193
+ } catch {
1194
+ return {};
1195
+ }
1196
+ },
1197
+ write(dirBindings) {
1198
+ const bindingsPath = getDirectoryBindingsPath();
1199
+ mkdirSync(path3.dirname(bindingsPath), { recursive: true });
1200
+ writeFileSync(
1201
+ bindingsPath,
1202
+ JSON.stringify(dirBindings, null, " "),
1203
+ "utf-8"
1204
+ );
1205
+ }
1206
+ };
1207
+ return createProfileStore({ configs, bindings });
1208
+ }
1209
+ __name(createCloudflareProfileStore, "createCloudflareProfileStore");
1210
+ function createKeyringPreference(deps) {
1211
+ const {
1212
+ loginCommand,
1213
+ createProfileCommand,
1214
+ keyringServiceName,
1215
+ getConfigPath,
1216
+ format,
1217
+ preferences
1218
+ } = deps;
1219
+ const { readUserPreferences, updateUserPreferences } = preferences;
1220
+ function describeProfile(profile) {
1221
+ return profile ?? "default";
1222
+ }
1223
+ __name(describeProfile, "describeProfile");
1224
+ function listEncryptedProfiles(logger) {
1225
+ const encrypted = [];
1226
+ if (existsSync(getEncryptedAuthConfigFilePath(getConfigPath()))) {
1227
+ encrypted.push(void 0);
1228
+ }
1229
+ const profileStore = createCloudflareProfileStore({
1230
+ logger,
1231
+ getConfigPath,
1232
+ keyringServiceName,
1233
+ format
1234
+ });
1235
+ for (const name of profileStore.configs.list()) {
1236
+ try {
1237
+ validateProfileName(name);
1238
+ } catch {
1239
+ continue;
1240
+ }
1241
+ if (existsSync(getEncryptedAuthConfigFilePath(getConfigPath(), name))) {
1242
+ encrypted.push(name);
1243
+ }
1244
+ }
1245
+ return encrypted;
1246
+ }
1247
+ __name(listEncryptedProfiles, "listEncryptedProfiles");
1248
+ function scrubAllEncryptedProfiles(logger) {
1249
+ const encryptedProfiles = listEncryptedProfiles(logger);
1250
+ if (encryptedProfiles.length === 0) {
1251
+ return;
1252
+ }
1253
+ const cleared = [];
1254
+ const unreachable = [];
1255
+ for (const profile of encryptedProfiles) {
1256
+ try {
1257
+ const { backendAvailable } = scrubEncryptedCredentials({
1258
+ serviceName: keyringServiceName,
1259
+ configPath: getConfigPath(),
1260
+ profile,
1261
+ format
1262
+ });
1263
+ cleared.push(describeProfile(profile));
1264
+ if (!backendAvailable) {
1265
+ unreachable.push(describeProfile(profile));
1266
+ }
1267
+ } catch (e) {
1268
+ logger.warn(
1269
+ `Failed to remove encrypted credentials for profile "${describeProfile(profile)}": ${e instanceof Error ? e.message : String(e)}. You may need to clear them manually.`
1270
+ );
1271
+ }
1272
+ }
1273
+ if (cleared.length > 0) {
1274
+ const reauthenticate = createProfileCommand ? `Re-authenticate with \`${loginCommand}\` (default profile) or \`${createProfileCommand} <name>\` (named profiles).` : `Re-authenticate with \`${loginCommand}\`.`;
1275
+ logger.log(
1276
+ `Removed encrypted credentials for ${cleared.map((p) => `"${p}"`).join(", ")}. ${reauthenticate}`
1277
+ );
1278
+ }
1279
+ if (unreachable.length > 0) {
1280
+ logger.warn(
1281
+ `The keyring backend was not reachable on this host, so the keyring entry for ${unreachable.map((p) => `"${p}"`).join(", ")} could not be cleared. Clear it manually if it persists.`
1282
+ );
1283
+ }
1284
+ }
1285
+ __name(scrubAllEncryptedProfiles, "scrubAllEncryptedProfiles");
1286
+ function setKeyringPreference(enabled, ctx) {
1287
+ const { logger, getCredentialStore } = ctx;
1288
+ const previouslyEnabled = readUserPreferences().keyring_enabled === true;
1289
+ const envOverride = getCloudflareAuthUseKeyringFromEnv();
1290
+ if (envOverride !== void 0 && envOverride !== enabled) {
1291
+ logger.warn(
1292
+ `CLOUDFLARE_AUTH_USE_KEYRING=${envOverride} overrides ${enabled ? "enabling" : "disabling"} keyring storage for this command.`
1293
+ );
1294
+ }
1295
+ if (!enabled && envOverride !== true) {
1296
+ scrubAllEncryptedProfiles(logger);
1297
+ }
1298
+ updateUserPreferences({ keyring_enabled: enabled });
1299
+ if (enabled && envOverride !== false) {
1300
+ try {
1301
+ const store = getCredentialStore();
1302
+ if (store.kind !== "encrypted-file") {
1303
+ updateUserPreferences({ keyring_enabled: previouslyEnabled });
1304
+ logger.warn(
1305
+ "Keyring storage isn't available on this host (see warning above), so it was not enabled. Try again once the keyring backend is reachable."
1306
+ );
1307
+ }
1308
+ } catch (e) {
1309
+ updateUserPreferences({ keyring_enabled: previouslyEnabled });
1310
+ throw e;
1311
+ }
1312
+ }
1313
+ return { enabled: readUserPreferences().keyring_enabled === true };
1314
+ }
1315
+ __name(setKeyringPreference, "setKeyringPreference");
1316
+ return { setKeyringPreference };
1317
+ }
1318
+ __name(createKeyringPreference, "createKeyringPreference");
1319
+
1320
+ // src/core/auth-config-file.ts
1321
+ function createAuthConfigFileHelpers(deps) {
1322
+ const { getConfigPath, format } = deps;
1323
+ function getAuthConfigFilePath2(profile) {
1324
+ return getAuthConfigFilePath(getConfigPath(), profile, format);
1325
+ }
1326
+ __name(getAuthConfigFilePath2, "getAuthConfigFilePath");
1327
+ function getEncryptedAuthConfigFilePath2(profile) {
1328
+ return getEncryptedAuthConfigFilePath(getConfigPath(), profile);
1329
+ }
1330
+ __name(getEncryptedAuthConfigFilePath2, "getEncryptedAuthConfigFilePath");
1331
+ function defaultAuthConfigStorage(profile) {
1332
+ return createFileStorage(
1333
+ format,
1334
+ () => getAuthConfigFilePath2(profile)
1335
+ );
1336
+ }
1337
+ __name(defaultAuthConfigStorage, "defaultAuthConfigStorage");
1338
+ function writeAuthConfigFile(config, profile) {
1339
+ defaultAuthConfigStorage(profile).write(config);
1340
+ }
1341
+ __name(writeAuthConfigFile, "writeAuthConfigFile");
1342
+ function readAuthConfigFile(profile) {
1343
+ return defaultAuthConfigStorage(profile).read();
1344
+ }
1345
+ __name(readAuthConfigFile, "readAuthConfigFile");
1346
+ return {
1347
+ getAuthConfigFilePath: getAuthConfigFilePath2,
1348
+ getEncryptedAuthConfigFilePath: getEncryptedAuthConfigFilePath2,
1349
+ defaultAuthConfigStorage,
1350
+ readAuthConfigFile,
1351
+ writeAuthConfigFile
1352
+ };
1353
+ }
1354
+ __name(createAuthConfigFileHelpers, "createAuthConfigFileHelpers");
1355
+
1356
+ export { createAuthConfigFileHelpers, createCloudflareAuth, createCloudflareProfileStore, createFileStorage, createKeyringPreference, createPreferences };