@cloudflare/workers-auth 0.4.1 → 0.5.0

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