@cloudflare/workers-auth 0.4.2 → 0.5.1

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 CHANGED
@@ -1,3666 +1,2 @@
1
- import { __name } from './chunk-O6YSETKJ.mjs';
2
- import { getEnvironmentVariableFactory, getCloudflareApiEnvironmentFromEnv, getBooleanEnvironmentVariableFactory, UserError, parseTOML, readFileSync, getCloudflareApiBaseUrl, COMPLIANCE_REGION_CONFIG_PUBLIC, FatalError, getCloudflareComplianceRegion } from '@cloudflare/workers-utils';
3
- import { spawnSync } from 'node:child_process';
4
- import { fetch } from 'undici';
5
- import assert2 from 'node:assert';
6
- import http from 'node:http';
7
- import url from 'node:url';
8
- import { webcrypto, createHash, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
9
- import { TextEncoder } from 'node:util';
10
- import path4 from 'node:path';
11
- import { existsSync, mkdirSync, writeFileSync, chmodSync, rmSync } from 'node:fs';
12
- import { createRequire } from 'node:module';
13
-
14
- // src/state.ts
15
- var hasWarnedAboutDeprecatedV1ApiToken = false;
16
- function readStoredAuthState(options) {
17
- const { configOverride, warningLogger, storage } = options;
18
- const parsed = configOverride ?? storage.read() ?? {};
19
- const { oauth_token, refresh_token, expiration_time, scopes, api_token } = parsed;
20
- if (oauth_token) {
21
- return {
22
- accessToken: {
23
- value: oauth_token,
24
- // If there is no `expiration_time` field then set it to an old date, to cause it to expire immediately.
25
- expiry: expiration_time ?? "2000-01-01:00:00:00+00:00"
26
- },
27
- refreshToken: { value: refresh_token ?? "" },
28
- scopes
29
- };
30
- }
31
- if (api_token) {
32
- if (!hasWarnedAboutDeprecatedV1ApiToken && warningLogger) {
33
- hasWarnedAboutDeprecatedV1ApiToken = true;
34
- warningLogger.warn(
35
- `It looks like you have used Wrangler v1's \`config\` command to login with an API token
36
- from ${configOverride === void 0 ? storage.path() : "in-memory config"}.
37
- This is no longer supported in the current version of Wrangler.
38
- If you wish to authenticate via an API token then please set the \`CLOUDFLARE_API_TOKEN\` environment variable.`
39
- );
40
- }
41
- return { deprecatedApiToken: api_token };
42
- }
43
- return {};
44
- }
45
- __name(readStoredAuthState, "readStoredAuthState");
46
-
47
- // src/credentials.ts
48
- var getCloudflareAPITokenFromEnv = getEnvironmentVariableFactory({
49
- variableName: "CLOUDFLARE_API_TOKEN",
50
- deprecatedName: "CF_API_TOKEN"
51
- });
52
- var getCloudflareGlobalAuthKeyFromEnv = getEnvironmentVariableFactory({
53
- variableName: "CLOUDFLARE_API_KEY",
54
- deprecatedName: "CF_API_KEY"
55
- });
56
- var getCloudflareGlobalAuthEmailFromEnv = getEnvironmentVariableFactory({
57
- variableName: "CLOUDFLARE_EMAIL",
58
- deprecatedName: "CF_EMAIL"
59
- });
60
- function getAuthFromEnv(options) {
61
- const allowGlobalAuthKey = options?.allowGlobalAuthKey ?? true;
62
- if (allowGlobalAuthKey) {
63
- const globalApiKey = getCloudflareGlobalAuthKeyFromEnv();
64
- const globalApiEmail = getCloudflareGlobalAuthEmailFromEnv();
65
- if (globalApiKey && globalApiEmail) {
66
- return { authKey: globalApiKey, authEmail: globalApiEmail };
67
- }
68
- }
69
- const apiToken = getCloudflareAPITokenFromEnv();
70
- if (apiToken) {
71
- return { apiToken };
72
- }
73
- return void 0;
74
- }
75
- __name(getAuthFromEnv, "getAuthFromEnv");
76
- function getAPIToken(options) {
77
- const envAuth = getAuthFromEnv(options);
78
- if (envAuth) {
79
- return envAuth;
80
- }
81
- const stored = readStoredAuthState({
82
- storage: options.storage,
83
- warningLogger: options.warningLogger
84
- });
85
- if (stored.deprecatedApiToken) {
86
- return { apiToken: stored.deprecatedApiToken };
87
- }
88
- if (stored.accessToken?.value) {
89
- return { apiToken: stored.accessToken.value };
90
- }
91
- return void 0;
92
- }
93
- __name(getAPIToken, "getAPIToken");
94
- function requireApiToken(options) {
95
- const credentials = getAPIToken(options);
96
- if (!credentials) {
97
- throw new UserError("No API token found.", {
98
- telemetryMessage: "user auth missing api token"
99
- });
100
- }
101
- return credentials;
102
- }
103
- __name(requireApiToken, "requireApiToken");
104
- var getAuthDomainFromEnv = getEnvironmentVariableFactory({
105
- variableName: "WRANGLER_AUTH_DOMAIN",
106
- defaultValue: /* @__PURE__ */ __name(() => getCloudflareApiEnvironmentFromEnv() === "staging" ? "dash.staging.cloudflare.com" : "dash.cloudflare.com", "defaultValue")
107
- });
108
- var getAuthUrlFromEnv = getEnvironmentVariableFactory({
109
- variableName: "WRANGLER_AUTH_URL",
110
- defaultValue: /* @__PURE__ */ __name(() => `https://${getAuthDomainFromEnv()}/oauth2/auth`, "defaultValue")
111
- });
112
- var getTokenUrlFromEnv = getEnvironmentVariableFactory({
113
- variableName: "WRANGLER_TOKEN_URL",
114
- defaultValue: /* @__PURE__ */ __name(() => `https://${getAuthDomainFromEnv()}/oauth2/token`, "defaultValue")
115
- });
116
- var getRevokeUrlFromEnv = getEnvironmentVariableFactory({
117
- variableName: "WRANGLER_REVOKE_URL",
118
- defaultValue: /* @__PURE__ */ __name(() => `https://${getAuthDomainFromEnv()}/oauth2/revoke`, "defaultValue")
119
- });
120
- var getAccessClientIdFromEnv = getEnvironmentVariableFactory({
121
- variableName: "CLOUDFLARE_ACCESS_CLIENT_ID"
122
- });
123
- var getAccessClientSecretFromEnv = getEnvironmentVariableFactory({
124
- variableName: "CLOUDFLARE_ACCESS_CLIENT_SECRET"
125
- });
126
- var getCfAuthorizationTokenFromEnv = getEnvironmentVariableFactory({
127
- variableName: "WRANGLER_CF_AUTHORIZATION_TOKEN"
128
- });
129
- var getCloudflareAuthUseKeyringFromEnv = getBooleanEnvironmentVariableFactory({
130
- variableName: "CLOUDFLARE_AUTH_USE_KEYRING"
131
- });
132
-
133
- // src/access.ts
134
- var headersCache = {};
135
- var usesAccessCache = /* @__PURE__ */ new Map();
136
- function clearAccessCaches() {
137
- for (const key of Object.keys(headersCache)) {
138
- delete headersCache[key];
139
- }
140
- usesAccessCache.clear();
141
- }
142
- __name(clearAccessCaches, "clearAccessCaches");
143
- async function domainUsesAccess(domain, logger) {
144
- logger.debug("Checking if domain has Access enabled:", domain);
145
- if (usesAccessCache.has(domain)) {
146
- logger.debug(
147
- "Using cached Access switch for:",
148
- domain,
149
- usesAccessCache.get(domain)
150
- );
151
- return usesAccessCache.get(domain) ?? false;
152
- }
153
- logger.debug("Access switch not cached for:", domain);
154
- try {
155
- const controller = new AbortController();
156
- const cancel = setTimeout(() => {
157
- controller.abort();
158
- }, 1e3);
159
- const output = await fetch(`https://${domain}`, {
160
- redirect: "manual",
161
- signal: controller.signal
162
- });
163
- clearTimeout(cancel);
164
- const usesAccess = !!(output.status === 302 && output.headers.get("location")?.includes("cloudflareaccess.com"));
165
- logger.debug("Caching access switch for:", domain);
166
- usesAccessCache.set(domain, usesAccess);
167
- return usesAccess;
168
- } catch {
169
- usesAccessCache.set(domain, false);
170
- return false;
171
- }
172
- }
173
- __name(domainUsesAccess, "domainUsesAccess");
174
- async function getAccessHeaders(domain, options) {
175
- const logger = options.logger;
176
- const isNonInteractiveOrCI = options.isNonInteractiveOrCI;
177
- const clientId = getAccessClientIdFromEnv();
178
- const clientSecret = getAccessClientSecretFromEnv();
179
- if (clientId && clientSecret) {
180
- logger.debug("Using Access Service Token headers for domain:", domain);
181
- const headers = {
182
- "CF-Access-Client-Id": clientId,
183
- "CF-Access-Client-Secret": clientSecret
184
- };
185
- headersCache[domain] = headers;
186
- return headers;
187
- }
188
- if (clientId !== void 0 || clientSecret !== void 0) {
189
- logger.warn(
190
- `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.`
191
- );
192
- }
193
- if (!await domainUsesAccess(domain, logger)) {
194
- return {};
195
- }
196
- logger.debug("Getting Access headers for domain:", domain);
197
- if (headersCache[domain]) {
198
- logger.debug("Using cached Access headers for domain:", domain);
199
- return headersCache[domain];
200
- }
201
- if (isNonInteractiveOrCI()) {
202
- throw new UserError(
203
- `The domain "${domain}" is behind Cloudflare Access, but no Access Service Token credentials were found and the current environment is non-interactive.
204
- Set the CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET environment variables to authenticate with an Access Service Token.
205
- See https://developers.cloudflare.com/cloudflare-one/access-controls/service-credentials/service-tokens/`,
206
- {
207
- telemetryMessage: "user access missing service token non interactive"
208
- }
209
- );
210
- }
211
- logger.debug("Spawning cloudflared to get Access token for domain:");
212
- const output = spawnSync("cloudflared", ["access", "login", domain]);
213
- if (output.error) {
214
- throw new UserError(
215
- "To use Wrangler with Cloudflare Access, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation",
216
- { telemetryMessage: "user access missing cloudflared" }
217
- );
218
- }
219
- const stringOutput = output.stdout.toString();
220
- logger.debug("cloudflared output:", stringOutput);
221
- const matches = stringOutput.match(/fetched your token:\n\n(.*)/m);
222
- if (matches && matches.length >= 2) {
223
- const headers = { Cookie: `CF_Authorization=${matches[1]}` };
224
- headersCache[domain] = headers;
225
- logger.debug("Caching Access headers for domain:", domain);
226
- return headers;
227
- }
228
- throw new Error("Failed to authenticate with Cloudflare Access");
229
- }
230
- __name(getAccessHeaders, "getAccessHeaders");
231
- async function getCloudflareAccessHeaders(options) {
232
- const cfAuthToken = getCfAuthorizationTokenFromEnv();
233
- if (cfAuthToken !== void 0) {
234
- options.logger.debug(
235
- "Using WRANGLER_CF_AUTHORIZATION_TOKEN from environment"
236
- );
237
- return { Cookie: `CF_Authorization=${cfAuthToken}` };
238
- }
239
- return getAccessHeaders(getAuthDomainFromEnv(), options);
240
- }
241
- __name(getCloudflareAccessHeaders, "getCloudflareAccessHeaders");
242
-
243
- // ../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/esm/index.js
244
- function dedent(templ) {
245
- var values = [];
246
- for (var _i = 1; _i < arguments.length; _i++) {
247
- values[_i - 1] = arguments[_i];
248
- }
249
- var strings = Array.from(typeof templ === "string" ? [templ] : templ);
250
- strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
251
- var indentLengths = strings.reduce(function(arr, str) {
252
- var matches = str.match(/\n([\t ]+|(?!\s).)/g);
253
- if (matches) {
254
- return arr.concat(matches.map(function(match) {
255
- var _a, _b;
256
- return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
257
- }));
258
- }
259
- return arr;
260
- }, []);
261
- if (indentLengths.length) {
262
- var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
263
- strings = strings.map(function(str) {
264
- return str.replace(pattern_1, "\n");
265
- });
266
- }
267
- strings[0] = strings[0].replace(/^\r?\n/, "");
268
- var string = strings[0];
269
- values.forEach(function(value, i) {
270
- var endentations = string.match(/(?:^|\n)( *)$/);
271
- var endentation = endentations ? endentations[1] : "";
272
- var indentedValue = value;
273
- if (typeof value === "string" && value.includes("\n")) {
274
- indentedValue = String(value).split("\n").map(function(str, i2) {
275
- return i2 === 0 ? str : "" + endentation + str;
276
- }).join("\n");
277
- }
278
- string += indentedValue + strings[i + 1];
279
- });
280
- return string;
281
- }
282
- __name(dedent, "dedent");
283
- var esm_default = dedent;
284
- var ErrorOAuth2 = class extends UserError {
285
- static {
286
- __name(this, "ErrorOAuth2");
287
- }
288
- /** The OAuth `error` code returned by the provider (e.g. `invalid_scope`). */
289
- code;
290
- /** The OAuth `error_description` returned by the provider, if any. */
291
- description;
292
- /** The OAuth `error_uri` returned by the provider, if any. */
293
- uri;
294
- toString() {
295
- return "ErrorOAuth2";
296
- }
297
- };
298
- var ErrorUnknown = class extends ErrorOAuth2 {
299
- static {
300
- __name(this, "ErrorUnknown");
301
- }
302
- toString() {
303
- return "ErrorUnknown";
304
- }
305
- };
306
- var ErrorNoAuthCode = class extends ErrorOAuth2 {
307
- static {
308
- __name(this, "ErrorNoAuthCode");
309
- }
310
- toString() {
311
- return "ErrorNoAuthCode";
312
- }
313
- };
314
- var ErrorInvalidReturnedStateParam = class extends ErrorOAuth2 {
315
- static {
316
- __name(this, "ErrorInvalidReturnedStateParam");
317
- }
318
- toString() {
319
- return "ErrorInvalidReturnedStateParam";
320
- }
321
- };
322
- var ErrorInvalidJson = class extends ErrorOAuth2 {
323
- static {
324
- __name(this, "ErrorInvalidJson");
325
- }
326
- toString() {
327
- return "ErrorInvalidJson";
328
- }
329
- };
330
- var ErrorInvalidScope = class extends ErrorOAuth2 {
331
- static {
332
- __name(this, "ErrorInvalidScope");
333
- }
334
- toString() {
335
- return "ErrorInvalidScope";
336
- }
337
- };
338
- var ErrorInvalidRequest = class extends ErrorOAuth2 {
339
- static {
340
- __name(this, "ErrorInvalidRequest");
341
- }
342
- toString() {
343
- return "ErrorInvalidRequest";
344
- }
345
- };
346
- var ErrorInvalidToken = class extends ErrorOAuth2 {
347
- static {
348
- __name(this, "ErrorInvalidToken");
349
- }
350
- toString() {
351
- return "ErrorInvalidToken";
352
- }
353
- };
354
- var ErrorAuthenticationGrant = class extends ErrorOAuth2 {
355
- static {
356
- __name(this, "ErrorAuthenticationGrant");
357
- }
358
- toString() {
359
- return "ErrorAuthenticationGrant";
360
- }
361
- };
362
- var ErrorUnauthorizedClient = class extends ErrorAuthenticationGrant {
363
- static {
364
- __name(this, "ErrorUnauthorizedClient");
365
- }
366
- toString() {
367
- return "ErrorUnauthorizedClient";
368
- }
369
- };
370
- var ErrorAccessDenied = class extends ErrorAuthenticationGrant {
371
- static {
372
- __name(this, "ErrorAccessDenied");
373
- }
374
- toString() {
375
- return "ErrorAccessDenied";
376
- }
377
- };
378
- var ErrorUnsupportedResponseType = class extends ErrorAuthenticationGrant {
379
- static {
380
- __name(this, "ErrorUnsupportedResponseType");
381
- }
382
- toString() {
383
- return "ErrorUnsupportedResponseType";
384
- }
385
- };
386
- var ErrorServerError = class extends ErrorAuthenticationGrant {
387
- static {
388
- __name(this, "ErrorServerError");
389
- }
390
- toString() {
391
- return "ErrorServerError";
392
- }
393
- };
394
- var ErrorTemporarilyUnavailable = class extends ErrorAuthenticationGrant {
395
- static {
396
- __name(this, "ErrorTemporarilyUnavailable");
397
- }
398
- toString() {
399
- return "ErrorTemporarilyUnavailable";
400
- }
401
- };
402
- var ErrorAccessTokenResponse = class extends ErrorOAuth2 {
403
- static {
404
- __name(this, "ErrorAccessTokenResponse");
405
- }
406
- toString() {
407
- return "ErrorAccessTokenResponse";
408
- }
409
- };
410
- var ErrorInvalidClient = class extends ErrorAccessTokenResponse {
411
- static {
412
- __name(this, "ErrorInvalidClient");
413
- }
414
- toString() {
415
- return "ErrorInvalidClient";
416
- }
417
- };
418
- var ErrorInvalidGrant = class extends ErrorAccessTokenResponse {
419
- static {
420
- __name(this, "ErrorInvalidGrant");
421
- }
422
- toString() {
423
- return "ErrorInvalidGrant";
424
- }
425
- };
426
- var ErrorUnsupportedGrantType = class extends ErrorAccessTokenResponse {
427
- static {
428
- __name(this, "ErrorUnsupportedGrantType");
429
- }
430
- toString() {
431
- return "ErrorUnsupportedGrantType";
432
- }
433
- };
434
- function formatOAuthErrorMessage(code, description, uri) {
435
- let message = `OAuth error: ${code}`;
436
- if (description) {
437
- message += `
438
- ${description}`;
439
- }
440
- if (uri) {
441
- message += `
442
- See: ${uri}`;
443
- }
444
- return message;
445
- }
446
- __name(formatOAuthErrorMessage, "formatOAuthErrorMessage");
447
- function toErrorClass(rawError, description, uri) {
448
- const message = formatOAuthErrorMessage(rawError, description, uri);
449
- let error;
450
- switch (rawError) {
451
- case "invalid_request":
452
- error = new ErrorInvalidRequest(message, {
453
- telemetryMessage: "user oauth invalid request"
454
- });
455
- break;
456
- case "invalid_grant":
457
- error = new ErrorInvalidGrant(message, {
458
- telemetryMessage: "user oauth invalid grant"
459
- });
460
- break;
461
- case "unauthorized_client":
462
- error = new ErrorUnauthorizedClient(message, {
463
- telemetryMessage: "user oauth unauthorized client"
464
- });
465
- break;
466
- case "access_denied":
467
- error = new ErrorAccessDenied(message, {
468
- telemetryMessage: "user oauth access denied"
469
- });
470
- break;
471
- case "unsupported_response_type":
472
- error = new ErrorUnsupportedResponseType(message, {
473
- telemetryMessage: "user oauth unsupported response type"
474
- });
475
- break;
476
- case "invalid_scope":
477
- error = new ErrorInvalidScope(message, {
478
- telemetryMessage: "user oauth invalid scope"
479
- });
480
- break;
481
- case "server_error":
482
- error = new ErrorServerError(message, {
483
- telemetryMessage: "user oauth server error"
484
- });
485
- break;
486
- case "temporarily_unavailable":
487
- error = new ErrorTemporarilyUnavailable(message, {
488
- telemetryMessage: "user oauth temporarily unavailable"
489
- });
490
- break;
491
- case "invalid_client":
492
- error = new ErrorInvalidClient(message, {
493
- telemetryMessage: "user oauth invalid client"
494
- });
495
- break;
496
- case "unsupported_grant_type":
497
- error = new ErrorUnsupportedGrantType(message, {
498
- telemetryMessage: "user oauth unsupported grant type"
499
- });
500
- break;
501
- case "invalid_json":
502
- error = new ErrorInvalidJson(message, {
503
- telemetryMessage: "user oauth invalid json"
504
- });
505
- break;
506
- case "invalid_token":
507
- error = new ErrorInvalidToken(message, {
508
- telemetryMessage: "user oauth invalid token"
509
- });
510
- break;
511
- default:
512
- error = new ErrorUnknown(message, {
513
- telemetryMessage: "user oauth unknown error"
514
- });
515
- break;
516
- }
517
- error.code = rawError;
518
- error.description = description;
519
- error.uri = uri;
520
- return error;
521
- }
522
- __name(toErrorClass, "toErrorClass");
523
- var RECOMMENDED_CODE_VERIFIER_LENGTH = 96;
524
- var RECOMMENDED_STATE_LENGTH = 32;
525
- var PKCE_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
526
- function base64urlEncode(value) {
527
- let base64 = btoa(value);
528
- base64 = base64.replace(/\+/g, "-");
529
- base64 = base64.replace(/\//g, "_");
530
- base64 = base64.replace(/=/g, "");
531
- return base64;
532
- }
533
- __name(base64urlEncode, "base64urlEncode");
534
- async function generatePKCECodes() {
535
- const output = new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);
536
- webcrypto.getRandomValues(output);
537
- const codeVerifier = base64urlEncode(
538
- Array.from(output).map((num) => PKCE_CHARSET[num % PKCE_CHARSET.length]).join("")
539
- );
540
- const buffer = await webcrypto.subtle.digest(
541
- "SHA-256",
542
- new TextEncoder().encode(codeVerifier)
543
- );
544
- const hash = new Uint8Array(buffer);
545
- let binary = "";
546
- const hashLength = hash.byteLength;
547
- for (let i = 0; i < hashLength; i++) {
548
- binary += String.fromCharCode(hash[i]);
549
- }
550
- const codeChallenge = base64urlEncode(binary);
551
- return { codeChallenge, codeVerifier };
552
- }
553
- __name(generatePKCECodes, "generatePKCECodes");
554
-
555
- // src/token-exchange.ts
556
- function isReturningFromAuthServer(query, state, logger) {
557
- if (query.error) {
558
- const error = Array.isArray(query.error) ? query.error[0] : query.error;
559
- const description = Array.isArray(query.error_description) ? query.error_description[0] : query.error_description;
560
- const uri = Array.isArray(query.error_uri) ? query.error_uri[0] : query.error_uri;
561
- throw toErrorClass(error, description, uri);
562
- }
563
- const code = query.code;
564
- if (!code) {
565
- return false;
566
- }
567
- const stateQueryParam = query.state;
568
- if (stateQueryParam !== state.stateQueryParam) {
569
- logger.warn(
570
- "Received query string parameter doesn't match the one sent! Possible malicious activity somewhere."
571
- );
572
- throw new ErrorInvalidReturnedStateParam("", {
573
- telemetryMessage: "user oauth invalid returned state"
574
- });
575
- }
576
- assert2(!Array.isArray(code));
577
- state.authorizationCode = code;
578
- state.hasAuthCodeBeenExchangedForAccessToken = false;
579
- return true;
580
- }
581
- __name(isReturningFromAuthServer, "isReturningFromAuthServer");
582
- async function getAuthURL(scopes, clientId, redirectUri, state, generators) {
583
- const { codeChallenge, codeVerifier } = await generatePKCECodes();
584
- const stateQueryParam = generators.generateRandomState(
585
- RECOMMENDED_STATE_LENGTH
586
- );
587
- Object.assign(state, {
588
- codeChallenge,
589
- codeVerifier,
590
- stateQueryParam
591
- });
592
- return generators.generateAuthUrl({
593
- authUrl: getAuthUrlFromEnv(),
594
- clientId,
595
- scopes,
596
- stateQueryParam,
597
- codeChallenge,
598
- redirectUri
599
- });
600
- }
601
- __name(getAuthURL, "getAuthURL");
602
- async function exchangeRefreshTokenForAccessToken(logger, isNonInteractiveOrCI, clientId, storage) {
603
- const storedRefreshToken = readStoredAuthState({
604
- warningLogger: logger,
605
- storage
606
- }).refreshToken;
607
- if (!storedRefreshToken) {
608
- logger.warn("No refresh token is present.");
609
- }
610
- const params = new URLSearchParams({
611
- grant_type: "refresh_token",
612
- refresh_token: storedRefreshToken?.value ?? "",
613
- client_id: clientId
614
- });
615
- const response = await fetchAuthToken(params, logger, isNonInteractiveOrCI);
616
- if (response.status >= 400) {
617
- let tokenExchangeResErr = void 0;
618
- try {
619
- tokenExchangeResErr = await getJSONFromResponse(response, logger);
620
- } catch (e) {
621
- logger.error(e);
622
- }
623
- if (tokenExchangeResErr !== void 0) {
624
- throw typeof tokenExchangeResErr === "string" ? new Error(tokenExchangeResErr) : tokenExchangeResErr;
625
- } else {
626
- throw new ErrorUnknown(
627
- "Failed to parse Error from exchangeRefreshTokenForAccessToken",
628
- { telemetryMessage: "user oauth refresh token exchange parse error" }
629
- );
630
- }
631
- } else {
632
- try {
633
- const json = await getJSONFromResponse(
634
- response,
635
- logger
636
- );
637
- if ("error" in json) {
638
- throw json.error;
639
- }
640
- const { access_token, expires_in, refresh_token, scope } = json;
641
- const accessToken = {
642
- value: access_token,
643
- expiry: new Date(Date.now() + expires_in * 1e3).toISOString()
644
- };
645
- const scopes = scope ? scope.split(" ") : [];
646
- const accessContext = {
647
- token: accessToken,
648
- scopes,
649
- refreshToken: refresh_token ? { value: refresh_token } : storedRefreshToken
650
- };
651
- return accessContext;
652
- } catch (error) {
653
- if (typeof error === "string") {
654
- throw toErrorClass(error);
655
- } else {
656
- throw error;
657
- }
658
- }
659
- }
660
- }
661
- __name(exchangeRefreshTokenForAccessToken, "exchangeRefreshTokenForAccessToken");
662
- async function exchangeAuthCodeForAccessToken(state, logger, isNonInteractiveOrCI, clientId, redirectUri) {
663
- const { authorizationCode, codeVerifier = "" } = state;
664
- if (!codeVerifier) {
665
- logger.warn("No code verifier is being sent.");
666
- } else if (!authorizationCode) {
667
- logger.warn("No authorization grant code is being passed.");
668
- }
669
- const params = new URLSearchParams({
670
- grant_type: `authorization_code`,
671
- code: authorizationCode ?? "",
672
- redirect_uri: redirectUri,
673
- client_id: clientId,
674
- code_verifier: codeVerifier
675
- });
676
- const response = await fetchAuthToken(params, logger, isNonInteractiveOrCI);
677
- if (!response.ok) {
678
- const { error } = await getJSONFromResponse(response, logger);
679
- if (error === "invalid_grant") {
680
- logger.log("Expired! Auth code or refresh token needs to be renewed.");
681
- }
682
- throw toErrorClass(error);
683
- }
684
- const json = await getJSONFromResponse(response, logger);
685
- if ("error" in json) {
686
- throw toErrorClass(json.error);
687
- }
688
- const { access_token, expires_in, refresh_token, scope } = json;
689
- state.hasAuthCodeBeenExchangedForAccessToken = true;
690
- const expiryDate = new Date(Date.now() + expires_in * 1e3);
691
- const accessToken = {
692
- value: access_token,
693
- expiry: expiryDate.toISOString()
694
- };
695
- const scopes = scope ? scope.split(" ") : [];
696
- const accessContext = {
697
- token: accessToken,
698
- scopes,
699
- refreshToken: refresh_token ? { value: refresh_token } : void 0
700
- };
701
- return accessContext;
702
- }
703
- __name(exchangeAuthCodeForAccessToken, "exchangeAuthCodeForAccessToken");
704
- async function fetchAuthToken(body, logger, isNonInteractiveOrCI) {
705
- const headers = {
706
- "Content-Type": "application/x-www-form-urlencoded"
707
- };
708
- logger.debug(
709
- "fetching auth token",
710
- `grant_type=${body.get("grant_type") ?? "<unknown>"}`
711
- );
712
- if (await domainUsesAccess(getAuthDomainFromEnv(), logger)) {
713
- logger.debug(
714
- "Using Cloudflare Access to get an access token for the auth request"
715
- );
716
- const accessHeaders = await getCloudflareAccessHeaders({
717
- logger,
718
- isNonInteractiveOrCI
719
- });
720
- Object.assign(headers, accessHeaders);
721
- }
722
- logger.debug("Fetching auth token from", getTokenUrlFromEnv());
723
- try {
724
- const response = await fetch(getTokenUrlFromEnv(), {
725
- method: "POST",
726
- body: body.toString(),
727
- headers
728
- });
729
- if (!response.ok) {
730
- logger.debug(
731
- "Failed to fetch auth token:",
732
- response.status,
733
- response.statusText
734
- );
735
- }
736
- return response;
737
- } catch (e) {
738
- logger.debug("Failed to fetch auth token:", e);
739
- throw e;
740
- }
741
- }
742
- __name(fetchAuthToken, "fetchAuthToken");
743
- async function getJSONFromResponse(response, logger) {
744
- const text = await response.text();
745
- try {
746
- return JSON.parse(text);
747
- } catch (e) {
748
- if (text.match(/<!DOCTYPE html>/)) {
749
- logger.error(
750
- "The body of the response was HTML rather than JSON. Check the debug logs to see the full body of the response."
751
- );
752
- if (text.match(/challenge-platform/)) {
753
- logger.error(
754
- `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(
755
- "cf-ray"
756
- )}`
757
- );
758
- }
759
- }
760
- logger.debug("Full body of response\n\n", text);
761
- throw new Error(
762
- `Invalid JSON in response: status: ${response.status} ${response.statusText}`,
763
- { cause: e }
764
- );
765
- }
766
- }
767
- __name(getJSONFromResponse, "getJSONFromResponse");
768
-
769
- // src/callback-server.ts
770
- async function getOauthToken(options, state, ctx, generators) {
771
- const urlToOpen = await getAuthURL(
772
- options.scopes,
773
- options.clientId,
774
- options.redirectUri,
775
- state,
776
- generators
777
- );
778
- const callbackPath = new URL(options.redirectUri).pathname;
779
- let server;
780
- let loginTimeoutHandle;
781
- const timerPromise = new Promise((_, reject) => {
782
- loginTimeoutHandle = setTimeout(() => {
783
- server.close();
784
- clearTimeout(loginTimeoutHandle);
785
- reject(
786
- new UserError(
787
- "Timed out waiting for authorization code, please try again.",
788
- { telemetryMessage: "user oauth authorization timeout" }
789
- )
790
- );
791
- }, 12e4);
792
- });
793
- const loginPromise = new Promise((resolve, reject) => {
794
- server = http.createServer(async (req, res) => {
795
- function finish(token, error) {
796
- clearTimeout(loginTimeoutHandle);
797
- if (!res.writableEnded) {
798
- res.end();
799
- }
800
- server.close((closeErr) => {
801
- if (error || closeErr) {
802
- reject(error || closeErr);
803
- } else {
804
- assert2(token);
805
- resolve(token);
806
- }
807
- });
808
- }
809
- __name(finish, "finish");
810
- function renderErrorPage(detail) {
811
- const escape = /* @__PURE__ */ __name((s) => s.replace(
812
- /[&<>"']/g,
813
- (c) => ({
814
- "&": "&amp;",
815
- "<": "&lt;",
816
- ">": "&gt;",
817
- '"': "&quot;",
818
- "'": "&#39;"
819
- })[c]
820
- ), "escape");
821
- const codeRow = detail.code ? `<p>Code: <code>${escape(detail.code)}</code></p>` : "";
822
- const descriptionRow = detail.description ? `<p class="detail">${escape(detail.description)}</p>` : "";
823
- const body = `<!doctype html>
824
- <html lang="en">
825
- <head>
826
- <meta charset="utf-8" />
827
- <title>Wrangler login failed</title>
828
- <style>
829
- body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; max-width: 720px; margin: 4rem auto; padding: 0 1rem; color: #1f2933; line-height: 1.5; }
830
- h1 { color: #c12d3f; }
831
- code { background: #f5f7fa; padding: 0.15em 0.3em; border-radius: 3px; }
832
- p.detail { background: #f5f7fa; padding: 1rem; border-radius: 4px; white-space: pre-wrap; }
833
- </style>
834
- </head>
835
- <body>
836
- <h1>Wrangler login failed</h1>
837
- <p>The Cloudflare OAuth provider returned an error.</p>
838
- ${codeRow}
839
- ${descriptionRow}
840
- <p>You can close this tab and return to your terminal for more details.</p>
841
- </body>
842
- </html>`;
843
- res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
844
- res.end(body);
845
- }
846
- __name(renderErrorPage, "renderErrorPage");
847
- assert2(req.url, "This request doesn't have a URL");
848
- const { pathname, query } = url.parse(req.url, true);
849
- if (req.method !== "GET") {
850
- return res.end("OK");
851
- }
852
- switch (pathname) {
853
- case callbackPath: {
854
- let hasAuthCode = false;
855
- try {
856
- hasAuthCode = isReturningFromAuthServer(query, state, ctx.logger);
857
- } catch (err) {
858
- if (err instanceof ErrorAccessDenied) {
859
- res.writeHead(307, {
860
- Location: options.denied.url
861
- });
862
- res.end(() => {
863
- finish(
864
- null,
865
- new UserError(options.denied.error, {
866
- telemetryMessage: "user oauth consent denied"
867
- })
868
- );
869
- });
870
- return;
871
- }
872
- const oauthErr = err;
873
- renderErrorPage({
874
- code: oauthErr.code,
875
- description: oauthErr.description ?? oauthErr.message
876
- });
877
- finish(null, oauthErr);
878
- return;
879
- }
880
- if (!hasAuthCode) {
881
- const noCodeMessage = "The Cloudflare OAuth provider did not return an authorisation code.";
882
- renderErrorPage({ description: noCodeMessage });
883
- finish(
884
- null,
885
- new ErrorNoAuthCode(noCodeMessage, {
886
- telemetryMessage: "user oauth missing auth code"
887
- })
888
- );
889
- return;
890
- }
891
- try {
892
- const exchange = await exchangeAuthCodeForAccessToken(
893
- state,
894
- ctx.logger,
895
- ctx.isNonInteractiveOrCI,
896
- options.clientId,
897
- options.redirectUri
898
- );
899
- res.writeHead(307, {
900
- Location: options.granted.url
901
- });
902
- res.end(() => {
903
- finish(exchange);
904
- });
905
- } catch (err) {
906
- const exchangeErr = err;
907
- const isOAuthError = exchangeErr instanceof ErrorOAuth2;
908
- renderErrorPage({
909
- code: isOAuthError ? exchangeErr.code : void 0,
910
- description: (isOAuthError ? exchangeErr.description : void 0) ?? exchangeErr.message ?? "Failed to exchange the authorisation code for an access token."
911
- });
912
- finish(null, exchangeErr);
913
- }
914
- return;
915
- }
916
- }
917
- });
918
- const redirect = new URL(options.redirectUri);
919
- const redirectPort = Number(
920
- redirect.port || (redirect.protocol === "https:" ? 443 : 80)
921
- );
922
- if (redirect.hostname !== options.callbackHost || redirectPort !== options.callbackPort) {
923
- ctx.logger.log(
924
- `Temporary login server listening on ${options.callbackHost}:${options.callbackPort}`
925
- );
926
- ctx.logger.log(
927
- `Note that the OAuth login page will always redirect to \`${options.redirectUri}\`.
928
- If 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.`
929
- );
930
- }
931
- server.once("error", (err) => {
932
- clearTimeout(loginTimeoutHandle);
933
- if (err.code === "EADDRINUSE") {
934
- reject(
935
- new UserError(
936
- `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\`.`,
937
- { telemetryMessage: "user oauth callback port in use" }
938
- )
939
- );
940
- } else {
941
- reject(err);
942
- }
943
- });
944
- server.listen(options.callbackPort, options.callbackHost);
945
- });
946
- if (options.browser) {
947
- ctx.logger.log(`Opening a link in your default browser: ${urlToOpen}`);
948
- await ctx.openInBrowser(urlToOpen);
949
- } else {
950
- ctx.logger.log(`Visit this link to authenticate: ${urlToOpen}`);
951
- }
952
- return Promise.race([timerPromise, loginPromise]);
953
- }
954
- __name(getOauthToken, "getOauthToken");
955
-
956
- // src/generate-auth-url.ts
957
- var generateAuthUrl = /* @__PURE__ */ __name(({
958
- authUrl,
959
- clientId,
960
- scopes,
961
- stateQueryParam,
962
- codeChallenge,
963
- redirectUri
964
- }) => {
965
- return authUrl + `?response_type=code&client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent([...scopes, "offline_access"].join(" "))}&state=${stateQueryParam}&code_challenge=${encodeURIComponent(codeChallenge)}&code_challenge_method=S256`;
966
- }, "generateAuthUrl");
967
- function generateRandomState(lengthOfState) {
968
- const output = new Uint32Array(lengthOfState);
969
- webcrypto.getRandomValues(output);
970
- return Array.from(output).map((num) => PKCE_CHARSET[num % PKCE_CHARSET.length]).join("");
971
- }
972
- __name(generateRandomState, "generateRandomState");
973
- var POW_MAX_ITERATIONS = 64e6;
974
- function solvePow(seed, k, g) {
975
- const checkpoints = new Array(k + 1);
976
- let h = createHash("sha256").update(seed).digest();
977
- checkpoints[0] = h;
978
- for (let j = 0; j < k; j++) {
979
- for (let i = 0; i < g; i++) {
980
- h = createHash("sha256").update(h).digest();
981
- }
982
- checkpoints[j + 1] = h;
983
- }
984
- return checkpoints;
985
- }
986
- __name(solvePow, "solvePow");
987
- function encodeCheckpoints(checkpoints) {
988
- return Buffer.concat(checkpoints).toString("base64");
989
- }
990
- __name(encodeCheckpoints, "encodeCheckpoints");
991
- function solveChallenge(challenge) {
992
- const checkpoints = solvePow(
993
- Buffer.from(challenge.seed, "base64url"),
994
- challenge.k,
995
- challenge.g
996
- );
997
- return {
998
- challengeToken: challenge.challengeToken,
999
- solution: { checkpoints: encodeCheckpoints(checkpoints) }
1000
- };
1001
- }
1002
- __name(solveChallenge, "solveChallenge");
1003
-
1004
- // src/temporary.ts
1005
- var TEMPORARY_TERMS_URLS = {
1006
- termsOfService: "https://www.cloudflare.com/terms/",
1007
- privacyPolicy: "https://www.cloudflare.com/privacypolicy/"
1008
- };
1009
- var TEMPORARY_TERMS_PROMPT = `You must accept Cloudflare's Terms of Service (${TEMPORARY_TERMS_URLS.termsOfService}) and Privacy Policy (${TEMPORARY_TERMS_URLS.privacyPolicy}) in order to continue. By typing "yes", you agree to these terms. Type "yes" to continue.`;
1010
- var TEMPORARY_TERMS_NOTICE = `Continuing means you accept Cloudflare's Terms of Service (${TEMPORARY_TERMS_URLS.termsOfService}) and Privacy Policy (${TEMPORARY_TERMS_URLS.privacyPolicy}).`;
1011
- var TEMPORARY_TERMS_ERROR = `You must accept Cloudflare's Terms of Service (${TEMPORARY_TERMS_URLS.termsOfService}) and Privacy Policy (${TEMPORARY_TERMS_URLS.privacyPolicy}) to use --temporary.`;
1012
- function getTemporaryPreviewUrl() {
1013
- return `${getCloudflareApiBaseUrl(COMPLIANCE_REGION_CONFIG_PUBLIC)}/provisioning/previews`;
1014
- }
1015
- __name(getTemporaryPreviewUrl, "getTemporaryPreviewUrl");
1016
- function getTemporaryPreviewChallengeUrl() {
1017
- return `${getTemporaryPreviewUrl()}/challenge`;
1018
- }
1019
- __name(getTemporaryPreviewChallengeUrl, "getTemporaryPreviewChallengeUrl");
1020
- function isFutureTimestamp(timestamp) {
1021
- const parsed = Date.parse(timestamp);
1022
- return !Number.isNaN(parsed) && parsed > Date.now();
1023
- }
1024
- __name(isFutureTimestamp, "isFutureTimestamp");
1025
- function getCachedTemporaryPreviewAccount(storage) {
1026
- const temporaryPreviewAccount = storage.read();
1027
- if (!temporaryPreviewAccount) {
1028
- return void 0;
1029
- }
1030
- if (!temporaryPreviewAccount.account?.id || !temporaryPreviewAccount.account?.apiToken || !temporaryPreviewAccount.account?.name || !temporaryPreviewAccount.claim?.url || !isFutureTimestamp(temporaryPreviewAccount.account?.expiresAt ?? "") || !isFutureTimestamp(temporaryPreviewAccount.claim?.expiresAt ?? "")) {
1031
- return void 0;
1032
- }
1033
- return temporaryPreviewAccount;
1034
- }
1035
- __name(getCachedTemporaryPreviewAccount, "getCachedTemporaryPreviewAccount");
1036
- async function requestPowSolution(logger) {
1037
- const response = await fetch(getTemporaryPreviewChallengeUrl(), {
1038
- method: "POST",
1039
- headers: { "Content-Type": "application/json" },
1040
- body: "{}"
1041
- });
1042
- if (!response.ok) {
1043
- throw new FatalError(
1044
- `Failed to request a proof-of-work challenge (${response.status} ${response.statusText}).`,
1045
- { telemetryMessage: "deploy temporary account challenge failed" }
1046
- );
1047
- }
1048
- let body;
1049
- try {
1050
- body = await response.json();
1051
- } catch {
1052
- throw new FatalError(
1053
- `Failed to request a proof-of-work challenge. Received an invalid response (${response.status} ${response.statusText}).`,
1054
- {
1055
- telemetryMessage: "deploy temporary account challenge invalid response"
1056
- }
1057
- );
1058
- }
1059
- const { challengeToken, seed, k, g } = body.result ?? {};
1060
- if (challengeToken === void 0 || seed === void 0 || k === void 0 || g === void 0) {
1061
- throw new FatalError(
1062
- "Failed to request a proof-of-work challenge because the response was missing required fields.",
1063
- { telemetryMessage: "deploy temporary account challenge incomplete" }
1064
- );
1065
- }
1066
- if (!Number.isInteger(k) || !Number.isInteger(g) || k <= 0 || g <= 0 || k * g > POW_MAX_ITERATIONS || Buffer.from(seed, "base64url").length !== 32) {
1067
- throw new FatalError(
1068
- "The proof-of-work challenge is not supported by this version of Wrangler.",
1069
- {
1070
- telemetryMessage: "deploy temporary account challenge difficulty unsupported"
1071
- }
1072
- );
1073
- }
1074
- logger.log("Solving proof-of-work challenge\u2026");
1075
- return solveChallenge({ challengeToken, seed, k, g });
1076
- }
1077
- __name(requestPowSolution, "requestPowSolution");
1078
- async function createTemporaryPreviewAccount(logger) {
1079
- const pow = await requestPowSolution(logger);
1080
- const response = await fetch(getTemporaryPreviewUrl(), {
1081
- method: "POST",
1082
- headers: { "Content-Type": "application/json" },
1083
- body: JSON.stringify({
1084
- termsOfService: TEMPORARY_TERMS_URLS.termsOfService,
1085
- privacyPolicy: TEMPORARY_TERMS_URLS.privacyPolicy,
1086
- acceptTermsOfService: "yes",
1087
- challengeToken: pow.challengeToken,
1088
- solution: pow.solution
1089
- })
1090
- });
1091
- if (!response.ok) {
1092
- throw new FatalError(
1093
- `Failed to create a temporary preview account (${response.status} ${response.statusText}).`,
1094
- { telemetryMessage: "deploy temporary account create failed" }
1095
- );
1096
- }
1097
- let responseBody;
1098
- try {
1099
- responseBody = await response.json();
1100
- } catch {
1101
- throw new FatalError(
1102
- `Failed to create a temporary preview account. Received an invalid response (${response.status} ${response.statusText}).`,
1103
- { telemetryMessage: "deploy temporary account invalid response" }
1104
- );
1105
- }
1106
- const previewAccount = responseBody.result;
1107
- const accountId = previewAccount?.account?.id;
1108
- const accountName = previewAccount?.account?.name;
1109
- const apiToken = previewAccount?.account?.apiToken;
1110
- const accountExpiresAt = previewAccount?.account?.expiresAt;
1111
- const claimUrl = previewAccount?.claim?.url;
1112
- const claimExpiresAt = previewAccount?.claim?.expiresAt;
1113
- if (accountId === void 0 || accountName === void 0 || apiToken === void 0 || accountExpiresAt === void 0 || claimUrl === void 0 || claimExpiresAt === void 0) {
1114
- throw new FatalError(
1115
- "Failed to create a temporary preview account because the response was missing required fields.",
1116
- { telemetryMessage: "deploy temporary account response incomplete" }
1117
- );
1118
- }
1119
- return {
1120
- account: {
1121
- id: accountId,
1122
- name: accountName,
1123
- apiToken,
1124
- expiresAt: accountExpiresAt
1125
- },
1126
- claim: {
1127
- url: claimUrl,
1128
- expiresAt: claimExpiresAt
1129
- }
1130
- };
1131
- }
1132
- __name(createTemporaryPreviewAccount, "createTemporaryPreviewAccount");
1133
- async function getOrCreateTemporaryPreviewAccount(options) {
1134
- const cachedPreviewAccount = getCachedTemporaryPreviewAccount(
1135
- options.storage
1136
- );
1137
- if (cachedPreviewAccount) {
1138
- return { account: cachedPreviewAccount, cached: true };
1139
- }
1140
- const termsAccepted = await options.prompt(
1141
- TEMPORARY_TERMS_PROMPT,
1142
- TEMPORARY_TERMS_NOTICE
1143
- );
1144
- if (!termsAccepted) {
1145
- throw new UserError(TEMPORARY_TERMS_ERROR, {
1146
- telemetryMessage: "user temporary terms not accepted"
1147
- });
1148
- }
1149
- const temporaryPreviewAccount = await createTemporaryPreviewAccount(
1150
- options.logger
1151
- );
1152
- options.storage.write(temporaryPreviewAccount);
1153
- return { account: temporaryPreviewAccount, cached: false };
1154
- }
1155
- __name(getOrCreateTemporaryPreviewAccount, "getOrCreateTemporaryPreviewAccount");
1156
-
1157
- // src/flow.ts
1158
- function createOAuthFlow(ctx) {
1159
- const oauthFlowState = {};
1160
- const generators = {
1161
- generateAuthUrl: ctx.generateAuthUrl ?? generateAuthUrl,
1162
- generateRandomState: ctx.generateRandomState ?? generateRandomState
1163
- };
1164
- let activeProfile = "default";
1165
- function getStorage(profile) {
1166
- return ctx.storageFactory(profile ?? activeProfile);
1167
- }
1168
- __name(getStorage, "getStorage");
1169
- const getClientId = /* @__PURE__ */ __name(() => typeof ctx.clientId === "function" ? ctx.clientId() : ctx.clientId, "getClientId");
1170
- const consent = ctx.consent;
1171
- let temporaryAllowed = false;
1172
- let activeTemporaryAccount;
1173
- const redirectUrl = new URL(ctx.redirectUri);
1174
- const defaultCallbackHost = redirectUrl.hostname;
1175
- const defaultCallbackPort = Number(redirectUrl.port);
1176
- async function login(props) {
1177
- if (ctx.hasEnvCredentials()) {
1178
- ctx.logger.error(
1179
- "You are logged in with an API Token. Unset the CLOUDFLARE_API_TOKEN in the environment to log in via OAuth."
1180
- );
1181
- return false;
1182
- }
1183
- const complianceRegion = getCloudflareComplianceRegion(
1184
- props.complianceConfig
1185
- );
1186
- if (complianceRegion === "fedramp_high") {
1187
- const configurationSource = props.complianceConfig?.compliance_region ? "`compliance_region` configuration property" : "`CLOUDFLARE_API_ENVIRONMENT` environment variable";
1188
- throw new UserError(
1189
- esm_default`
1190
- OAuth login is not supported in the \`${complianceRegion}\` compliance region.
1191
- Please use a Cloudflare API token (\`CLOUDFLARE_API_TOKEN\` environment variable) or remove the ${configurationSource}.
1192
- `,
1193
- {
1194
- telemetryMessage: "user login unsupported compliance region"
1195
- }
1196
- );
1197
- }
1198
- ctx.logger.log("Attempting to login via OAuth...");
1199
- const oauth = await getOauthToken(
1200
- {
1201
- browser: props.browser ?? true,
1202
- scopes: props.scopes,
1203
- clientId: getClientId(),
1204
- redirectUri: ctx.redirectUri,
1205
- denied: consent.denied,
1206
- granted: consent.granted,
1207
- callbackHost: props.callbackHost ?? defaultCallbackHost,
1208
- callbackPort: props.callbackPort ?? defaultCallbackPort
1209
- },
1210
- oauthFlowState,
1211
- ctx,
1212
- generators
1213
- );
1214
- getStorage(props.profile).write({
1215
- oauth_token: oauth.token?.value ?? "",
1216
- expiration_time: oauth.token?.expiry,
1217
- refresh_token: oauth.refreshToken?.value,
1218
- scopes: oauth.scopes
1219
- });
1220
- ctx.logger.log(`Successfully logged in.`);
1221
- clearTemporaryAccount();
1222
- ctx.purgeOnLoginOrLogout?.();
1223
- return true;
1224
- }
1225
- __name(login, "login");
1226
- function isRefreshNeeded(profile) {
1227
- if (ctx.hasEnvCredentials()) {
1228
- return false;
1229
- }
1230
- const { accessToken } = readStoredAuthState({
1231
- warningLogger: ctx.logger,
1232
- storage: getStorage(profile)
1233
- });
1234
- return Boolean(accessToken && /* @__PURE__ */ new Date() >= new Date(accessToken.expiry));
1235
- }
1236
- __name(isRefreshNeeded, "isRefreshNeeded");
1237
- async function refreshToken(profile) {
1238
- const storage = getStorage(profile);
1239
- try {
1240
- const {
1241
- token: { value: oauth_token, expiry: expiration_time } = {
1242
- value: "",
1243
- expiry: ""
1244
- },
1245
- refreshToken: { value: refresh_token } = {},
1246
- scopes
1247
- } = await exchangeRefreshTokenForAccessToken(
1248
- ctx.logger,
1249
- ctx.isNonInteractiveOrCI,
1250
- getClientId(),
1251
- storage
1252
- );
1253
- storage.write({
1254
- oauth_token,
1255
- expiration_time,
1256
- refresh_token,
1257
- scopes
1258
- });
1259
- return true;
1260
- } catch (e) {
1261
- ctx.logger.debug(
1262
- `Token refresh failed: ${e instanceof Error ? e.message : String(e)}`
1263
- );
1264
- return false;
1265
- }
1266
- }
1267
- __name(refreshToken, "refreshToken");
1268
- async function loginOrRefreshIfRequired(props) {
1269
- if (ctx.hasEnvCredentials()) {
1270
- return { loggedIn: true };
1271
- }
1272
- const stored = readStoredAuthState({
1273
- warningLogger: ctx.logger,
1274
- storage: getStorage(props.profile)
1275
- });
1276
- if (!stored.accessToken && !stored.deprecatedApiToken) {
1277
- if (ctx.isNonInteractiveOrCI()) {
1278
- return {
1279
- loggedIn: false,
1280
- reason: "no-credentials-non-interactive"
1281
- };
1282
- }
1283
- if (await login(props)) {
1284
- return { loggedIn: true };
1285
- }
1286
- return { loggedIn: false, reason: "no-credentials-login-failed" };
1287
- } else if (isRefreshNeeded(props.profile)) {
1288
- const didRefresh = await refreshToken(props.profile);
1289
- if (didRefresh) {
1290
- return { loggedIn: true };
1291
- }
1292
- if (ctx.isNonInteractiveOrCI()) {
1293
- return {
1294
- loggedIn: false,
1295
- reason: "token-expired-non-interactive"
1296
- };
1297
- }
1298
- if (await login(props)) {
1299
- return { loggedIn: true };
1300
- }
1301
- return { loggedIn: false, reason: "token-expired-login-failed" };
1302
- } else {
1303
- return { loggedIn: true };
1304
- }
1305
- }
1306
- __name(loginOrRefreshIfRequired, "loginOrRefreshIfRequired");
1307
- async function logout(profile) {
1308
- const clearedTemporary = clearTemporaryAccount();
1309
- if (ctx.hasEnvCredentials()) {
1310
- ctx.logger.log(
1311
- "You are logged in with an API Token. Unset the CLOUDFLARE_API_TOKEN in the environment to log out."
1312
- );
1313
- return;
1314
- }
1315
- const storedRefreshToken = readStoredAuthState({
1316
- warningLogger: ctx.logger,
1317
- storage: getStorage(profile)
1318
- }).refreshToken;
1319
- if (!storedRefreshToken) {
1320
- ctx.logger.log(
1321
- clearedTemporary ? "Cleared temporary preview account." : "Not logged in, exiting..."
1322
- );
1323
- return;
1324
- }
1325
- const body = `client_id=${encodeURIComponent(getClientId())}&token_type_hint=refresh_token&token=${encodeURIComponent(storedRefreshToken.value || "")}`;
1326
- const response = await fetch(getRevokeUrlFromEnv(), {
1327
- method: "POST",
1328
- body,
1329
- headers: {
1330
- "Content-Type": "application/x-www-form-urlencoded"
1331
- }
1332
- });
1333
- await response.text();
1334
- getStorage(profile).clear();
1335
- ctx.logger.log(`Successfully logged out.`);
1336
- ctx.purgeOnLoginOrLogout?.();
1337
- }
1338
- __name(logout, "logout");
1339
- async function getOAuthTokenFromLocalState() {
1340
- let stored = readStoredAuthState({
1341
- warningLogger: ctx.logger,
1342
- storage: getStorage()
1343
- });
1344
- if (!stored.accessToken) {
1345
- return void 0;
1346
- }
1347
- const expired = stored.accessToken && /* @__PURE__ */ new Date() >= new Date(stored.accessToken.expiry);
1348
- if (expired) {
1349
- const didRefresh = await refreshToken();
1350
- if (!didRefresh) {
1351
- return void 0;
1352
- }
1353
- stored = readStoredAuthState({
1354
- warningLogger: ctx.logger,
1355
- storage: getStorage()
1356
- });
1357
- }
1358
- return stored.accessToken?.value;
1359
- }
1360
- __name(getOAuthTokenFromLocalState, "getOAuthTokenFromLocalState");
1361
- function getAPITokenInternal() {
1362
- if (activeTemporaryAccount) {
1363
- return { apiToken: activeTemporaryAccount.account.apiToken };
1364
- }
1365
- return getAPIToken({
1366
- storage: getStorage(),
1367
- warningLogger: ctx.logger,
1368
- allowGlobalAuthKey: ctx.allowGlobalAuthKey
1369
- });
1370
- }
1371
- __name(getAPITokenInternal, "getAPITokenInternal");
1372
- function requireApiTokenInternal() {
1373
- if (activeTemporaryAccount) {
1374
- return { apiToken: activeTemporaryAccount.account.apiToken };
1375
- }
1376
- return requireApiToken({
1377
- storage: getStorage(),
1378
- warningLogger: ctx.logger,
1379
- allowGlobalAuthKey: ctx.allowGlobalAuthKey
1380
- });
1381
- }
1382
- __name(requireApiTokenInternal, "requireApiTokenInternal");
1383
- function setTemporaryAllowed(allowed) {
1384
- temporaryAllowed = allowed && ctx.temporary !== void 0;
1385
- activeTemporaryAccount = void 0;
1386
- }
1387
- __name(setTemporaryAllowed, "setTemporaryAllowed");
1388
- function isTemporaryAllowed() {
1389
- return temporaryAllowed;
1390
- }
1391
- __name(isTemporaryAllowed, "isTemporaryAllowed");
1392
- function getActiveTemporaryAccount() {
1393
- return activeTemporaryAccount;
1394
- }
1395
- __name(getActiveTemporaryAccount, "getActiveTemporaryAccount");
1396
- async function activateTemporaryAccount() {
1397
- if (!ctx.temporary) {
1398
- throw new UserError(
1399
- "Temporary preview accounts are not supported by this CLI.",
1400
- { telemetryMessage: "user temporary account unsupported" }
1401
- );
1402
- }
1403
- const result = await getOrCreateTemporaryPreviewAccount({
1404
- ...ctx.temporary,
1405
- logger: ctx.logger
1406
- });
1407
- activeTemporaryAccount = result.account;
1408
- return result;
1409
- }
1410
- __name(activateTemporaryAccount, "activateTemporaryAccount");
1411
- function clearTemporaryAccount() {
1412
- activeTemporaryAccount = void 0;
1413
- return ctx.temporary?.storage.clear() ?? false;
1414
- }
1415
- __name(clearTemporaryAccount, "clearTemporaryAccount");
1416
- function setProfile(profile) {
1417
- activeProfile = profile;
1418
- }
1419
- __name(setProfile, "setProfile");
1420
- function getActiveProfile() {
1421
- return activeProfile;
1422
- }
1423
- __name(getActiveProfile, "getActiveProfile");
1424
- function getScopes() {
1425
- return readStoredAuthState({
1426
- warningLogger: ctx.logger,
1427
- storage: getStorage()
1428
- }).scopes;
1429
- }
1430
- __name(getScopes, "getScopes");
1431
- return {
1432
- setProfile,
1433
- getActiveProfile,
1434
- login,
1435
- logout,
1436
- loginOrRefreshIfRequired,
1437
- getOAuthTokenFromLocalState,
1438
- getAPIToken: getAPITokenInternal,
1439
- requireApiToken: requireApiTokenInternal,
1440
- getScopes,
1441
- setTemporaryAllowed,
1442
- isTemporaryAllowed,
1443
- getActiveTemporaryAccount,
1444
- activateTemporaryAccount
1445
- };
1446
- }
1447
- __name(createOAuthFlow, "createOAuthFlow");
1448
- var RESERVED_PROFILE_NAMES = ["default", "staging"];
1449
- function createProfileStore(args) {
1450
- const bindings = {
1451
- read() {
1452
- return args.bindings.read();
1453
- },
1454
- write(currentBindings) {
1455
- args.bindings.write(currentBindings);
1456
- },
1457
- activate(profile, dir) {
1458
- const normalizedDir = path4.resolve(dir);
1459
- const currentBindings = args.bindings.read();
1460
- currentBindings[normalizedDir] = profile;
1461
- args.bindings.write(currentBindings);
1462
- },
1463
- deactivate(dir) {
1464
- const normalizedDir = path4.resolve(dir);
1465
- const currentBindings = args.bindings.read();
1466
- const boundProfile = currentBindings[normalizedDir];
1467
- if (boundProfile === void 0) {
1468
- const parentBinding = getProfileForDirectoryFromBindings(
1469
- normalizedDir,
1470
- currentBindings
1471
- );
1472
- if (parentBinding) {
1473
- throw new UserError(
1474
- `No profile is directly bound to "${formatDirectoryForUserError(normalizedDir)}". The active profile "${parentBinding.profile}" is bound at "${formatDirectoryForUserError(
1475
- parentBinding.dir
1476
- )}". Run \`wrangler auth deactivate\` from that directory instead.`,
1477
- { telemetryMessage: "auth deactivate wrong directory" }
1478
- );
1479
- }
1480
- throw new UserError(
1481
- `No profile is bound to "${formatDirectoryForUserError(normalizedDir)}". Nothing to deactivate.`,
1482
- { telemetryMessage: "auth deactivate no binding" }
1483
- );
1484
- }
1485
- delete currentBindings[normalizedDir];
1486
- args.bindings.write(currentBindings);
1487
- const fallbackProfile = getProfileForDirectoryFromBindings(
1488
- normalizedDir,
1489
- currentBindings
1490
- );
1491
- if (fallbackProfile) {
1492
- return {
1493
- removedProfile: boundProfile,
1494
- newResolution: {
1495
- profile: fallbackProfile.profile,
1496
- source: `inherited from ${fallbackProfile.dir}`
1497
- }
1498
- };
1499
- }
1500
- if (args.configs.exists("default")) {
1501
- return {
1502
- removedProfile: boundProfile,
1503
- newResolution: { profile: "default", source: "default profile" }
1504
- };
1505
- }
1506
- return {
1507
- removedProfile: boundProfile,
1508
- newResolution: { profile: void 0, source: "no profile" }
1509
- };
1510
- },
1511
- getProfileForDirectory(startDir) {
1512
- return getProfileForDirectoryFromBindings(startDir, args.bindings.read())?.profile;
1513
- },
1514
- getBindingsForProfile(profile) {
1515
- return Object.entries(args.bindings.read()).filter(([, p]) => p === profile).map(([dir]) => dir);
1516
- },
1517
- removeAllBindingsForProfile(profile) {
1518
- const currentBindings = args.bindings.read();
1519
- const removed = [];
1520
- for (const [dir, p] of Object.entries(currentBindings)) {
1521
- if (p === profile) {
1522
- removed.push(dir);
1523
- delete currentBindings[dir];
1524
- }
1525
- }
1526
- if (removed.length > 0) {
1527
- args.bindings.write(currentBindings);
1528
- }
1529
- return removed;
1530
- }
1531
- };
1532
- return {
1533
- configs: args.configs,
1534
- bindings,
1535
- resolve(resolveArgs) {
1536
- if (resolveArgs.profile) {
1537
- if (resolveArgs.profile === "default") {
1538
- return "default";
1539
- }
1540
- validateProfileName(resolveArgs.profile);
1541
- return resolveArgs.profile;
1542
- }
1543
- const dirProfile = bindings.getProfileForDirectory(resolveArgs.cwd);
1544
- if (dirProfile) {
1545
- return dirProfile;
1546
- }
1547
- return "default";
1548
- }
1549
- };
1550
- }
1551
- __name(createProfileStore, "createProfileStore");
1552
- function validateProfileName(name) {
1553
- if (RESERVED_PROFILE_NAMES.includes(name.toLowerCase())) {
1554
- throw new UserError(
1555
- `"${name}" is a reserved profile name. Use \`wrangler login\` and \`wrangler logout\` to manage the default profile, which applies as a global fallback.`,
1556
- { telemetryMessage: "auth profile reserved name" }
1557
- );
1558
- }
1559
- if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
1560
- throw new UserError(
1561
- `Invalid profile name "${name}". Profile names may only contain alphanumeric characters, hyphens, and underscores.`,
1562
- { telemetryMessage: "auth profile invalid name" }
1563
- );
1564
- }
1565
- }
1566
- __name(validateProfileName, "validateProfileName");
1567
- function formatDirectoryForUserError(dir) {
1568
- return path4.relative(process.cwd(), dir) || ".";
1569
- }
1570
- __name(formatDirectoryForUserError, "formatDirectoryForUserError");
1571
- function getProfileForDirectoryFromBindings(startDir, bindings) {
1572
- const normalizedDir = path4.resolve(startDir);
1573
- const sortedEntries = Object.entries(bindings).sort(
1574
- ([a], [b]) => b.length - a.length
1575
- );
1576
- for (const [boundDir, profile] of sortedEntries) {
1577
- if (normalizedDir === boundDir) {
1578
- return { profile, dir: boundDir };
1579
- }
1580
- if (normalizedDir.startsWith(boundDir) && normalizedDir[boundDir.length] === path4.sep) {
1581
- return { profile, dir: boundDir };
1582
- }
1583
- }
1584
- return void 0;
1585
- }
1586
- __name(getProfileForDirectoryFromBindings, "getProfileForDirectoryFromBindings");
1587
-
1588
- // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/error.js
1589
- function getLineColFromPtr(string, ptr) {
1590
- let lines = string.slice(0, ptr).split(/\r\n|\n|\r/g);
1591
- return [lines.length, lines.pop().length + 1];
1592
- }
1593
- __name(getLineColFromPtr, "getLineColFromPtr");
1594
- function makeCodeBlock(string, line, column) {
1595
- let lines = string.split(/\r\n|\n|\r/g);
1596
- let codeblock = "";
1597
- let numberLen = (Math.log10(line + 1) | 0) + 1;
1598
- for (let i = line - 1; i <= line + 1; i++) {
1599
- let l = lines[i - 1];
1600
- if (!l)
1601
- continue;
1602
- codeblock += i.toString().padEnd(numberLen, " ");
1603
- codeblock += ": ";
1604
- codeblock += l;
1605
- codeblock += "\n";
1606
- if (i === line) {
1607
- codeblock += " ".repeat(numberLen + column + 2);
1608
- codeblock += "^\n";
1609
- }
1610
- }
1611
- return codeblock;
1612
- }
1613
- __name(makeCodeBlock, "makeCodeBlock");
1614
- var TomlError = class extends Error {
1615
- static {
1616
- __name(this, "TomlError");
1617
- }
1618
- line;
1619
- column;
1620
- codeblock;
1621
- constructor(message, options) {
1622
- const [line, column] = getLineColFromPtr(options.toml, options.ptr);
1623
- const codeblock = makeCodeBlock(options.toml, line, column);
1624
- super(`Invalid TOML document: ${message}
1625
-
1626
- ${codeblock}`, options);
1627
- this.line = line;
1628
- this.column = column;
1629
- this.codeblock = codeblock;
1630
- }
1631
- };
1632
-
1633
- // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/util.js
1634
- function isEscaped(str, ptr) {
1635
- let i = 0;
1636
- while (str[ptr - ++i] === "\\")
1637
- ;
1638
- return --i && i % 2;
1639
- }
1640
- __name(isEscaped, "isEscaped");
1641
- function indexOfNewline(str, start = 0, end = str.length) {
1642
- let idx = str.indexOf("\n", start);
1643
- if (str[idx - 1] === "\r")
1644
- idx--;
1645
- return idx <= end ? idx : -1;
1646
- }
1647
- __name(indexOfNewline, "indexOfNewline");
1648
- function skipComment(str, ptr) {
1649
- for (let i = ptr; i < str.length; i++) {
1650
- let c = str[i];
1651
- if (c === "\n")
1652
- return i;
1653
- if (c === "\r" && str[i + 1] === "\n")
1654
- return i + 1;
1655
- if (c < " " && c !== " " || c === "\x7F") {
1656
- throw new TomlError("control characters are not allowed in comments", {
1657
- toml: str,
1658
- ptr
1659
- });
1660
- }
1661
- }
1662
- return str.length;
1663
- }
1664
- __name(skipComment, "skipComment");
1665
- function skipVoid(str, ptr, banNewLines, banComments) {
1666
- let c;
1667
- while ((c = str[ptr]) === " " || c === " " || !banNewLines && (c === "\n" || c === "\r" && str[ptr + 1] === "\n"))
1668
- ptr++;
1669
- return banComments || c !== "#" ? ptr : skipVoid(str, skipComment(str, ptr), banNewLines);
1670
- }
1671
- __name(skipVoid, "skipVoid");
1672
- function skipUntil(str, ptr, sep, end, banNewLines = false) {
1673
- if (!end) {
1674
- ptr = indexOfNewline(str, ptr);
1675
- return ptr < 0 ? str.length : ptr;
1676
- }
1677
- for (let i = ptr; i < str.length; i++) {
1678
- let c = str[i];
1679
- if (c === "#") {
1680
- i = indexOfNewline(str, i);
1681
- } else if (c === sep) {
1682
- return i + 1;
1683
- } else if (c === end || banNewLines && (c === "\n" || c === "\r" && str[i + 1] === "\n")) {
1684
- return i;
1685
- }
1686
- }
1687
- throw new TomlError("cannot find end of structure", {
1688
- toml: str,
1689
- ptr
1690
- });
1691
- }
1692
- __name(skipUntil, "skipUntil");
1693
- function getStringEnd(str, seek) {
1694
- let first = str[seek];
1695
- let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2] ? str.slice(seek, seek + 3) : first;
1696
- seek += target.length - 1;
1697
- do
1698
- seek = str.indexOf(target, ++seek);
1699
- while (seek > -1 && first !== "'" && isEscaped(str, seek));
1700
- if (seek > -1) {
1701
- seek += target.length;
1702
- if (target.length > 1) {
1703
- if (str[seek] === first)
1704
- seek++;
1705
- if (str[seek] === first)
1706
- seek++;
1707
- }
1708
- }
1709
- return seek;
1710
- }
1711
- __name(getStringEnd, "getStringEnd");
1712
-
1713
- // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/date.js
1714
- var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}:\d{2}(?:\.\d+)?)?(Z|[-+]\d{2}:\d{2})?$/i;
1715
- var TomlDate = class _TomlDate extends Date {
1716
- static {
1717
- __name(this, "TomlDate");
1718
- }
1719
- #hasDate = false;
1720
- #hasTime = false;
1721
- #offset = null;
1722
- constructor(date) {
1723
- let hasDate = true;
1724
- let hasTime = true;
1725
- let offset = "Z";
1726
- if (typeof date === "string") {
1727
- let match = date.match(DATE_TIME_RE);
1728
- if (match) {
1729
- if (!match[1]) {
1730
- hasDate = false;
1731
- date = `0000-01-01T${date}`;
1732
- }
1733
- hasTime = !!match[2];
1734
- hasTime && date[10] === " " && (date = date.replace(" ", "T"));
1735
- if (match[2] && +match[2] > 23) {
1736
- date = "";
1737
- } else {
1738
- offset = match[3] || null;
1739
- date = date.toUpperCase();
1740
- if (!offset && hasTime)
1741
- date += "Z";
1742
- }
1743
- } else {
1744
- date = "";
1745
- }
1746
- }
1747
- super(date);
1748
- if (!isNaN(this.getTime())) {
1749
- this.#hasDate = hasDate;
1750
- this.#hasTime = hasTime;
1751
- this.#offset = offset;
1752
- }
1753
- }
1754
- isDateTime() {
1755
- return this.#hasDate && this.#hasTime;
1756
- }
1757
- isLocal() {
1758
- return !this.#hasDate || !this.#hasTime || !this.#offset;
1759
- }
1760
- isDate() {
1761
- return this.#hasDate && !this.#hasTime;
1762
- }
1763
- isTime() {
1764
- return this.#hasTime && !this.#hasDate;
1765
- }
1766
- isValid() {
1767
- return this.#hasDate || this.#hasTime;
1768
- }
1769
- toISOString() {
1770
- let iso = super.toISOString();
1771
- if (this.isDate())
1772
- return iso.slice(0, 10);
1773
- if (this.isTime())
1774
- return iso.slice(11, 23);
1775
- if (this.#offset === null)
1776
- return iso.slice(0, -1);
1777
- if (this.#offset === "Z")
1778
- return iso;
1779
- let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
1780
- offset = this.#offset[0] === "-" ? offset : -offset;
1781
- let offsetDate = new Date(this.getTime() - offset * 6e4);
1782
- return offsetDate.toISOString().slice(0, -1) + this.#offset;
1783
- }
1784
- static wrapAsOffsetDateTime(jsDate, offset = "Z") {
1785
- let date = new _TomlDate(jsDate);
1786
- date.#offset = offset;
1787
- return date;
1788
- }
1789
- static wrapAsLocalDateTime(jsDate) {
1790
- let date = new _TomlDate(jsDate);
1791
- date.#offset = null;
1792
- return date;
1793
- }
1794
- static wrapAsLocalDate(jsDate) {
1795
- let date = new _TomlDate(jsDate);
1796
- date.#hasTime = false;
1797
- date.#offset = null;
1798
- return date;
1799
- }
1800
- static wrapAsLocalTime(jsDate) {
1801
- let date = new _TomlDate(jsDate);
1802
- date.#hasDate = false;
1803
- date.#offset = null;
1804
- return date;
1805
- }
1806
- };
1807
-
1808
- // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/primitive.js
1809
- var INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/;
1810
- var FLOAT_REGEX = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/;
1811
- var LEADING_ZERO = /^[+-]?0[0-9_]/;
1812
- var ESCAPE_REGEX = /^[0-9a-f]{4,8}$/i;
1813
- var ESC_MAP = {
1814
- b: "\b",
1815
- t: " ",
1816
- n: "\n",
1817
- f: "\f",
1818
- r: "\r",
1819
- '"': '"',
1820
- "\\": "\\"
1821
- };
1822
- function parseString(str, ptr = 0, endPtr = str.length) {
1823
- let isLiteral = str[ptr] === "'";
1824
- let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];
1825
- if (isMultiline) {
1826
- endPtr -= 2;
1827
- if (str[ptr += 2] === "\r")
1828
- ptr++;
1829
- if (str[ptr] === "\n")
1830
- ptr++;
1831
- }
1832
- let tmp = 0;
1833
- let isEscape;
1834
- let parsed = "";
1835
- let sliceStart = ptr;
1836
- while (ptr < endPtr - 1) {
1837
- let c = str[ptr++];
1838
- if (c === "\n" || c === "\r" && str[ptr] === "\n") {
1839
- if (!isMultiline) {
1840
- throw new TomlError("newlines are not allowed in strings", {
1841
- toml: str,
1842
- ptr: ptr - 1
1843
- });
1844
- }
1845
- } else if (c < " " && c !== " " || c === "\x7F") {
1846
- throw new TomlError("control characters are not allowed in strings", {
1847
- toml: str,
1848
- ptr: ptr - 1
1849
- });
1850
- }
1851
- if (isEscape) {
1852
- isEscape = false;
1853
- if (c === "u" || c === "U") {
1854
- let code = str.slice(ptr, ptr += c === "u" ? 4 : 8);
1855
- if (!ESCAPE_REGEX.test(code)) {
1856
- throw new TomlError("invalid unicode escape", {
1857
- toml: str,
1858
- ptr: tmp
1859
- });
1860
- }
1861
- try {
1862
- parsed += String.fromCodePoint(parseInt(code, 16));
1863
- } catch {
1864
- throw new TomlError("invalid unicode escape", {
1865
- toml: str,
1866
- ptr: tmp
1867
- });
1868
- }
1869
- } else if (isMultiline && (c === "\n" || c === " " || c === " " || c === "\r")) {
1870
- ptr = skipVoid(str, ptr - 1, true);
1871
- if (str[ptr] !== "\n" && str[ptr] !== "\r") {
1872
- throw new TomlError("invalid escape: only line-ending whitespace may be escaped", {
1873
- toml: str,
1874
- ptr: tmp
1875
- });
1876
- }
1877
- ptr = skipVoid(str, ptr);
1878
- } else if (c in ESC_MAP) {
1879
- parsed += ESC_MAP[c];
1880
- } else {
1881
- throw new TomlError("unrecognized escape sequence", {
1882
- toml: str,
1883
- ptr: tmp
1884
- });
1885
- }
1886
- sliceStart = ptr;
1887
- } else if (!isLiteral && c === "\\") {
1888
- tmp = ptr - 1;
1889
- isEscape = true;
1890
- parsed += str.slice(sliceStart, tmp);
1891
- }
1892
- }
1893
- return parsed + str.slice(sliceStart, endPtr - 1);
1894
- }
1895
- __name(parseString, "parseString");
1896
- function parseValue(value, toml, ptr, integersAsBigInt) {
1897
- if (value === "true")
1898
- return true;
1899
- if (value === "false")
1900
- return false;
1901
- if (value === "-inf")
1902
- return -Infinity;
1903
- if (value === "inf" || value === "+inf")
1904
- return Infinity;
1905
- if (value === "nan" || value === "+nan" || value === "-nan")
1906
- return NaN;
1907
- if (value === "-0")
1908
- return integersAsBigInt ? 0n : 0;
1909
- let isInt = INT_REGEX.test(value);
1910
- if (isInt || FLOAT_REGEX.test(value)) {
1911
- if (LEADING_ZERO.test(value)) {
1912
- throw new TomlError("leading zeroes are not allowed", {
1913
- toml,
1914
- ptr
1915
- });
1916
- }
1917
- value = value.replace(/_/g, "");
1918
- let numeric = +value;
1919
- if (isNaN(numeric)) {
1920
- throw new TomlError("invalid number", {
1921
- toml,
1922
- ptr
1923
- });
1924
- }
1925
- if (isInt) {
1926
- if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {
1927
- throw new TomlError("integer value cannot be represented losslessly", {
1928
- toml,
1929
- ptr
1930
- });
1931
- }
1932
- if (isInt || integersAsBigInt === true)
1933
- numeric = BigInt(value);
1934
- }
1935
- return numeric;
1936
- }
1937
- const date = new TomlDate(value);
1938
- if (!date.isValid()) {
1939
- throw new TomlError("invalid value", {
1940
- toml,
1941
- ptr
1942
- });
1943
- }
1944
- return date;
1945
- }
1946
- __name(parseValue, "parseValue");
1947
-
1948
- // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/extract.js
1949
- function sliceAndTrimEndOf(str, startPtr, endPtr, allowNewLines) {
1950
- let value = str.slice(startPtr, endPtr);
1951
- let commentIdx = value.indexOf("#");
1952
- if (commentIdx > -1) {
1953
- skipComment(str, commentIdx);
1954
- value = value.slice(0, commentIdx);
1955
- }
1956
- let trimmed = value.trimEnd();
1957
- if (!allowNewLines) {
1958
- let newlineIdx = value.indexOf("\n", trimmed.length);
1959
- if (newlineIdx > -1) {
1960
- throw new TomlError("newlines are not allowed in inline tables", {
1961
- toml: str,
1962
- ptr: startPtr + newlineIdx
1963
- });
1964
- }
1965
- }
1966
- return [trimmed, commentIdx];
1967
- }
1968
- __name(sliceAndTrimEndOf, "sliceAndTrimEndOf");
1969
- function extractValue(str, ptr, end, depth, integersAsBigInt) {
1970
- if (depth === 0) {
1971
- throw new TomlError("document contains excessively nested structures. aborting.", {
1972
- toml: str,
1973
- ptr
1974
- });
1975
- }
1976
- let c = str[ptr];
1977
- if (c === "[" || c === "{") {
1978
- let [value, endPtr2] = c === "[" ? parseArray(str, ptr, depth, integersAsBigInt) : parseInlineTable(str, ptr, depth, integersAsBigInt);
1979
- let newPtr = end ? skipUntil(str, endPtr2, ",", end) : endPtr2;
1980
- if (endPtr2 - newPtr && end === "}") {
1981
- let nextNewLine = indexOfNewline(str, endPtr2, newPtr);
1982
- if (nextNewLine > -1) {
1983
- throw new TomlError("newlines are not allowed in inline tables", {
1984
- toml: str,
1985
- ptr: nextNewLine
1986
- });
1987
- }
1988
- }
1989
- return [value, newPtr];
1990
- }
1991
- let endPtr;
1992
- if (c === '"' || c === "'") {
1993
- endPtr = getStringEnd(str, ptr);
1994
- let parsed = parseString(str, ptr, endPtr);
1995
- if (end) {
1996
- endPtr = skipVoid(str, endPtr, end !== "]");
1997
- if (str[endPtr] && str[endPtr] !== "," && str[endPtr] !== end && str[endPtr] !== "\n" && str[endPtr] !== "\r") {
1998
- throw new TomlError("unexpected character encountered", {
1999
- toml: str,
2000
- ptr: endPtr
2001
- });
2002
- }
2003
- endPtr += +(str[endPtr] === ",");
2004
- }
2005
- return [parsed, endPtr];
2006
- }
2007
- endPtr = skipUntil(str, ptr, ",", end);
2008
- let slice = sliceAndTrimEndOf(str, ptr, endPtr - +(str[endPtr - 1] === ","), end === "]");
2009
- if (!slice[0]) {
2010
- throw new TomlError("incomplete key-value declaration: no value specified", {
2011
- toml: str,
2012
- ptr
2013
- });
2014
- }
2015
- if (end && slice[1] > -1) {
2016
- endPtr = skipVoid(str, ptr + slice[1]);
2017
- endPtr += +(str[endPtr] === ",");
2018
- }
2019
- return [
2020
- parseValue(slice[0], str, ptr, integersAsBigInt),
2021
- endPtr
2022
- ];
2023
- }
2024
- __name(extractValue, "extractValue");
2025
-
2026
- // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/struct.js
2027
- var KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \t]*$/;
2028
- function parseKey(str, ptr, end = "=") {
2029
- let dot = ptr - 1;
2030
- let parsed = [];
2031
- let endPtr = str.indexOf(end, ptr);
2032
- if (endPtr < 0) {
2033
- throw new TomlError("incomplete key-value: cannot find end of key", {
2034
- toml: str,
2035
- ptr
2036
- });
2037
- }
2038
- do {
2039
- let c = str[ptr = ++dot];
2040
- if (c !== " " && c !== " ") {
2041
- if (c === '"' || c === "'") {
2042
- if (c === str[ptr + 1] && c === str[ptr + 2]) {
2043
- throw new TomlError("multiline strings are not allowed in keys", {
2044
- toml: str,
2045
- ptr
2046
- });
2047
- }
2048
- let eos = getStringEnd(str, ptr);
2049
- if (eos < 0) {
2050
- throw new TomlError("unfinished string encountered", {
2051
- toml: str,
2052
- ptr
2053
- });
2054
- }
2055
- dot = str.indexOf(".", eos);
2056
- let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);
2057
- let newLine = indexOfNewline(strEnd);
2058
- if (newLine > -1) {
2059
- throw new TomlError("newlines are not allowed in keys", {
2060
- toml: str,
2061
- ptr: ptr + dot + newLine
2062
- });
2063
- }
2064
- if (strEnd.trimStart()) {
2065
- throw new TomlError("found extra tokens after the string part", {
2066
- toml: str,
2067
- ptr: eos
2068
- });
2069
- }
2070
- if (endPtr < eos) {
2071
- endPtr = str.indexOf(end, eos);
2072
- if (endPtr < 0) {
2073
- throw new TomlError("incomplete key-value: cannot find end of key", {
2074
- toml: str,
2075
- ptr
2076
- });
2077
- }
2078
- }
2079
- parsed.push(parseString(str, ptr, eos));
2080
- } else {
2081
- dot = str.indexOf(".", ptr);
2082
- let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);
2083
- if (!KEY_PART_RE.test(part)) {
2084
- throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys", {
2085
- toml: str,
2086
- ptr
2087
- });
2088
- }
2089
- parsed.push(part.trimEnd());
2090
- }
2091
- }
2092
- } while (dot + 1 && dot < endPtr);
2093
- return [parsed, skipVoid(str, endPtr + 1, true, true)];
2094
- }
2095
- __name(parseKey, "parseKey");
2096
- function parseInlineTable(str, ptr, depth, integersAsBigInt) {
2097
- let res = {};
2098
- let seen = /* @__PURE__ */ new Set();
2099
- let c;
2100
- let comma = 0;
2101
- ptr++;
2102
- while ((c = str[ptr++]) !== "}" && c) {
2103
- let err = { toml: str, ptr: ptr - 1 };
2104
- if (c === "\n") {
2105
- throw new TomlError("newlines are not allowed in inline tables", err);
2106
- } else if (c === "#") {
2107
- throw new TomlError("inline tables cannot contain comments", err);
2108
- } else if (c === ",") {
2109
- throw new TomlError("expected key-value, found comma", err);
2110
- } else if (c !== " " && c !== " ") {
2111
- let k;
2112
- let t = res;
2113
- let hasOwn = false;
2114
- let [key, keyEndPtr] = parseKey(str, ptr - 1);
2115
- for (let i = 0; i < key.length; i++) {
2116
- if (i)
2117
- t = hasOwn ? t[k] : t[k] = {};
2118
- k = key[i];
2119
- if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
2120
- throw new TomlError("trying to redefine an already defined value", {
2121
- toml: str,
2122
- ptr
2123
- });
2124
- }
2125
- if (!hasOwn && k === "__proto__") {
2126
- Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
2127
- }
2128
- }
2129
- if (hasOwn) {
2130
- throw new TomlError("trying to redefine an already defined value", {
2131
- toml: str,
2132
- ptr
2133
- });
2134
- }
2135
- let [value, valueEndPtr] = extractValue(str, keyEndPtr, "}", depth - 1, integersAsBigInt);
2136
- seen.add(value);
2137
- t[k] = value;
2138
- ptr = valueEndPtr;
2139
- comma = str[ptr - 1] === "," ? ptr - 1 : 0;
2140
- }
2141
- }
2142
- if (comma) {
2143
- throw new TomlError("trailing commas are not allowed in inline tables", {
2144
- toml: str,
2145
- ptr: comma
2146
- });
2147
- }
2148
- if (!c) {
2149
- throw new TomlError("unfinished table encountered", {
2150
- toml: str,
2151
- ptr
2152
- });
2153
- }
2154
- return [res, ptr];
2155
- }
2156
- __name(parseInlineTable, "parseInlineTable");
2157
- function parseArray(str, ptr, depth, integersAsBigInt) {
2158
- let res = [];
2159
- let c;
2160
- ptr++;
2161
- while ((c = str[ptr++]) !== "]" && c) {
2162
- if (c === ",") {
2163
- throw new TomlError("expected value, found comma", {
2164
- toml: str,
2165
- ptr: ptr - 1
2166
- });
2167
- } else if (c === "#")
2168
- ptr = skipComment(str, ptr);
2169
- else if (c !== " " && c !== " " && c !== "\n" && c !== "\r") {
2170
- let e = extractValue(str, ptr - 1, "]", depth - 1, integersAsBigInt);
2171
- res.push(e[0]);
2172
- ptr = e[1];
2173
- }
2174
- }
2175
- if (!c) {
2176
- throw new TomlError("unfinished array encountered", {
2177
- toml: str,
2178
- ptr
2179
- });
2180
- }
2181
- return [res, ptr];
2182
- }
2183
- __name(parseArray, "parseArray");
2184
-
2185
- // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/parse.js
2186
- function peekTable(key, table, meta, type) {
2187
- let t = table;
2188
- let m = meta;
2189
- let k;
2190
- let hasOwn = false;
2191
- let state;
2192
- for (let i = 0; i < key.length; i++) {
2193
- if (i) {
2194
- t = hasOwn ? t[k] : t[k] = {};
2195
- m = (state = m[k]).c;
2196
- if (type === 0 && (state.t === 1 || state.t === 2)) {
2197
- return null;
2198
- }
2199
- if (state.t === 2) {
2200
- let l = t.length - 1;
2201
- t = t[l];
2202
- m = m[l].c;
2203
- }
2204
- }
2205
- k = key[i];
2206
- if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
2207
- return null;
2208
- }
2209
- if (!hasOwn) {
2210
- if (k === "__proto__") {
2211
- Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
2212
- Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
2213
- }
2214
- m[k] = {
2215
- t: i < key.length - 1 && type === 2 ? 3 : type,
2216
- d: false,
2217
- i: 0,
2218
- c: {}
2219
- };
2220
- }
2221
- }
2222
- state = m[k];
2223
- if (state.t !== type && !(type === 1 && state.t === 3)) {
2224
- return null;
2225
- }
2226
- if (type === 2) {
2227
- if (!state.d) {
2228
- state.d = true;
2229
- t[k] = [];
2230
- }
2231
- t[k].push(t = {});
2232
- state.c[state.i++] = state = { t: 1, d: false, i: 0, c: {} };
2233
- }
2234
- if (state.d) {
2235
- return null;
2236
- }
2237
- state.d = true;
2238
- if (type === 1) {
2239
- t = hasOwn ? t[k] : t[k] = {};
2240
- } else if (type === 0 && hasOwn) {
2241
- return null;
2242
- }
2243
- return [k, t, state.c];
2244
- }
2245
- __name(peekTable, "peekTable");
2246
- function parse(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
2247
- let res = {};
2248
- let meta = {};
2249
- let tbl = res;
2250
- let m = meta;
2251
- for (let ptr = skipVoid(toml, 0); ptr < toml.length; ) {
2252
- if (toml[ptr] === "[") {
2253
- let isTableArray = toml[++ptr] === "[";
2254
- let k = parseKey(toml, ptr += +isTableArray, "]");
2255
- if (isTableArray) {
2256
- if (toml[k[1] - 1] !== "]") {
2257
- throw new TomlError("expected end of table declaration", {
2258
- toml,
2259
- ptr: k[1] - 1
2260
- });
2261
- }
2262
- k[1]++;
2263
- }
2264
- let p = peekTable(
2265
- k[0],
2266
- res,
2267
- meta,
2268
- isTableArray ? 2 : 1
2269
- /* Type.EXPLICIT */
2270
- );
2271
- if (!p) {
2272
- throw new TomlError("trying to redefine an already defined table or value", {
2273
- toml,
2274
- ptr
2275
- });
2276
- }
2277
- m = p[2];
2278
- tbl = p[1];
2279
- ptr = k[1];
2280
- } else {
2281
- let k = parseKey(toml, ptr);
2282
- let p = peekTable(
2283
- k[0],
2284
- tbl,
2285
- m,
2286
- 0
2287
- /* Type.DOTTED */
2288
- );
2289
- if (!p) {
2290
- throw new TomlError("trying to redefine an already defined table or value", {
2291
- toml,
2292
- ptr
2293
- });
2294
- }
2295
- let v = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);
2296
- p[1][p[0]] = v[0];
2297
- ptr = v[1];
2298
- }
2299
- ptr = skipVoid(toml, ptr, true);
2300
- if (toml[ptr] && toml[ptr] !== "\n" && toml[ptr] !== "\r") {
2301
- throw new TomlError("each key-value declaration must be followed by an end-of-line", {
2302
- toml,
2303
- ptr
2304
- });
2305
- }
2306
- ptr = skipVoid(toml, ptr);
2307
- }
2308
- return res;
2309
- }
2310
- __name(parse, "parse");
2311
-
2312
- // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/stringify.js
2313
- var BARE_KEY = /^[a-z0-9-_]+$/i;
2314
- function extendedTypeOf(obj) {
2315
- let type = typeof obj;
2316
- if (type === "object") {
2317
- if (Array.isArray(obj))
2318
- return "array";
2319
- if (obj instanceof Date)
2320
- return "date";
2321
- }
2322
- return type;
2323
- }
2324
- __name(extendedTypeOf, "extendedTypeOf");
2325
- function isArrayOfTables(obj) {
2326
- for (let i = 0; i < obj.length; i++) {
2327
- if (extendedTypeOf(obj[i]) !== "object")
2328
- return false;
2329
- }
2330
- return obj.length != 0;
2331
- }
2332
- __name(isArrayOfTables, "isArrayOfTables");
2333
- function formatString(s) {
2334
- return JSON.stringify(s).replace(/\x7f/g, "\\u007f");
2335
- }
2336
- __name(formatString, "formatString");
2337
- function stringifyValue(val, type, depth, numberAsFloat) {
2338
- if (depth === 0) {
2339
- throw new Error("Could not stringify the object: maximum object depth exceeded");
2340
- }
2341
- if (type === "number") {
2342
- if (isNaN(val))
2343
- return "nan";
2344
- if (val === Infinity)
2345
- return "inf";
2346
- if (val === -Infinity)
2347
- return "-inf";
2348
- if (numberAsFloat && Number.isInteger(val))
2349
- return val.toFixed(1);
2350
- return val.toString();
2351
- }
2352
- if (type === "bigint" || type === "boolean") {
2353
- return val.toString();
2354
- }
2355
- if (type === "string") {
2356
- return formatString(val);
2357
- }
2358
- if (type === "date") {
2359
- if (isNaN(val.getTime())) {
2360
- throw new TypeError("cannot serialize invalid date");
2361
- }
2362
- return val.toISOString();
2363
- }
2364
- if (type === "object") {
2365
- return stringifyInlineTable(val, depth, numberAsFloat);
2366
- }
2367
- if (type === "array") {
2368
- return stringifyArray(val, depth, numberAsFloat);
2369
- }
2370
- }
2371
- __name(stringifyValue, "stringifyValue");
2372
- function stringifyInlineTable(obj, depth, numberAsFloat) {
2373
- let keys = Object.keys(obj);
2374
- if (keys.length === 0)
2375
- return "{}";
2376
- let res = "{ ";
2377
- for (let i = 0; i < keys.length; i++) {
2378
- let k = keys[i];
2379
- if (i)
2380
- res += ", ";
2381
- res += BARE_KEY.test(k) ? k : formatString(k);
2382
- res += " = ";
2383
- res += stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat);
2384
- }
2385
- return res + " }";
2386
- }
2387
- __name(stringifyInlineTable, "stringifyInlineTable");
2388
- function stringifyArray(array, depth, numberAsFloat) {
2389
- if (array.length === 0)
2390
- return "[]";
2391
- let res = "[ ";
2392
- for (let i = 0; i < array.length; i++) {
2393
- if (i)
2394
- res += ", ";
2395
- if (array[i] === null || array[i] === void 0) {
2396
- throw new TypeError("arrays cannot contain null or undefined values");
2397
- }
2398
- res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat);
2399
- }
2400
- return res + " ]";
2401
- }
2402
- __name(stringifyArray, "stringifyArray");
2403
- function stringifyArrayTable(array, key, depth, numberAsFloat) {
2404
- if (depth === 0) {
2405
- throw new Error("Could not stringify the object: maximum object depth exceeded");
2406
- }
2407
- let res = "";
2408
- for (let i = 0; i < array.length; i++) {
2409
- res += `${res && "\n"}[[${key}]]
2410
- `;
2411
- res += stringifyTable(0, array[i], key, depth, numberAsFloat);
2412
- }
2413
- return res;
2414
- }
2415
- __name(stringifyArrayTable, "stringifyArrayTable");
2416
- function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat) {
2417
- if (depth === 0) {
2418
- throw new Error("Could not stringify the object: maximum object depth exceeded");
2419
- }
2420
- let preamble = "";
2421
- let tables = "";
2422
- let keys = Object.keys(obj);
2423
- for (let i = 0; i < keys.length; i++) {
2424
- let k = keys[i];
2425
- if (obj[k] !== null && obj[k] !== void 0) {
2426
- let type = extendedTypeOf(obj[k]);
2427
- if (type === "symbol" || type === "function") {
2428
- throw new TypeError(`cannot serialize values of type '${type}'`);
2429
- }
2430
- let key = BARE_KEY.test(k) ? k : formatString(k);
2431
- if (type === "array" && isArrayOfTables(obj[k])) {
2432
- tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat);
2433
- } else if (type === "object") {
2434
- let tblKey = prefix ? `${prefix}.${key}` : key;
2435
- tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat);
2436
- } else {
2437
- preamble += key;
2438
- preamble += " = ";
2439
- preamble += stringifyValue(obj[k], type, depth, numberAsFloat);
2440
- preamble += "\n";
2441
- }
2442
- }
2443
- }
2444
- if (tableKey && (preamble || !tables))
2445
- preamble = preamble ? `[${tableKey}]
2446
- ${preamble}` : `[${tableKey}]`;
2447
- return preamble && tables ? `${preamble}
2448
- ${tables}` : preamble || tables;
2449
- }
2450
- __name(stringifyTable, "stringifyTable");
2451
- function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false } = {}) {
2452
- if (extendedTypeOf(obj) !== "object") {
2453
- throw new TypeError("stringify can only be called with an object");
2454
- }
2455
- let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat);
2456
- if (str[str.length - 1] !== "\n")
2457
- return str + "\n";
2458
- return str;
2459
- }
2460
- __name(stringify, "stringify");
2461
-
2462
- // ../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/index.js
2463
- var dist_default = { parse, stringify, TomlDate, TomlError };
2464
-
2465
- // src/credential-store/file-store.ts
2466
- var USER_AUTH_CONFIG_PATH = "config";
2467
- function resolveAuthProfileBaseName(profile) {
2468
- if (profile === void 0 || profile === "default") {
2469
- const environment = getCloudflareApiEnvironmentFromEnv();
2470
- return environment === "production" ? "default" : environment;
2471
- }
2472
- validateProfileName(profile);
2473
- return profile;
2474
- }
2475
- __name(resolveAuthProfileBaseName, "resolveAuthProfileBaseName");
2476
- function getAuthConfigFilePath(configPath, profile) {
2477
- return path4.join(
2478
- configPath,
2479
- USER_AUTH_CONFIG_PATH,
2480
- `${resolveAuthProfileBaseName(profile)}.toml`
2481
- );
2482
- }
2483
- __name(getAuthConfigFilePath, "getAuthConfigFilePath");
2484
- var FileCredentialStore = class {
2485
- /**
2486
- * @param configPath consumer-provided global config directory (the CLI
2487
- * owns where its config lives, so workers-auth never resolves it itself).
2488
- * @param profile the auth profile (defaults to the active environment's
2489
- * default profile).
2490
- */
2491
- constructor(configPath, profile) {
2492
- this.configPath = configPath;
2493
- this.profile = profile;
2494
- }
2495
- static {
2496
- __name(this, "FileCredentialStore");
2497
- }
2498
- kind = "file";
2499
- read() {
2500
- const filePath = getAuthConfigFilePath(this.configPath, this.profile);
2501
- if (!existsSync(filePath)) {
2502
- return void 0;
2503
- }
2504
- return parseTOML(readFileSync(filePath));
2505
- }
2506
- write(config) {
2507
- const filePath = getAuthConfigFilePath(this.configPath, this.profile);
2508
- mkdirSync(path4.dirname(filePath), { recursive: true });
2509
- writeFileSync(filePath, dist_default.stringify(config), {
2510
- encoding: "utf-8",
2511
- mode: 384
2512
- });
2513
- chmodSync(filePath, 384);
2514
- }
2515
- clear() {
2516
- const filePath = getAuthConfigFilePath(this.configPath, this.profile);
2517
- const existed = existsSync(filePath);
2518
- if (existed) {
2519
- rmSync(filePath);
2520
- }
2521
- return existed;
2522
- }
2523
- path() {
2524
- return getAuthConfigFilePath(this.configPath, this.profile);
2525
- }
2526
- describe() {
2527
- return getAuthConfigFilePath(this.configPath, this.profile);
2528
- }
2529
- };
2530
- var KEY_LENGTH_BYTES = 32;
2531
- var IV_LENGTH_BYTES = 12;
2532
- var TAG_LENGTH_BYTES = 16;
2533
- var ALGORITHM_LABEL = "AES-256-GCM";
2534
- var CIPHER_NAME = "aes-256-gcm";
2535
- function generateKey() {
2536
- return new Uint8Array(randomBytes(KEY_LENGTH_BYTES));
2537
- }
2538
- __name(generateKey, "generateKey");
2539
- function encryptString(plaintext, key) {
2540
- if (key.length !== KEY_LENGTH_BYTES) {
2541
- throw new Error(
2542
- `AES-256-GCM requires a ${KEY_LENGTH_BYTES}-byte key (got ${key.length} bytes).`
2543
- );
2544
- }
2545
- const iv = randomBytes(IV_LENGTH_BYTES);
2546
- const cipher = createCipheriv(CIPHER_NAME, key, iv);
2547
- const ciphertext = Buffer.concat([
2548
- cipher.update(plaintext, "utf-8"),
2549
- cipher.final()
2550
- ]);
2551
- const tag = cipher.getAuthTag();
2552
- return {
2553
- v: 1,
2554
- alg: ALGORITHM_LABEL,
2555
- iv: iv.toString("base64"),
2556
- tag: tag.toString("base64"),
2557
- ciphertext: ciphertext.toString("base64")
2558
- };
2559
- }
2560
- __name(encryptString, "encryptString");
2561
- function decryptString(envelope, key) {
2562
- if (key.length !== KEY_LENGTH_BYTES) {
2563
- throw new Error(
2564
- `AES-256-GCM requires a ${KEY_LENGTH_BYTES}-byte key (got ${key.length} bytes).`
2565
- );
2566
- }
2567
- if (envelope.v !== 1) {
2568
- throw new Error(
2569
- `Unsupported encrypted envelope version: ${envelope.v}.`
2570
- );
2571
- }
2572
- const iv = Buffer.from(envelope.iv, "base64");
2573
- const tag = Buffer.from(envelope.tag, "base64");
2574
- const ciphertext = Buffer.from(envelope.ciphertext, "base64");
2575
- if (iv.length !== IV_LENGTH_BYTES) {
2576
- throw new Error(
2577
- `Expected ${IV_LENGTH_BYTES}-byte IV in envelope (got ${iv.length} bytes).`
2578
- );
2579
- }
2580
- if (tag.length !== TAG_LENGTH_BYTES) {
2581
- throw new Error(
2582
- `Expected ${TAG_LENGTH_BYTES}-byte auth tag in envelope (got ${tag.length} bytes).`
2583
- );
2584
- }
2585
- const decipher = createDecipheriv(CIPHER_NAME, key, iv);
2586
- decipher.setAuthTag(tag);
2587
- const plaintext = Buffer.concat([
2588
- decipher.update(ciphertext),
2589
- // `final()` is where GCM verifies the auth tag and throws on
2590
- // mismatch. We let that error propagate so callers can decide
2591
- // whether to treat it as "not logged in" or surface it.
2592
- decipher.final()
2593
- ]);
2594
- return plaintext.toString("utf-8");
2595
- }
2596
- __name(decryptString, "decryptString");
2597
- function parseEncryptedEnvelope(raw) {
2598
- if (typeof raw !== "object" || raw === null) {
2599
- return void 0;
2600
- }
2601
- const candidate = raw;
2602
- if (candidate.v !== 1 || candidate.alg !== ALGORITHM_LABEL || typeof candidate.iv !== "string" || typeof candidate.tag !== "string" || typeof candidate.ciphertext !== "string") {
2603
- return void 0;
2604
- }
2605
- return candidate;
2606
- }
2607
- __name(parseEncryptedEnvelope, "parseEncryptedEnvelope");
2608
-
2609
- // src/credential-store/encrypted-file-store.ts
2610
- function getEncryptedAuthConfigFilePath(configPath, profile) {
2611
- return path4.join(
2612
- configPath,
2613
- "config",
2614
- `${resolveAuthProfileBaseName(profile)}.enc`
2615
- );
2616
- }
2617
- __name(getEncryptedAuthConfigFilePath, "getEncryptedAuthConfigFilePath");
2618
- var EncryptedFileCredentialStore = class {
2619
- /**
2620
- * @param configPath consumer-provided global config directory (the CLI
2621
- * owns where its config lives, so workers-auth never resolves it itself).
2622
- * @param keyProvider the OS-keyring backend holding the encryption key.
2623
- * @param onPlaintextMigration optional callback invoked when a plaintext
2624
- * TOML file is migrated into the encrypted layout on first read.
2625
- * @param profile the auth profile (defaults to the active environment's
2626
- * default profile).
2627
- */
2628
- constructor(configPath, keyProvider, onPlaintextMigration, profile) {
2629
- this.configPath = configPath;
2630
- this.keyProvider = keyProvider;
2631
- this.onPlaintextMigration = onPlaintextMigration;
2632
- this.profile = profile;
2633
- }
2634
- static {
2635
- __name(this, "EncryptedFileCredentialStore");
2636
- }
2637
- kind = "encrypted-file";
2638
- read() {
2639
- const encryptedPath = getEncryptedAuthConfigFilePath(
2640
- this.configPath,
2641
- this.profile
2642
- );
2643
- if (existsSync(encryptedPath)) {
2644
- return this.readEncryptedFile(encryptedPath);
2645
- }
2646
- const plaintextPath = getAuthConfigFilePath(this.configPath, this.profile);
2647
- if (existsSync(plaintextPath)) {
2648
- return this.migrateFromPlaintext(plaintextPath, encryptedPath);
2649
- }
2650
- return void 0;
2651
- }
2652
- write(config) {
2653
- const key = this.ensureKey();
2654
- const plaintext = dist_default.stringify(config);
2655
- const envelope = encryptString(plaintext, key);
2656
- const encryptedPath = getEncryptedAuthConfigFilePath(
2657
- this.configPath,
2658
- this.profile
2659
- );
2660
- mkdirSync(path4.dirname(encryptedPath), { recursive: true });
2661
- writeFileSync(encryptedPath, JSON.stringify(envelope, null, " "), {
2662
- encoding: "utf-8",
2663
- mode: 384
2664
- });
2665
- chmodSync(encryptedPath, 384);
2666
- const plaintextPath = getAuthConfigFilePath(this.configPath, this.profile);
2667
- if (existsSync(plaintextPath)) {
2668
- rmSync(plaintextPath);
2669
- }
2670
- }
2671
- clear() {
2672
- const encryptedPath = getEncryptedAuthConfigFilePath(
2673
- this.configPath,
2674
- this.profile
2675
- );
2676
- const plaintextPath = getAuthConfigFilePath(this.configPath, this.profile);
2677
- let existed = false;
2678
- if (existsSync(encryptedPath)) {
2679
- rmSync(encryptedPath);
2680
- existed = true;
2681
- }
2682
- if (existsSync(plaintextPath)) {
2683
- rmSync(plaintextPath);
2684
- existed = true;
2685
- }
2686
- try {
2687
- this.keyProvider.deleteKey();
2688
- } catch {
2689
- }
2690
- return existed;
2691
- }
2692
- path() {
2693
- return getEncryptedAuthConfigFilePath(this.configPath, this.profile);
2694
- }
2695
- describe() {
2696
- return `Encrypted file (${getEncryptedAuthConfigFilePath(this.configPath, this.profile)}) with key in ${this.keyProvider.describe()}`;
2697
- }
2698
- /* ------------------------------------------------------------------ */
2699
- /* Internals */
2700
- /* ------------------------------------------------------------------ */
2701
- readEncryptedFile(encryptedPath) {
2702
- const key = this.keyProvider.getKey();
2703
- if (key === void 0) {
2704
- return void 0;
2705
- }
2706
- const raw = readFileSync(encryptedPath);
2707
- let envelope;
2708
- try {
2709
- envelope = parseEncryptedEnvelope(JSON.parse(raw));
2710
- } catch {
2711
- return void 0;
2712
- }
2713
- if (envelope === void 0) {
2714
- return void 0;
2715
- }
2716
- let plaintext;
2717
- try {
2718
- plaintext = decryptString(envelope, key);
2719
- } catch {
2720
- return void 0;
2721
- }
2722
- try {
2723
- return dist_default.parse(plaintext);
2724
- } catch {
2725
- return void 0;
2726
- }
2727
- }
2728
- migrateFromPlaintext(plaintextPath, encryptedPath) {
2729
- const raw = readFileSync(plaintextPath);
2730
- let plaintext;
2731
- try {
2732
- plaintext = dist_default.parse(raw);
2733
- } catch {
2734
- return void 0;
2735
- }
2736
- this.write(plaintext);
2737
- this.onPlaintextMigration?.({
2738
- plaintextPath,
2739
- encryptedPath,
2740
- keyProviderDescription: this.keyProvider.describe()
2741
- });
2742
- return plaintext;
2743
- }
2744
- /**
2745
- * Return the existing encryption key, or generate + persist a fresh
2746
- * one when none exists yet. Called from `write()` so the first
2747
- * `wrangler login --use-keyring` is fully bootstrapping.
2748
- */
2749
- ensureKey() {
2750
- const existing = this.keyProvider.getKey();
2751
- if (existing !== void 0) {
2752
- return existing;
2753
- }
2754
- const fresh = generateKey();
2755
- this.keyProvider.setKey(fresh);
2756
- return fresh;
2757
- }
2758
- };
2759
- var PINNED_KEYRING_VERSION = "1.3.0";
2760
- function defaultNpmRunner(args) {
2761
- return spawnSync("npm", args, {
2762
- encoding: "utf-8",
2763
- stdio: ["ignore", "pipe", "pipe"],
2764
- shell: process.platform === "win32"
2765
- });
2766
- }
2767
- __name(defaultNpmRunner, "defaultNpmRunner");
2768
- var npmRunner = defaultNpmRunner;
2769
- var cachedBindingPathByDir = /* @__PURE__ */ new Map();
2770
- function setNpmRunner(fn) {
2771
- npmRunner = fn ?? defaultNpmRunner;
2772
- cachedBindingPathByDir.clear();
2773
- }
2774
- __name(setNpmRunner, "setNpmRunner");
2775
- function getKeyringInstallDir(configPath) {
2776
- return path4.join(configPath, "native", "keyring");
2777
- }
2778
- __name(getKeyringInstallDir, "getKeyringInstallDir");
2779
- function getInstalledBindingPath(installDir) {
2780
- return path4.join(installDir, "node_modules", "@napi-rs", "keyring");
2781
- }
2782
- __name(getInstalledBindingPath, "getInstalledBindingPath");
2783
- function findKeyringBinding(installDir) {
2784
- const cached = cachedBindingPathByDir.get(installDir);
2785
- if (cached !== void 0) {
2786
- return cached;
2787
- }
2788
- const lazy = getInstalledBindingPath(installDir);
2789
- if (existsSync(path4.join(lazy, "index.js"))) {
2790
- cachedBindingPathByDir.set(installDir, lazy);
2791
- return lazy;
2792
- }
2793
- try {
2794
- const r = npmRunner(["root", "-g"]);
2795
- if (r.status === 0) {
2796
- const global = path4.join(r.stdout.trim(), "@napi-rs", "keyring");
2797
- if (existsSync(path4.join(global, "index.js"))) {
2798
- cachedBindingPathByDir.set(installDir, global);
2799
- return global;
2800
- }
2801
- }
2802
- } catch {
2803
- }
2804
- cachedBindingPathByDir.set(installDir, null);
2805
- return null;
2806
- }
2807
- __name(findKeyringBinding, "findKeyringBinding");
2808
- function installKeyringBindingSync(installDir) {
2809
- const dir = installDir;
2810
- mkdirSync(dir, { recursive: true });
2811
- const hostPkgJson = path4.join(dir, "package.json");
2812
- if (!existsSync(hostPkgJson)) {
2813
- writeFileSync(
2814
- hostPkgJson,
2815
- JSON.stringify(
2816
- { private: true, name: "cloudflare-auth-keyring-host" },
2817
- null,
2818
- " "
2819
- ),
2820
- "utf-8"
2821
- );
2822
- }
2823
- let r;
2824
- try {
2825
- r = npmRunner([
2826
- "install",
2827
- `@napi-rs/keyring@${PINNED_KEYRING_VERSION}`,
2828
- "--prefix",
2829
- dir,
2830
- "--no-save",
2831
- "--no-audit",
2832
- "--no-fund",
2833
- "--no-package-lock",
2834
- "--loglevel=error"
2835
- ]);
2836
- } catch (e) {
2837
- throw new UserError(
2838
- `Failed to spawn \`npm\` to install the keyring backend: ${e instanceof Error ? e.message : String(e)}
2839
-
2840
- Install \`npm\` and retry, or install the binding globally:
2841
- npm install -g @napi-rs/keyring@${PINNED_KEYRING_VERSION}`,
2842
- { telemetryMessage: "workers-auth keyring npm spawn failed" }
2843
- );
2844
- }
2845
- if (r.status !== 0) {
2846
- throw new UserError(
2847
- `Failed to install \`@napi-rs/keyring\` (npm exited ${r.status}):
2848
- ${r.stderr?.trim() ?? "(no stderr)"}
2849
-
2850
- Retry once the underlying issue is fixed, or install the binding globally:
2851
- npm install -g @napi-rs/keyring@${PINNED_KEYRING_VERSION}`,
2852
- { telemetryMessage: "workers-auth keyring npm install failed" }
2853
- );
2854
- }
2855
- cachedBindingPathByDir.delete(installDir);
2856
- }
2857
- __name(installKeyringBindingSync, "installKeyringBindingSync");
2858
- var entryFactoryOverride;
2859
- function setKeyringEntryFactory(factory) {
2860
- entryFactoryOverride = factory;
2861
- }
2862
- __name(setKeyringEntryFactory, "setKeyringEntryFactory");
2863
- var dynamicRequire = createRequire(__filename);
2864
- function resolveKeyringEntryFactory(installDir) {
2865
- if (entryFactoryOverride !== void 0) {
2866
- return entryFactoryOverride;
2867
- }
2868
- const bindingPath = findKeyringBinding(installDir);
2869
- if (bindingPath === null) {
2870
- throw new Error(
2871
- "`@napi-rs/keyring` binding not found. Call `installKeyringBindingSync()` first."
2872
- );
2873
- }
2874
- const mod = dynamicRequire(bindingPath);
2875
- return (service, account) => new mod.Entry(service, account);
2876
- }
2877
- __name(resolveKeyringEntryFactory, "resolveKeyringEntryFactory");
2878
-
2879
- // src/credential-store/key-providers/shared.ts
2880
- function getKeyringAccountName(profile) {
2881
- return resolveAuthProfileBaseName(profile);
2882
- }
2883
- __name(getKeyringAccountName, "getKeyringAccountName");
2884
- function encodeKeyEnvelope(key) {
2885
- const envelope = {
2886
- v: 1,
2887
- key: Buffer.from(key).toString("base64"),
2888
- created: (/* @__PURE__ */ new Date()).toISOString()
2889
- };
2890
- return JSON.stringify(envelope);
2891
- }
2892
- __name(encodeKeyEnvelope, "encodeKeyEnvelope");
2893
- function decodeKeyEnvelope(raw) {
2894
- if (raw === "") {
2895
- return void 0;
2896
- }
2897
- let parsed;
2898
- try {
2899
- parsed = JSON.parse(raw);
2900
- } catch {
2901
- return void 0;
2902
- }
2903
- if (typeof parsed !== "object" || parsed === null || parsed.v !== 1 || typeof parsed.key !== "string") {
2904
- return void 0;
2905
- }
2906
- try {
2907
- const buf = Buffer.from(parsed.key, "base64");
2908
- if (buf.length !== 32) {
2909
- return void 0;
2910
- }
2911
- return new Uint8Array(buf);
2912
- } catch {
2913
- return void 0;
2914
- }
2915
- }
2916
- __name(decodeKeyEnvelope, "decodeKeyEnvelope");
2917
-
2918
- // src/credential-store/key-providers/linux-secret-tool.ts
2919
- function defaultRunner(args, options = {}) {
2920
- return spawnSync("secret-tool", args, {
2921
- encoding: "utf-8",
2922
- input: options.input
2923
- });
2924
- }
2925
- __name(defaultRunner, "defaultRunner");
2926
- var runner = defaultRunner;
2927
- var cachedProbeResult = void 0;
2928
- function setLinuxSecretToolRunner(fn) {
2929
- runner = fn ?? defaultRunner;
2930
- cachedProbeResult = void 0;
2931
- }
2932
- __name(setLinuxSecretToolRunner, "setLinuxSecretToolRunner");
2933
- function probeSecretTool() {
2934
- if (cachedProbeResult !== void 0) {
2935
- return cachedProbeResult;
2936
- }
2937
- let result;
2938
- try {
2939
- const r = runner(["--version"]);
2940
- result = r.status === 0;
2941
- } catch {
2942
- result = false;
2943
- }
2944
- cachedProbeResult = result;
2945
- return result;
2946
- }
2947
- __name(probeSecretTool, "probeSecretTool");
2948
- var LinuxSecretToolKeyProvider = class {
2949
- constructor(serviceName, profile) {
2950
- this.serviceName = serviceName;
2951
- this.profile = profile;
2952
- }
2953
- static {
2954
- __name(this, "LinuxSecretToolKeyProvider");
2955
- }
2956
- getKey() {
2957
- const r = runner([
2958
- "lookup",
2959
- "service",
2960
- this.serviceName,
2961
- "account",
2962
- getKeyringAccountName(this.profile)
2963
- ]);
2964
- if (r.status === 1) {
2965
- return void 0;
2966
- }
2967
- if (r.status !== 0) {
2968
- throw new Error(
2969
- `Failed to read key via secret-tool (exit ${r.status}): ${r.stderr?.trim() ?? "(no stderr)"}`
2970
- );
2971
- }
2972
- return decodeKeyEnvelope(r.stdout.trim());
2973
- }
2974
- setKey(key) {
2975
- const r = runner(
2976
- [
2977
- "store",
2978
- "--label=Cloudflare credentials key",
2979
- "service",
2980
- this.serviceName,
2981
- "account",
2982
- getKeyringAccountName(this.profile)
2983
- ],
2984
- { input: encodeKeyEnvelope(key) }
2985
- );
2986
- if (r.status !== 0) {
2987
- throw new Error(
2988
- `Failed to write key via secret-tool (exit ${r.status}): ${r.stderr?.trim() ?? "(no stderr)"}`
2989
- );
2990
- }
2991
- }
2992
- deleteKey() {
2993
- const r = runner([
2994
- "clear",
2995
- "service",
2996
- this.serviceName,
2997
- "account",
2998
- getKeyringAccountName(this.profile)
2999
- ]);
3000
- if (r.status !== 0) {
3001
- throw new Error(
3002
- `Failed to delete key via secret-tool (exit ${r.status}): ${r.stderr?.trim() ?? "(no stderr)"}`
3003
- );
3004
- }
3005
- }
3006
- describe() {
3007
- return `Linux secret-tool (service=${this.serviceName}, account=${getKeyringAccountName(this.profile)})`;
3008
- }
3009
- };
3010
- var SECURITY_EXIT_ITEM_NOT_FOUND = 44;
3011
- function defaultRunner2(args, options = {}) {
3012
- return spawnSync("/usr/bin/security", args, {
3013
- encoding: "utf-8",
3014
- input: options.input
3015
- });
3016
- }
3017
- __name(defaultRunner2, "defaultRunner");
3018
- var runner2 = defaultRunner2;
3019
- function setMacSecurityCommandRunner(fn) {
3020
- runner2 = fn ?? defaultRunner2;
3021
- }
3022
- __name(setMacSecurityCommandRunner, "setMacSecurityCommandRunner");
3023
- var MacSecurityKeyProvider = class {
3024
- constructor(serviceName, profile) {
3025
- this.serviceName = serviceName;
3026
- this.profile = profile;
3027
- }
3028
- static {
3029
- __name(this, "MacSecurityKeyProvider");
3030
- }
3031
- getKey() {
3032
- const r = runner2([
3033
- "find-generic-password",
3034
- "-s",
3035
- this.serviceName,
3036
- "-a",
3037
- getKeyringAccountName(this.profile),
3038
- "-w"
3039
- ]);
3040
- if (r.status === SECURITY_EXIT_ITEM_NOT_FOUND) {
3041
- return void 0;
3042
- }
3043
- if (r.status !== 0) {
3044
- throw new Error(
3045
- `Failed to read key from macOS Keychain (exit ${r.status}): ${r.stderr?.trim() ?? "(no stderr)"}`
3046
- );
3047
- }
3048
- return decodeKeyEnvelope(r.stdout.trim());
3049
- }
3050
- setKey(key) {
3051
- const r = runner2([
3052
- "add-generic-password",
3053
- "-s",
3054
- this.serviceName,
3055
- "-a",
3056
- getKeyringAccountName(this.profile),
3057
- "-w",
3058
- encodeKeyEnvelope(key),
3059
- "-U"
3060
- ]);
3061
- if (r.status !== 0) {
3062
- throw new Error(
3063
- `Failed to write key to macOS Keychain (exit ${r.status}): ${r.stderr?.trim() ?? "(no stderr)"}`
3064
- );
3065
- }
3066
- }
3067
- deleteKey() {
3068
- const r = runner2([
3069
- "delete-generic-password",
3070
- "-s",
3071
- this.serviceName,
3072
- "-a",
3073
- getKeyringAccountName(this.profile)
3074
- ]);
3075
- if (r.status === 0 || r.status === SECURITY_EXIT_ITEM_NOT_FOUND) {
3076
- return;
3077
- }
3078
- throw new Error(
3079
- `Failed to delete key from macOS Keychain (exit ${r.status}): ${r.stderr?.trim() ?? "(no stderr)"}`
3080
- );
3081
- }
3082
- describe() {
3083
- return `macOS Keychain (service=${this.serviceName}, account=${getKeyringAccountName(this.profile)})`;
3084
- }
3085
- };
3086
-
3087
- // src/credential-store/key-providers/napi-keyring.ts
3088
- var NapiKeyringKeyProvider = class {
3089
- /**
3090
- * @param serviceName keyring service identifier (e.g. `"wrangler"`).
3091
- * @param installDir directory hosting the lazy-installed `@napi-rs/keyring`
3092
- * binding, derived from the consumer's config path.
3093
- * @param profile the auth profile (selects the keyring account name).
3094
- */
3095
- constructor(serviceName, installDir, profile) {
3096
- this.serviceName = serviceName;
3097
- this.installDir = installDir;
3098
- this.profile = profile;
3099
- }
3100
- static {
3101
- __name(this, "NapiKeyringKeyProvider");
3102
- }
3103
- // Resolve the entry factory (and account name) lazily on every call
3104
- // rather than caching them on construction: on Windows the native
3105
- // binding is installed *after* this provider is constructed (the
3106
- // resolver builds the provider, then runs the install), and tests
3107
- // swap the factory between operations via `setKeyringEntryFactory`.
3108
- // Caching on the instance would pin a stale/absent factory. The
3109
- // account-name lookup is a cheap env read, so recomputing is free.
3110
- entry() {
3111
- return resolveKeyringEntryFactory(this.installDir)(
3112
- this.serviceName,
3113
- getKeyringAccountName(this.profile)
3114
- );
3115
- }
3116
- getKey() {
3117
- const raw = this.entry().getPassword();
3118
- if (raw === null || raw === "") {
3119
- return void 0;
3120
- }
3121
- return decodeKeyEnvelope(raw);
3122
- }
3123
- setKey(key) {
3124
- this.entry().setPassword(encodeKeyEnvelope(key));
3125
- }
3126
- deleteKey() {
3127
- try {
3128
- this.entry().deletePassword();
3129
- } catch {
3130
- }
3131
- }
3132
- describe() {
3133
- const platformName = process.platform === "win32" ? "Windows Credential Manager" : "OS keyring";
3134
- return `${platformName} via @napi-rs/keyring (service=${this.serviceName}, account=${getKeyringAccountName(this.profile)})`;
3135
- }
3136
- };
3137
-
3138
- // src/credential-store/key-providers/factory.ts
3139
- var testProviderFactory;
3140
- function setKeyProviderFactoryForTesting(factory) {
3141
- testProviderFactory = factory;
3142
- }
3143
- __name(setKeyProviderFactoryForTesting, "setKeyProviderFactoryForTesting");
3144
- function resolveKeyProvider(serviceName, profile, configPath) {
3145
- if (testProviderFactory !== void 0) {
3146
- return {
3147
- kind: "available",
3148
- provider: testProviderFactory(serviceName, profile)
3149
- };
3150
- }
3151
- switch (process.platform) {
3152
- case "darwin":
3153
- return {
3154
- kind: "available",
3155
- provider: new MacSecurityKeyProvider(serviceName, profile)
3156
- };
3157
- case "linux":
3158
- if (probeSecretTool()) {
3159
- return {
3160
- kind: "available",
3161
- provider: new LinuxSecretToolKeyProvider(serviceName, profile)
3162
- };
3163
- }
3164
- return { kind: "unsupported" };
3165
- case "win32": {
3166
- const installDir = getKeyringInstallDir(configPath);
3167
- if (findKeyringBinding(installDir) !== null) {
3168
- return {
3169
- kind: "available",
3170
- provider: new NapiKeyringKeyProvider(
3171
- serviceName,
3172
- installDir,
3173
- profile
3174
- )
3175
- };
3176
- }
3177
- return {
3178
- kind: "needs-install",
3179
- install: /* @__PURE__ */ __name(() => installKeyringBindingSync(installDir), "install"),
3180
- afterInstall: /* @__PURE__ */ __name(() => new NapiKeyringKeyProvider(serviceName, installDir, profile), "afterInstall")
3181
- };
3182
- }
3183
- default:
3184
- return { kind: "unsupported" };
3185
- }
3186
- }
3187
- __name(resolveKeyProvider, "resolveKeyProvider");
3188
-
3189
- // src/credential-store/state.ts
3190
- var sessionFlags = {
3191
- installFailedThisSession: false,
3192
- hasWarnedAboutKeyringFallback: false,
3193
- hasWarnedAboutSecretToolMissing: false
3194
- };
3195
- function getResolverSessionFlags() {
3196
- return sessionFlags;
3197
- }
3198
- __name(getResolverSessionFlags, "getResolverSessionFlags");
3199
- function resetCredentialStorageState() {
3200
- sessionFlags.installFailedThisSession = false;
3201
- sessionFlags.hasWarnedAboutKeyringFallback = false;
3202
- sessionFlags.hasWarnedAboutSecretToolMissing = false;
3203
- }
3204
- __name(resetCredentialStorageState, "resetCredentialStorageState");
3205
- var clearCredentialStorageState = resetCredentialStorageState;
3206
-
3207
- // src/credential-store/resolver.ts
3208
- function createCredentialStorageContext(context) {
3209
- const config = {
3210
- ...context,
3211
- cliName: context.cliName ?? "your CLI"
3212
- };
3213
- function getActiveStore(profile) {
3214
- return resolveActiveCredentialStore(config, profile);
3215
- }
3216
- __name(getActiveStore, "getActiveStore");
3217
- function storageFactory(profile) {
3218
- return {
3219
- read: /* @__PURE__ */ __name(() => getActiveStore(profile).read(), "read"),
3220
- write: /* @__PURE__ */ __name((value) => getActiveStore(profile).write(value), "write"),
3221
- clear: /* @__PURE__ */ __name(() => getActiveStore(profile).clear(), "clear"),
3222
- path: /* @__PURE__ */ __name(() => getActiveStore(profile).path(), "path")
3223
- };
3224
- }
3225
- __name(storageFactory, "storageFactory");
3226
- return { storageFactory, getActiveStore };
3227
- }
3228
- __name(createCredentialStorageContext, "createCredentialStorageContext");
3229
- function resolveActiveCredentialStore(config, profile) {
3230
- const envOverride = getCloudflareAuthUseKeyringFromEnv();
3231
- const configPath = config.getConfigPath();
3232
- if (envOverride === false) {
3233
- return new FileCredentialStore(configPath, profile);
3234
- }
3235
- const forcedByEnvVar = envOverride === true;
3236
- const wantsKeyring = envOverride ?? config.isKeyringEnabled() ?? false;
3237
- if (!wantsKeyring) {
3238
- return new FileCredentialStore(configPath, profile);
3239
- }
3240
- const resolution = resolveKeyProvider(
3241
- config.serviceName,
3242
- profile,
3243
- configPath
3244
- );
3245
- switch (resolution.kind) {
3246
- case "available":
3247
- return new EncryptedFileCredentialStore(
3248
- configPath,
3249
- resolution.provider,
3250
- buildMigrationLogger(config),
3251
- profile
3252
- );
3253
- case "needs-install":
3254
- return handleNeedsInstall(resolution, forcedByEnvVar, config, profile);
3255
- case "unsupported":
3256
- return handleUnsupported(forcedByEnvVar, config, profile);
3257
- }
3258
- }
3259
- __name(resolveActiveCredentialStore, "resolveActiveCredentialStore");
3260
- function buildMigrationLogger(config) {
3261
- return (result) => {
3262
- config.logger.warn(
3263
- `Migrated credentials from ${result.plaintextPath} into ${result.encryptedPath} (key in ${result.keyProviderDescription}). The plaintext file has been deleted.`
3264
- );
3265
- };
3266
- }
3267
- __name(buildMigrationLogger, "buildMigrationLogger");
3268
- function handleNeedsInstall(resolution, forcedByEnvVar, config, profile) {
3269
- const flags = getResolverSessionFlags();
3270
- if (flags.installFailedThisSession) {
3271
- if (forcedByEnvVar) {
3272
- throw new UserError(
3273
- `CLOUDFLARE_AUTH_USE_KEYRING is set but the keyring backend could not be installed earlier this session.`,
3274
- { telemetryMessage: "workers-auth keyring install previously failed" }
3275
- );
3276
- }
3277
- return fallbackToFileWithWarning(
3278
- `The keyring backend could not be installed earlier this session; using the plaintext credentials file.`,
3279
- config,
3280
- profile
3281
- );
3282
- }
3283
- if (config.isNonInteractiveOrCI()) {
3284
- throw new UserError(windowsBindingMissingMessage(config.cliName), {
3285
- telemetryMessage: "workers-auth keyring binding not installed"
3286
- });
3287
- }
3288
- try {
3289
- config.logger.log(`\u{1F510} Installing keyring backend (one-time, ~2 MB)\u2026`);
3290
- resolution.install();
3291
- } catch (e) {
3292
- flags.installFailedThisSession = true;
3293
- if (forcedByEnvVar) {
3294
- throw e instanceof UserError ? e : new UserError(
3295
- `Failed to install the keyring backend: ${e instanceof Error ? e.message : String(e)}`,
3296
- { telemetryMessage: "workers-auth keyring install threw" }
3297
- );
3298
- }
3299
- return fallbackToFileWithWarning(
3300
- `Failed to install the keyring backend (${e instanceof Error ? e.message : String(e)}); falling back to the plaintext credentials file.`,
3301
- config,
3302
- profile
3303
- );
3304
- }
3305
- return new EncryptedFileCredentialStore(
3306
- config.getConfigPath(),
3307
- resolution.afterInstall(),
3308
- buildMigrationLogger(config),
3309
- profile
3310
- );
3311
- }
3312
- __name(handleNeedsInstall, "handleNeedsInstall");
3313
- function handleUnsupported(forcedByEnvVar, config, profile) {
3314
- const platform = process.platform;
3315
- const linuxMissingTool = platform === "linux";
3316
- const message = linuxMissingTool ? secretToolMissingMessage(config.cliName) : `OS keyring storage is not supported on \`${platform}\`; falling back to the plaintext credentials file.`;
3317
- if (forcedByEnvVar) {
3318
- throw new UserError(
3319
- linuxMissingTool ? `CLOUDFLARE_AUTH_USE_KEYRING is set but ${message}` : `CLOUDFLARE_AUTH_USE_KEYRING is set but no keyring backend is available on \`${platform}\`.`,
3320
- {
3321
- telemetryMessage: linuxMissingTool ? "workers-auth keyring secret tool missing" : "workers-auth keyring unsupported platform"
3322
- }
3323
- );
3324
- }
3325
- if (linuxMissingTool && config.isNonInteractiveOrCI()) {
3326
- throw new UserError(message, {
3327
- telemetryMessage: "workers-auth keyring secret tool missing"
3328
- });
3329
- }
3330
- const flags = getResolverSessionFlags();
3331
- if (linuxMissingTool) {
3332
- if (!flags.hasWarnedAboutSecretToolMissing) {
3333
- flags.hasWarnedAboutSecretToolMissing = true;
3334
- config.logger.warn(
3335
- `${message}
3336
-
3337
- Falling back to the plaintext credentials file for this session.`
3338
- );
3339
- }
3340
- return new FileCredentialStore(config.getConfigPath(), profile);
3341
- }
3342
- return fallbackToFileWithWarning(message, config, profile);
3343
- }
3344
- __name(handleUnsupported, "handleUnsupported");
3345
- function fallbackToFileWithWarning(message, config, profile) {
3346
- const flags = getResolverSessionFlags();
3347
- if (!flags.hasWarnedAboutKeyringFallback) {
3348
- flags.hasWarnedAboutKeyringFallback = true;
3349
- config.logger.warn(message);
3350
- }
3351
- return new FileCredentialStore(config.getConfigPath(), profile);
3352
- }
3353
- __name(fallbackToFileWithWarning, "fallbackToFileWithWarning");
3354
- function secretToolMissingMessage(cliName) {
3355
- return `\`secret-tool\` is required for OS keyring storage on Linux but is not installed.
3356
-
3357
- Install it via your package manager:
3358
- Debian/Ubuntu: sudo apt-get install libsecret-tools
3359
- Fedora/RHEL: sudo dnf install libsecret
3360
- Arch: sudo pacman -S libsecret
3361
- Alpine: apk add libsecret
3362
-
3363
- Or disable keyring storage: \`${cliName} login --no-use-keyring\`.`;
3364
- }
3365
- __name(secretToolMissingMessage, "secretToolMissingMessage");
3366
- function windowsBindingMissingMessage(cliName) {
3367
- return `\`@napi-rs/keyring\` is required for OS keyring storage on Windows but is not installed.
3368
-
3369
- Run \`${cliName} login --use-keyring\` interactively to install it automatically, or install it globally for CI:
3370
-
3371
- npm install -g @napi-rs/keyring@${PINNED_KEYRING_VERSION}
3372
-
3373
- Or disable keyring storage: \`${cliName} login --no-use-keyring\`.`;
3374
- }
3375
- __name(windowsBindingMissingMessage, "windowsBindingMissingMessage");
3376
- function scrubEncryptedCredentials(options) {
3377
- const encryptedPath = getEncryptedAuthConfigFilePath(
3378
- options.configPath,
3379
- options.profile
3380
- );
3381
- const encryptedFileExisted = existsSync(encryptedPath);
3382
- const resolution = resolveKeyProvider(
3383
- options.serviceName,
3384
- options.profile,
3385
- options.configPath
3386
- );
3387
- if (resolution.kind === "available") {
3388
- new EncryptedFileCredentialStore(
3389
- options.configPath,
3390
- resolution.provider,
3391
- void 0,
3392
- options.profile
3393
- ).clear();
3394
- return { backendAvailable: true, encryptedFileExisted };
3395
- }
3396
- if (encryptedFileExisted) {
3397
- rmSync(encryptedPath);
3398
- }
3399
- return { backendAvailable: false, encryptedFileExisted };
3400
- }
3401
- __name(scrubEncryptedCredentials, "scrubEncryptedCredentials");
3402
- /*! Bundled license information:
3403
-
3404
- smol-toml/dist/error.js:
3405
- (*!
3406
- * Copyright (c) Squirrel Chat et al., All rights reserved.
3407
- * SPDX-License-Identifier: BSD-3-Clause
3408
- *
3409
- * Redistribution and use in source and binary forms, with or without
3410
- * modification, are permitted provided that the following conditions are met:
3411
- *
3412
- * 1. Redistributions of source code must retain the above copyright notice, this
3413
- * list of conditions and the following disclaimer.
3414
- * 2. Redistributions in binary form must reproduce the above copyright notice,
3415
- * this list of conditions and the following disclaimer in the
3416
- * documentation and/or other materials provided with the distribution.
3417
- * 3. Neither the name of the copyright holder nor the names of its contributors
3418
- * may be used to endorse or promote products derived from this software without
3419
- * specific prior written permission.
3420
- *
3421
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
3422
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
3423
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3424
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
3425
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3426
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3427
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
3428
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
3429
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3430
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3431
- *)
3432
-
3433
- smol-toml/dist/util.js:
3434
- (*!
3435
- * Copyright (c) Squirrel Chat et al., All rights reserved.
3436
- * SPDX-License-Identifier: BSD-3-Clause
3437
- *
3438
- * Redistribution and use in source and binary forms, with or without
3439
- * modification, are permitted provided that the following conditions are met:
3440
- *
3441
- * 1. Redistributions of source code must retain the above copyright notice, this
3442
- * list of conditions and the following disclaimer.
3443
- * 2. Redistributions in binary form must reproduce the above copyright notice,
3444
- * this list of conditions and the following disclaimer in the
3445
- * documentation and/or other materials provided with the distribution.
3446
- * 3. Neither the name of the copyright holder nor the names of its contributors
3447
- * may be used to endorse or promote products derived from this software without
3448
- * specific prior written permission.
3449
- *
3450
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
3451
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
3452
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3453
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
3454
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3455
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3456
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
3457
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
3458
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3459
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3460
- *)
3461
-
3462
- smol-toml/dist/date.js:
3463
- (*!
3464
- * Copyright (c) Squirrel Chat et al., All rights reserved.
3465
- * SPDX-License-Identifier: BSD-3-Clause
3466
- *
3467
- * Redistribution and use in source and binary forms, with or without
3468
- * modification, are permitted provided that the following conditions are met:
3469
- *
3470
- * 1. Redistributions of source code must retain the above copyright notice, this
3471
- * list of conditions and the following disclaimer.
3472
- * 2. Redistributions in binary form must reproduce the above copyright notice,
3473
- * this list of conditions and the following disclaimer in the
3474
- * documentation and/or other materials provided with the distribution.
3475
- * 3. Neither the name of the copyright holder nor the names of its contributors
3476
- * may be used to endorse or promote products derived from this software without
3477
- * specific prior written permission.
3478
- *
3479
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
3480
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
3481
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3482
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
3483
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3484
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3485
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
3486
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
3487
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3488
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3489
- *)
3490
-
3491
- smol-toml/dist/primitive.js:
3492
- (*!
3493
- * Copyright (c) Squirrel Chat et al., All rights reserved.
3494
- * SPDX-License-Identifier: BSD-3-Clause
3495
- *
3496
- * Redistribution and use in source and binary forms, with or without
3497
- * modification, are permitted provided that the following conditions are met:
3498
- *
3499
- * 1. Redistributions of source code must retain the above copyright notice, this
3500
- * list of conditions and the following disclaimer.
3501
- * 2. Redistributions in binary form must reproduce the above copyright notice,
3502
- * this list of conditions and the following disclaimer in the
3503
- * documentation and/or other materials provided with the distribution.
3504
- * 3. Neither the name of the copyright holder nor the names of its contributors
3505
- * may be used to endorse or promote products derived from this software without
3506
- * specific prior written permission.
3507
- *
3508
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
3509
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
3510
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3511
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
3512
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3513
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3514
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
3515
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
3516
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3517
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3518
- *)
3519
-
3520
- smol-toml/dist/extract.js:
3521
- (*!
3522
- * Copyright (c) Squirrel Chat et al., All rights reserved.
3523
- * SPDX-License-Identifier: BSD-3-Clause
3524
- *
3525
- * Redistribution and use in source and binary forms, with or without
3526
- * modification, are permitted provided that the following conditions are met:
3527
- *
3528
- * 1. Redistributions of source code must retain the above copyright notice, this
3529
- * list of conditions and the following disclaimer.
3530
- * 2. Redistributions in binary form must reproduce the above copyright notice,
3531
- * this list of conditions and the following disclaimer in the
3532
- * documentation and/or other materials provided with the distribution.
3533
- * 3. Neither the name of the copyright holder nor the names of its contributors
3534
- * may be used to endorse or promote products derived from this software without
3535
- * specific prior written permission.
3536
- *
3537
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
3538
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
3539
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3540
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
3541
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3542
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3543
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
3544
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
3545
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3546
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3547
- *)
3548
-
3549
- smol-toml/dist/struct.js:
3550
- (*!
3551
- * Copyright (c) Squirrel Chat et al., All rights reserved.
3552
- * SPDX-License-Identifier: BSD-3-Clause
3553
- *
3554
- * Redistribution and use in source and binary forms, with or without
3555
- * modification, are permitted provided that the following conditions are met:
3556
- *
3557
- * 1. Redistributions of source code must retain the above copyright notice, this
3558
- * list of conditions and the following disclaimer.
3559
- * 2. Redistributions in binary form must reproduce the above copyright notice,
3560
- * this list of conditions and the following disclaimer in the
3561
- * documentation and/or other materials provided with the distribution.
3562
- * 3. Neither the name of the copyright holder nor the names of its contributors
3563
- * may be used to endorse or promote products derived from this software without
3564
- * specific prior written permission.
3565
- *
3566
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
3567
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
3568
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3569
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
3570
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3571
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3572
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
3573
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
3574
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3575
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3576
- *)
3577
-
3578
- smol-toml/dist/parse.js:
3579
- (*!
3580
- * Copyright (c) Squirrel Chat et al., All rights reserved.
3581
- * SPDX-License-Identifier: BSD-3-Clause
3582
- *
3583
- * Redistribution and use in source and binary forms, with or without
3584
- * modification, are permitted provided that the following conditions are met:
3585
- *
3586
- * 1. Redistributions of source code must retain the above copyright notice, this
3587
- * list of conditions and the following disclaimer.
3588
- * 2. Redistributions in binary form must reproduce the above copyright notice,
3589
- * this list of conditions and the following disclaimer in the
3590
- * documentation and/or other materials provided with the distribution.
3591
- * 3. Neither the name of the copyright holder nor the names of its contributors
3592
- * may be used to endorse or promote products derived from this software without
3593
- * specific prior written permission.
3594
- *
3595
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
3596
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
3597
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3598
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
3599
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3600
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3601
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
3602
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
3603
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3604
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3605
- *)
3606
-
3607
- smol-toml/dist/stringify.js:
3608
- (*!
3609
- * Copyright (c) Squirrel Chat et al., All rights reserved.
3610
- * SPDX-License-Identifier: BSD-3-Clause
3611
- *
3612
- * Redistribution and use in source and binary forms, with or without
3613
- * modification, are permitted provided that the following conditions are met:
3614
- *
3615
- * 1. Redistributions of source code must retain the above copyright notice, this
3616
- * list of conditions and the following disclaimer.
3617
- * 2. Redistributions in binary form must reproduce the above copyright notice,
3618
- * this list of conditions and the following disclaimer in the
3619
- * documentation and/or other materials provided with the distribution.
3620
- * 3. Neither the name of the copyright holder nor the names of its contributors
3621
- * may be used to endorse or promote products derived from this software without
3622
- * specific prior written permission.
3623
- *
3624
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
3625
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
3626
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3627
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
3628
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3629
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3630
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
3631
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
3632
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3633
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3634
- *)
3635
-
3636
- smol-toml/dist/index.js:
3637
- (*!
3638
- * Copyright (c) Squirrel Chat et al., All rights reserved.
3639
- * SPDX-License-Identifier: BSD-3-Clause
3640
- *
3641
- * Redistribution and use in source and binary forms, with or without
3642
- * modification, are permitted provided that the following conditions are met:
3643
- *
3644
- * 1. Redistributions of source code must retain the above copyright notice, this
3645
- * list of conditions and the following disclaimer.
3646
- * 2. Redistributions in binary form must reproduce the above copyright notice,
3647
- * this list of conditions and the following disclaimer in the
3648
- * documentation and/or other materials provided with the distribution.
3649
- * 3. Neither the name of the copyright holder nor the names of its contributors
3650
- * may be used to endorse or promote products derived from this software without
3651
- * specific prior written permission.
3652
- *
3653
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
3654
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
3655
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3656
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
3657
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3658
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3659
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
3660
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
3661
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3662
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3663
- *)
3664
- */
3665
-
3666
- export { EncryptedFileCredentialStore, FileCredentialStore, LinuxSecretToolKeyProvider, MacSecurityKeyProvider, NapiKeyringKeyProvider, PINNED_KEYRING_VERSION, PKCE_CHARSET, TEMPORARY_TERMS_NOTICE, TEMPORARY_TERMS_PROMPT, clearAccessCaches, clearCredentialStorageState, createCredentialStorageContext, createOAuthFlow, createProfileStore, decryptString, domainUsesAccess, encryptString, findKeyringBinding, generateAuthUrl, generateKey, generateRandomState, getAccessHeaders, getAuthConfigFilePath, getAuthFromEnv, getAuthUrlFromEnv, getCloudflareAPITokenFromEnv, getCloudflareAuthUseKeyringFromEnv, getCloudflareGlobalAuthEmailFromEnv, getCloudflareGlobalAuthKeyFromEnv, getEncryptedAuthConfigFilePath, getKeyringAccountName, getKeyringInstallDir, installKeyringBindingSync, parseEncryptedEnvelope, probeSecretTool, readStoredAuthState, resetCredentialStorageState, resolveKeyProvider, scrubEncryptedCredentials, setKeyProviderFactoryForTesting, setKeyringEntryFactory, setLinuxSecretToolRunner, setMacSecurityCommandRunner, setNpmRunner, validateProfileName };
1
+ export { EncryptedFileCredentialStore, FileCredentialStore, LinuxSecretToolKeyProvider, MacSecurityKeyProvider, NapiKeyringKeyProvider, PINNED_KEYRING_VERSION, PKCE_CHARSET, TEMPORARY_TERMS_NOTICE, TEMPORARY_TERMS_PROMPT, clearAccessCaches, clearCredentialStorageState, createCredentialStorageContext, createOAuthFlow, createProfileStore, decryptString, domainUsesAccess, encryptString, findKeyringBinding, generateAuthUrl, generateKey, generateRandomState, getAccessHeaders, getAuthConfigFilePath, getAuthFromEnv, getAuthUrlFromEnv, getCloudflareAPITokenFromEnv, getCloudflareAccountIdFromEnv, getCloudflareAuthUseKeyringFromEnv, getCloudflareGlobalAuthEmailFromEnv, getCloudflareGlobalAuthKeyFromEnv, getEncryptedAuthConfigFilePath, getKeyringAccountName, getKeyringInstallDir, installKeyringBindingSync, parseEncryptedEnvelope, probeSecretTool, readStoredAuthState, resetCredentialStorageState, resolveKeyProvider, scrubEncryptedCredentials, setKeyProviderFactoryForTesting, setKeyringEntryFactory, setLinuxSecretToolRunner, setMacSecurityCommandRunner, setNpmRunner, validateProfileName } from './chunk-N7JTI7BC.mjs';
2
+ import './chunk-O6YSETKJ.mjs';