@cloudflare/workers-auth 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- import { a as ConfigStorage, A as AuthConfigStorage, U as UserAuthConfig, f as OAuthFlowContext, g as ProfileStore } from '../file-format-Bpmgm2Po.mjs';
2
- import { C as CliDescriptor, A as AuthContext, a as CloudflareAuth, U as UserPreferences, K as KeyringPreferenceContext, S as SetKeyringPreferenceResult } from '../keyring-preference-CWjI7ct9.mjs';
3
- export { b as CloudflareLoginProps } from '../keyring-preference-CWjI7ct9.mjs';
1
+ import { a as ConfigStorage, A as AuthConfigStorage, U as UserAuthConfig, f as OAuthFlowContext, g as ProfileStore } from '../file-format-Dlt3H3sW.mjs';
2
+ import { C as CliDescriptor, A as AuthContext, a as CloudflareAuth, U as UserPreferences, K as KeyringPreferenceContext, S as SetKeyringPreferenceResult } from '../keyring-preference-B8dU564W.mjs';
3
+ export { b as CloudflareLoginProps } from '../keyring-preference-B8dU564W.mjs';
4
4
  import '@cloudflare/workers-utils';
5
5
 
6
6
  /**
package/dist/cf/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { createAuthConfigFileHelpers, createPreferences, createKeyringPreference, createFileStorage, createCloudflareAuth, createCloudflareProfileStore } from '../chunk-A6F4WXCF.mjs';
2
- import '../chunk-4CJO23DA.mjs';
1
+ import { createAuthConfigFileHelpers, createPreferences, createKeyringPreference, createFileStorage, createCloudflareAuth, createCloudflareProfileStore } from '../chunk-3U6VZT7T.mjs';
2
+ import '../chunk-XLADBZ7F.mjs';
3
3
  import { __name } from '../chunk-O6YSETKJ.mjs';
4
4
  import { getEnvironmentVariableFactory, getGlobalConfigPath, getCloudflareApiEnvironmentFromEnv } from '@cloudflare/workers-utils';
5
5
  import path from 'node:path';
@@ -1,4 +1,4 @@
1
- import { stringifyFile, parseFile, dedent, createCredentialStorageContext, createOAuthFlow, getAuthFromEnv, createProfileStore, validateAccountId, getCloudflareAccountIdFromEnv, getAuthConfigFilePath, getEncryptedAuthConfigFilePath, scrubEncryptedCredentials, validateProfileName, getCloudflareAuthUseKeyringFromEnv } from './chunk-4CJO23DA.mjs';
1
+ import { stringifyFile, parseFile, dedent, createCredentialStorageContext, createOAuthFlow, getAuthFromEnv, createProfileStore, validateAccountId, getCloudflareAccountIdFromEnv, getAuthConfigFilePath, getEncryptedAuthConfigFilePath, scrubEncryptedCredentials, validateProfileName, getCloudflareAuthUseKeyringFromEnv } from './chunk-XLADBZ7F.mjs';
2
2
  import { __name } from './chunk-O6YSETKJ.mjs';
3
3
  import { existsSync, rmSync, mkdirSync, writeFileSync, chmodSync, readFileSync as readFileSync$1, readdirSync } from 'node:fs';
4
4
  import path3 from 'node:path';
@@ -838,8 +838,8 @@ Run \`${descriptor.commands.whoami}\` to check your current authentication statu
838
838
  return credentialStorage.getActiveStore(oauthFlow.getActiveProfile());
839
839
  }
840
840
  __name(getCredentialStore, "getCredentialStore");
841
- function setTemporaryAllowed(allowed) {
842
- oauthFlow.setTemporaryAllowed(allowed);
841
+ function setTemporaryAllowed(allowed, request) {
842
+ oauthFlow.setTemporaryAllowed(allowed, request);
843
843
  }
844
844
  __name(setTemporaryAllowed, "setTemporaryAllowed");
845
845
  function getAPIToken() {
@@ -1,5 +1,5 @@
1
1
  import { __name } from './chunk-O6YSETKJ.mjs';
2
- import { getEnvironmentVariableFactory, getCloudflareApiEnvironmentFromEnv, getBooleanEnvironmentVariableFactory, UserError, readFileSync, isNonInteractiveOrCI, getCloudflareApiBaseUrl, COMPLIANCE_REGION_CONFIG_PUBLIC, FatalError, getCloudflareComplianceRegion, parseTOML } from '@cloudflare/workers-utils';
2
+ import { getEnvironmentVariableFactory, getCloudflareApiEnvironmentFromEnv, getBooleanEnvironmentVariableFactory, UserError, readFileSync, isNonInteractiveOrCI, FatalError, getCloudflareApiBaseUrl, COMPLIANCE_REGION_CONFIG_PUBLIC, getCloudflareComplianceRegion, parseTOML } from '@cloudflare/workers-utils';
3
3
  import { spawn, spawnSync } from 'node:child_process';
4
4
  import { fetch } from 'undici';
5
5
  import { webcrypto, createHash, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
@@ -410,6 +410,95 @@ var TEMPORARY_TERMS_URLS = {
410
410
  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.`;
411
411
  var TEMPORARY_TERMS_NOTICE = `Continuing means you accept Cloudflare's Terms of Service (${TEMPORARY_TERMS_URLS.termsOfService}) and Privacy Policy (${TEMPORARY_TERMS_URLS.privacyPolicy}).`;
412
412
  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.`;
413
+ var EVENT_ACCOUNT_ERRORS = /* @__PURE__ */ new Map([
414
+ [
415
+ 1035,
416
+ {
417
+ message: "The event code is malformed. Check it and try again.",
418
+ telemetryMessage: "deploy temporary event code invalid"
419
+ }
420
+ ],
421
+ [
422
+ 1036,
423
+ {
424
+ message: "The event code was not found. Check it and try again.",
425
+ telemetryMessage: "deploy temporary event not found"
426
+ }
427
+ ],
428
+ [
429
+ 1037,
430
+ {
431
+ message: "This event has not started yet.",
432
+ telemetryMessage: "deploy temporary event not started"
433
+ }
434
+ ],
435
+ [
436
+ 1038,
437
+ {
438
+ message: "This event has ended.",
439
+ telemetryMessage: "deploy temporary event expired"
440
+ }
441
+ ],
442
+ [
443
+ 1039,
444
+ {
445
+ message: "This event is disabled. Contact the event organizer.",
446
+ telemetryMessage: "deploy temporary event disabled"
447
+ }
448
+ ],
449
+ [
450
+ 1040,
451
+ {
452
+ message: "This event has no temporary accounts remaining.",
453
+ telemetryMessage: "deploy temporary event exhausted"
454
+ }
455
+ ],
456
+ [
457
+ 1041,
458
+ {
459
+ message: "The event account could not be prepared. Try again later or contact the event organizer.",
460
+ telemetryMessage: "deploy temporary event provisioning unavailable",
461
+ fatal: true
462
+ }
463
+ ]
464
+ ]);
465
+ function getResponseErrorCode(body) {
466
+ if (typeof body !== "object" || body === null || !("errors" in body)) {
467
+ return void 0;
468
+ }
469
+ const { errors } = body;
470
+ if (!Array.isArray(errors) || errors.length === 0) {
471
+ return void 0;
472
+ }
473
+ const [error] = errors;
474
+ if (typeof error !== "object" || error === null || !("code" in error)) {
475
+ return void 0;
476
+ }
477
+ return typeof error.code === "number" ? error.code : void 0;
478
+ }
479
+ __name(getResponseErrorCode, "getResponseErrorCode");
480
+ async function getEventAccountError(response) {
481
+ let body;
482
+ try {
483
+ body = await response.json();
484
+ } catch {
485
+ return void 0;
486
+ }
487
+ const errorCode = getResponseErrorCode(body);
488
+ if (errorCode === void 0) {
489
+ return void 0;
490
+ }
491
+ const eventError = EVENT_ACCOUNT_ERRORS.get(errorCode);
492
+ if (!eventError) {
493
+ return void 0;
494
+ }
495
+ const options = { telemetryMessage: eventError.telemetryMessage };
496
+ if (eventError.fatal) {
497
+ return new FatalError(eventError.message, options);
498
+ }
499
+ return new UserError(eventError.message, options);
500
+ }
501
+ __name(getEventAccountError, "getEventAccountError");
413
502
  function getTemporaryPreviewUrl() {
414
503
  return `${getCloudflareApiBaseUrl(COMPLIANCE_REGION_CONFIG_PUBLIC)}/provisioning/previews`;
415
504
  }
@@ -476,7 +565,7 @@ async function requestPowSolution(logger) {
476
565
  return solveChallenge({ challengeToken, seed, k, g });
477
566
  }
478
567
  __name(requestPowSolution, "requestPowSolution");
479
- async function createTemporaryPreviewAccount(logger) {
568
+ async function createTemporaryPreviewAccount(logger, request) {
480
569
  const pow = await requestPowSolution(logger);
481
570
  const response = await fetch(getTemporaryPreviewUrl(), {
482
571
  method: "POST",
@@ -486,10 +575,17 @@ async function createTemporaryPreviewAccount(logger) {
486
575
  privacyPolicy: TEMPORARY_TERMS_URLS.privacyPolicy,
487
576
  acceptTermsOfService: "yes",
488
577
  challengeToken: pow.challengeToken,
489
- solution: pow.solution
578
+ solution: pow.solution,
579
+ ...request?.eventCode ? { eventCode: request.eventCode } : {}
490
580
  })
491
581
  });
492
582
  if (!response.ok) {
583
+ if (request?.eventCode) {
584
+ const eventError = await getEventAccountError(response);
585
+ if (eventError) {
586
+ throw eventError;
587
+ }
588
+ }
493
589
  throw new FatalError(
494
590
  `Failed to create a temporary preview account (${response.status} ${response.statusText}).`,
495
591
  { telemetryMessage: "deploy temporary account create failed" }
@@ -511,12 +607,21 @@ async function createTemporaryPreviewAccount(logger) {
511
607
  const accountExpiresAt = previewAccount?.account?.expiresAt;
512
608
  const claimUrl = previewAccount?.claim?.url;
513
609
  const claimExpiresAt = previewAccount?.claim?.expiresAt;
610
+ const eventCodeAccepted = previewAccount?.eventCodeAccepted;
514
611
  if (accountId === void 0 || accountName === void 0 || apiToken === void 0 || accountExpiresAt === void 0 || claimUrl === void 0 || claimExpiresAt === void 0) {
515
612
  throw new FatalError(
516
613
  "Failed to create a temporary preview account because the response was missing required fields.",
517
614
  { telemetryMessage: "deploy temporary account response incomplete" }
518
615
  );
519
616
  }
617
+ if (request?.eventCode && eventCodeAccepted !== true) {
618
+ throw new FatalError(
619
+ "Failed to create a temporary preview account because the response did not acknowledge the event code.",
620
+ {
621
+ telemetryMessage: "deploy temporary event acknowledgement missing"
622
+ }
623
+ );
624
+ }
520
625
  return {
521
626
  account: {
522
627
  id: accountId,
@@ -536,6 +641,14 @@ async function getOrCreateTemporaryPreviewAccount(options) {
536
641
  options.storage
537
642
  );
538
643
  if (cachedPreviewAccount) {
644
+ if (options.request?.eventCode) {
645
+ throw new UserError(
646
+ "A temporary account is already cached. Rerun without --event-code to reuse it, or run `wrangler logout` and retry to create an account for this event.",
647
+ {
648
+ telemetryMessage: "deploy temporary event cache conflict"
649
+ }
650
+ );
651
+ }
539
652
  return { account: cachedPreviewAccount, cached: true };
540
653
  }
541
654
  const termsAccepted = await options.prompt(
@@ -548,7 +661,8 @@ async function getOrCreateTemporaryPreviewAccount(options) {
548
661
  });
549
662
  }
550
663
  const temporaryPreviewAccount = await createTemporaryPreviewAccount(
551
- options.logger
664
+ options.logger,
665
+ options.request
552
666
  );
553
667
  options.storage.write(temporaryPreviewAccount);
554
668
  return { account: temporaryPreviewAccount, cached: false };
@@ -1561,7 +1675,7 @@ function createOAuthFlow(ctx) {
1561
1675
  __name(getStorage, "getStorage");
1562
1676
  const getClientId = /* @__PURE__ */ __name(() => typeof ctx.clientId === "function" ? ctx.clientId() : ctx.clientId, "getClientId");
1563
1677
  const consent = ctx.consent;
1564
- let temporaryAllowed = false;
1678
+ let temporaryRequest;
1565
1679
  let activeTemporaryAccount;
1566
1680
  const redirectUrl = new URL(ctx.redirectUri);
1567
1681
  const defaultCallbackHost = redirectUrl.hostname;
@@ -1788,13 +1902,13 @@ function createOAuthFlow(ctx) {
1788
1902
  });
1789
1903
  }
1790
1904
  __name(requireApiTokenInternal, "requireApiTokenInternal");
1791
- function setTemporaryAllowed(allowed) {
1792
- temporaryAllowed = allowed && ctx.temporary !== void 0;
1905
+ function setTemporaryAllowed(allowed, request) {
1906
+ temporaryRequest = allowed && ctx.temporary !== void 0 ? request ?? {} : void 0;
1793
1907
  activeTemporaryAccount = void 0;
1794
1908
  }
1795
1909
  __name(setTemporaryAllowed, "setTemporaryAllowed");
1796
1910
  function isTemporaryAllowed() {
1797
- return temporaryAllowed;
1911
+ return temporaryRequest !== void 0;
1798
1912
  }
1799
1913
  __name(isTemporaryAllowed, "isTemporaryAllowed");
1800
1914
  function getActiveTemporaryAccount() {
@@ -1810,7 +1924,8 @@ function createOAuthFlow(ctx) {
1810
1924
  }
1811
1925
  const result = await getOrCreateTemporaryPreviewAccount({
1812
1926
  ...ctx.temporary,
1813
- logger: ctx.logger
1927
+ logger: ctx.logger,
1928
+ ...temporaryRequest ? { request: temporaryRequest } : {}
1814
1929
  });
1815
1930
  activeTemporaryAccount = result.account;
1816
1931
  return result;
@@ -106,6 +106,10 @@ interface OAuthFlowTemporaryContext {
106
106
  */
107
107
  prompt: (question: string, notice: string) => Promise<boolean>;
108
108
  }
109
+ /** Optional provisioning inputs for a newly-created temporary account. */
110
+ interface TemporaryAccountRequest {
111
+ eventCode?: string;
112
+ }
109
113
  /**
110
114
  * The branded OAuth consent pages the provider redirects the browser to after
111
115
  * the user grants or denies consent.
@@ -379,7 +383,7 @@ interface OAuthFlowAPI {
379
383
  * process (e.g. in tests) — each invocation starts a fresh temporary session.
380
384
  * No-op when the flow was created without a `temporary` context.
381
385
  */
382
- setTemporaryAllowed(allowed: boolean): void;
386
+ setTemporaryAllowed(allowed: boolean, request?: TemporaryAccountRequest): void;
383
387
  /**
384
388
  * Whether `--temporary` is permitted for this invocation (see
385
389
  * {@link setTemporaryAllowed}). Always `false` without a `temporary` context.
@@ -491,4 +495,4 @@ interface CredentialStore extends AuthConfigStorage {
491
495
  */
492
496
  type FileFormat = "toml" | "json";
493
497
 
494
- export { type AuthConfigStorage as A, type CredentialStore as C, type DeactivateDirectoryResult as D, type FileFormat as F, type LoginOrRefreshFailureReason as L, type OAuthFlowLogger as O, type ProfileConfigOperations as P, type TemporaryPreviewAccount as T, type UserAuthConfig as U, type ConfigStorage as a, type DirectoryBindingOperations as b, type DirectoryBindingsStorage as c, type LoginOrRefreshResult as d, type LoginProps as e, type OAuthFlowContext as f, type ProfileStore as g, createOAuthFlow as h, createProfileStore as i, generateAuthUrl as j, generateRandomState as k, type OAuthConsentPages as l, validateProfileName as v };
498
+ export { type AuthConfigStorage as A, type CredentialStore as C, type DeactivateDirectoryResult as D, type FileFormat as F, type LoginOrRefreshFailureReason as L, type OAuthFlowLogger as O, type ProfileConfigOperations as P, type TemporaryAccountRequest as T, type UserAuthConfig as U, type ConfigStorage as a, type DirectoryBindingOperations as b, type DirectoryBindingsStorage as c, type LoginOrRefreshResult as d, type LoginProps as e, type OAuthFlowContext as f, type ProfileStore as g, type TemporaryPreviewAccount as h, createOAuthFlow as i, createProfileStore as j, generateAuthUrl as k, generateRandomState as l, type OAuthConsentPages as m, validateProfileName as v };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { O as OAuthFlowLogger, U as UserAuthConfig, A as AuthConfigStorage, C as CredentialStore, F as FileFormat } from './file-format-Bpmgm2Po.mjs';
2
- export { a as ConfigStorage, D as DeactivateDirectoryResult, b as DirectoryBindingOperations, c as DirectoryBindingsStorage, L as LoginOrRefreshFailureReason, d as LoginOrRefreshResult, e as LoginProps, f as OAuthFlowContext, P as ProfileConfigOperations, g as ProfileStore, T as TemporaryPreviewAccount, h as createOAuthFlow, i as createProfileStore, j as generateAuthUrl, k as generateRandomState, v as validateProfileName } from './file-format-Bpmgm2Po.mjs';
1
+ import { O as OAuthFlowLogger, U as UserAuthConfig, A as AuthConfigStorage, C as CredentialStore, F as FileFormat } from './file-format-Dlt3H3sW.mjs';
2
+ export { a as ConfigStorage, D as DeactivateDirectoryResult, b as DirectoryBindingOperations, c as DirectoryBindingsStorage, L as LoginOrRefreshFailureReason, d as LoginOrRefreshResult, e as LoginProps, f as OAuthFlowContext, P as ProfileConfigOperations, g as ProfileStore, T as TemporaryAccountRequest, h as TemporaryPreviewAccount, i as createOAuthFlow, j as createProfileStore, k as generateAuthUrl, l as generateRandomState, v as validateProfileName } from './file-format-Dlt3H3sW.mjs';
3
3
  import { ApiCredentials } from '@cloudflare/workers-utils';
4
4
  import { SpawnSyncReturns } from 'node:child_process';
5
5
 
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- export { EncryptedFileCredentialStore, FileCredentialStore, LinuxSecretToolKeyProvider, MacSecurityKeyProvider, NapiKeyringKeyProvider, PINNED_KEYRING_VERSION, PKCE_CHARSET, TEMPORARY_TERMS_NOTICE, TEMPORARY_TERMS_PROMPT, clearAccessCaches, clearCredentialStorageState, createCredentialStorageContext, createOAuthFlow, createProfileStore, decryptString, domainUsesAccess, encryptString, findKeyringBinding, generateAuthUrl, generateKey, generateRandomState, generateVerificationUrl, getAccessHeaders, getAuthConfigFilePath, getAuthFromEnv, getAuthUrlFromEnv, getCloudflareAPITokenFromEnv, getCloudflareAccountIdFromEnv, getCloudflareAuthUseKeyringFromEnv, getCloudflareGlobalAuthEmailFromEnv, getCloudflareGlobalAuthKeyFromEnv, getEncryptedAuthConfigFilePath, getKeyringAccountName, getKeyringInstallDir, installKeyringBindingSync, parseEncryptedEnvelope, probeSecretTool, readStoredAuthState, resetCredentialStorageState, resolveKeyProvider, scrubEncryptedCredentials, setKeyProviderFactoryForTesting, setKeyringEntryFactory, setLinuxSecretToolRunner, setMacSecurityCommandRunner, setNpmRunner, validateProfileName } from './chunk-4CJO23DA.mjs';
1
+ export { EncryptedFileCredentialStore, FileCredentialStore, LinuxSecretToolKeyProvider, MacSecurityKeyProvider, NapiKeyringKeyProvider, PINNED_KEYRING_VERSION, PKCE_CHARSET, TEMPORARY_TERMS_NOTICE, TEMPORARY_TERMS_PROMPT, clearAccessCaches, clearCredentialStorageState, createCredentialStorageContext, createOAuthFlow, createProfileStore, decryptString, domainUsesAccess, encryptString, findKeyringBinding, generateAuthUrl, generateKey, generateRandomState, generateVerificationUrl, getAccessHeaders, getAuthConfigFilePath, getAuthFromEnv, getAuthUrlFromEnv, getCloudflareAPITokenFromEnv, getCloudflareAccountIdFromEnv, getCloudflareAuthUseKeyringFromEnv, getCloudflareGlobalAuthEmailFromEnv, getCloudflareGlobalAuthKeyFromEnv, getEncryptedAuthConfigFilePath, getKeyringAccountName, getKeyringInstallDir, installKeyringBindingSync, parseEncryptedEnvelope, probeSecretTool, readStoredAuthState, resetCredentialStorageState, resolveKeyProvider, scrubEncryptedCredentials, setKeyProviderFactoryForTesting, setKeyringEntryFactory, setLinuxSecretToolRunner, setMacSecurityCommandRunner, setNpmRunner, validateProfileName } from './chunk-XLADBZ7F.mjs';
2
2
  import './chunk-O6YSETKJ.mjs';
@@ -1,4 +1,4 @@
1
- import { f as OAuthFlowContext, l as OAuthConsentPages, F as FileFormat, C as CredentialStore, d as LoginOrRefreshResult, U as UserAuthConfig } from './file-format-Bpmgm2Po.mjs';
1
+ import { f as OAuthFlowContext, m as OAuthConsentPages, F as FileFormat, C as CredentialStore, T as TemporaryAccountRequest, d as LoginOrRefreshResult, U as UserAuthConfig } from './file-format-Dlt3H3sW.mjs';
2
2
  import { ApiCredentials, ComplianceConfig } from '@cloudflare/workers-utils';
3
3
 
4
4
  /** Minimal shape of the interactive `select` prompt's options for account selection. */
@@ -148,7 +148,7 @@ interface CloudflareAuth {
148
148
  /** The currently-active credential store for the active profile. */
149
149
  getCredentialStore: () => CredentialStore;
150
150
  /** Mark whether `--temporary` is permitted for the current invocation. */
151
- setTemporaryAllowed: (allowed: boolean) => void;
151
+ setTemporaryAllowed: (allowed: boolean, request?: TemporaryAccountRequest) => void;
152
152
  /** Resolve API credentials (env / temporary account / stored OAuth token). */
153
153
  getAPIToken: () => ApiCredentials | undefined;
154
154
  /** Throw an error if there is no API token available. */