workers-sdk / workers-auth
AGENTS.md4.6k starsChanged 6 months agoApache-2.0View on GitHub
OAuth-2.0-with-PKCE flow against Cloudflare's dash.cloudflare.com (or staging / custom-overridden) endpoints. Used by wrangler and (in future) other Cloudflare CLIs. Internal-only — published as prerelease: true. Pluggable credential persistence layer that
- Installs packages
Trending
Quiet since August.about the whole repository
Who's talking about cloudflare/workers-sdk
- cloudflare/workerd“🐛 BUG: The cache field on RequestInitializerDict is not implemented in fetch”GitHub · Apr 7, 2023 · 85 reactions
- sveltejs/kit“feat: Vite environment API”GitHub · Jul 17, 2025 · 31 reactions
- remix-run/remix“Cloudflare support for Vite”GitHub · Jan 16, 2024 · 25 reactions
- cloudflare/workerd“🐛 BUG: Workers TTFB slows down based on unused dynamic imports (additional modules)”GitHub · Mar 27, 2024 · 22 reactions
- withastro/astro“Cloudflare adapter returning [object Object]”GitHub · Oct 10, 2025 · 18 reactions
The biggest 5 of 17 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 17
Talked about on GitHub, Bluesky and Hacker News (17 times).
On GitHub · 14
- Apr 7, 2023🐛 BUG: The cache field on RequestInitializerDict is not implemented in fetch — cloudflare/workerd85 reactions · 61 comments
- Jul 17, 2025feat: Vite environment API — sveltejs/kit31 reactions · 16 comments
- Jan 16, 2024Cloudflare support for Vite — remix-run/remix25 reactions · 21 comments
- Mar 27, 2024🐛 BUG: Workers TTFB slows down based on unused dynamic imports (additional modules) — cloudflare/workerd22 reactions · 6 comments
- Oct 10, 2025Cloudflare adapter returning [object Object] — withastro/astro18 reactions · 15 comments
9 more on GitHub
- May 24, 2023Support Node Compat in Cloudflare Adaptor — sveltejs/kit17 reactions · 2 comments
- Oct 17, 2024Support Wrangler, the CLI for Cloudflare Workers — denoland/deno15 reactions · 8 comments
- Aug 10, 2026feat: `@cloudflare/vite-plugin` integration, take 2 — sveltejs/kit11 reactions · 5 comments
- Jul 22, 2023Feature Request — Runtime APIs: Superfluous throws — cloudflare/workerd11 reactions
- Oct 29, 2025Add --target=cloudflare support to bundler — oven-sh/bun8 reactions · 10 comments
- Nov 6, 2025placement just got better (finally) — cloudflare/cloudflare-docs7 reactions · 6 comments
- Oct 28, 2025vitest 4.0 fails with "TypeError: filename.replace is not a function" — withastro/astro7 reactions · 3 comments
- May 23, 2025'scopes' for Secret Store's secrets not retained in local development — cloudflare/developer-platform7 reactions · 7 comments
- Jul 23, 2024bun fetch to wrangler dev server crashes server and fails with "socket connection was closed unexpectedly" — oven-sh/bun7 reactions · 20 comments
On Bluesky · 2
- Oct 20, 2023📦 cloudflare / workers-sdk ⭐ 1,781 (+48) 🗒 TypeScript ⛅️ Home to Wrangler, the CLI for Cloudflare Workers® — @github-trending-js.bsky.social1 likes and repost
- Oct 20, 2023📦 cloudflare / workers-sdk ⭐ 1,734 (+4) 🗒 TypeScript ⛅️ Home to Wrangler, the CLI for Cloudflare Workers® — @github-trending.bsky.social1 likes and repost
On Hacker News · 1
- May 2, 2026Cloudflare Workers let you deploy serverless code instantly across the globe3 points
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository10 other files it gives its agents.
- AGENTS.mdAGENTS.md
- packages/auto-triage-bot/AGENTS.mdAGENTS.md
- packages/create-cloudflare/AGENTS.mdAGENTS.md
- packages/miniflare/AGENTS.mdAGENTS.md
- packages/vite-plugin-cloudflare/AGENTS.mdAGENTS.md
- packages/vitest-plugin/AGENTS.mdAGENTS.md
- packages/workers-utils/AGENTS.mdAGENTS.md
- packages/wrangler/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- local-explorerSkill
The file
We split this AGENTS.md into the rules it gives an agent
2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 160
No global fetch — use undici's fetch.
- Very specific: line 164
No direct Cloudflare REST API calls.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md — workers-auth
OAuth-2.0-with-PKCE flow against Cloudflare's dash.cloudflare.com (or staging /
custom-overridden) endpoints. Used by wrangler and (in future) other Cloudflare
CLIs. Internal-only — published as prerelease: true.
STRUCTURE
src/pkce.ts— PKCE code-verifier / code-challenge generation (RFC 7636)src/errors.ts—ErrorOAuth2class hierarchy +toErrorClassmappersrc/generate-auth-url.ts— authorize URL buildersrc/generate-random-state.ts— CSRF state generatorsrc/env-vars.ts—WRANGLER_*andCLOUDFLARE_AUTH_*env-var getterssrc/account-id.ts—validateAccountId(id, source), applied to every user-supplied account ID (CLOUDFLARE_ACCOUNT_ID, the consumer'saccount_idconfig field) before it reaches an API URL pathsrc/access.ts— Cloudflare Access detection + service-token /cloudflaredheaderssrc/config-file/auth.ts— theAuthConfigStorage/UserAuthConfigstorage contract (interfaces only). The default plaintext credential implementation lives alongside the credential-store layer atsrc/credential-store/file-store.ts(see "Credential storage" below). The coresrc/core/auth-config-file.ts(createAuthConfigFileHelpers({getConfigPath, format})) andsrc/core/file-storage.ts(createFileStorage(format, getPath)) build the per-profile path helpers and non-credential file stores; each CLI descriptor (src/wrangler/auth-config-file.ts,src/cf/auth-config-file.ts) binds them to its config dir +FileFormatand re-exportscreateTomlFileStorage/createJsonFileStorage,getAuthConfigFilePath, etc. from its entrypoint. See "CORE LAYER" below.src/config-file/temporary.ts—TemporaryAccountStorage/TemporaryPreviewAccountstorage contract for the temporary-preview-account flowsrc/config-file/index.ts— genericConfigStorage<T>interface shared by the auth and temporary-account contractssrc/state.ts—readStoredAuthState()+StoredAuthStateshapesrc/token-exchange.ts— auth-code → token + refresh-token rotation +fetchAuthTokensrc/callback-server.ts— local HTTP server for the OAuth callback (listens on the host/port from the consumer'sredirectUri)src/device-flow.ts—getOauthTokenViaDeviceFlow(options, ctx): the OAuth 2.0 Device Authorization Grant (RFC 8628) used bylogin({device: true})when the browser cannot reach the local callback URL. No callback server; prints the verification URL + user code and polls/oauth2/token. Every user-facing string is parameterised byctx.displayName/ctx.deviceLoginCommandso the module carries no per-CLI branding. Both endpoints' bodies are narrowed before use (asDeviceAuthorizationResponse,pollDeviceToken'sDevicePollResult) rather than cast — an intermediary's envelope or a 2xx without a grant must produce a reportableunexpected/unusable-response error, neverundefinedarithmetic.slow_down/ 5xx / 429 / unparseable bodies keep the loop alive; the last such failure is reported in place of the generic timeout if the deadline passessrc/generate-device-auth-url.ts—generateVerificationUrl(fallbackverification_uri_completebuilder for servers that omit it, RFC 8628 §3.3.1) +assertTrustedVerificationUrl, which rejects any server-supplied verification URL that is nothttps:on exactly the resolved auth domain (with no embedded credentials) before it is printed or handed toopenInBrowser— the device flow is the only place this package opens a URL it did not build itself (RFC 8628 §5.4, remote phishing)src/flow.ts—createOAuthFlow(ctx)factory wiring everything togethersrc/context.ts—OAuthFlowContextinterface (DI surface)src/credential-store/— opt-in OS-keyring-backed credential persistence (see below)src/test-helpers/— MSW handlers for consumers' tests (@cloudflare/workers-auth/test-helpers)
Credential storage (src/credential-store/)
Pluggable credential persistence layer that consumers can wire into the
OAuth flow via ctx.storageFactory. Default backend is the plaintext
TOML file (FileCredentialStore); an opt-in EncryptedFileCredentialStore
writes AES-256-GCM-encrypted credentials to a sibling .enc file using a
key held in the OS keyring. Every store is profile-aware: the file path,
the encrypted .enc path, and the keyring account name are all derived from
resolveAuthProfileBaseName(profile) (default profile → environment-based
name; named profile → the profile name), so each auth profile gets its own
files and its own encryption key.
interface.ts—CredentialStoreinterface (extendsAuthConfigStoragewithkindanddescribe())file-store.ts—FileCredentialStore(plaintext TOML, default)encrypted-file-store.ts—EncryptedFileCredentialStore+ plaintext-TOML migrationcrypto.ts— AES-256-GCMencryptString/decryptStringhelpersresolver.ts—createCredentialStorageContext({...})factory; returns{ storageFactory, getActiveStore }(both take an optionalprofile) for the consumer to plug intocreateOAuthFlow(asctx.storageFactory) andwhoami-style reporting respectivelystate.ts— module-level per-session resolver flags (one-time warnings, the Windows install-failed latch)key-providers/— per-platform OS-keyring backends that store only the 32-byte encryption key (never the credential blob itself, so the macOS Keychain 2.5 KB item limit is never a concern):interface.ts—KeyProviderinterfacemac-security.ts—/usr/bin/securityshell-outlinux-secret-tool.ts—secret-toolshell-out (probeslibsecret-tools)napi-keyring.ts—@napi-rs/keyringwincred binding on Windowslazy-installer.ts— Windows-onlynpm install @napi-rs/keyringon first opt-infactory.ts—resolveKeyProvider(serviceName)picks the right per-platform implementationshared.ts— account-name derivation + keyring JSON envelope encoding
DI SURFACE
createOAuthFlow(ctx) accepts a context object:
logger— drop-in replacement for wrangler's logger singletonisNonInteractiveOrCI()— whether to suppress interactive promptsopenInBrowser(url)— opens the browser to the OAuth authorize URLhasEnvCredentials()— short-circuits refresh logic when env-based auth is setclientId(required) — the consumer's registered OAuth app ID;stringor() => stringfor lazy (e.g. env-driven prod/staging) resolutionconsent(required) — the consumer's branded granted/denied consent pagesdisplayName(required) — the consumer's branded name ("Wrangler","cf"), interpolated into the device flow's "To authorize <name>…" copydeviceLoginCommand(required) — the command that restarts the device flow ("wrangler login --device"), quoted when a device code is denied, expires, or the flow times outredirectUri(required) — the registered redirect URI / local callback URL. The callback server's listen host/port and route path are all derived from it (per-call bind overrides viaLoginProps.callbackHost/callbackPort)storageFactory(required) — maps an auth profile to the consumer'sAuthConfigStoragetoken-persistence backend. The flow calls it with the active profile on every credential access. For keyring opt-in, pass thestorageFactoryfromcreateCredentialStorageContext(...)rather than a raw file store, so both the active profile and the encrypted-file / plaintext choice are re-resolved on every credential operation.purgeOnLoginOrLogout?()— invalidate consumer-side caches after login/logoutgenerateAuthUrl?/generateRandomState?— test overrides for deterministic snapshot tests (defaults pull from./generate-auth-url/./generate-random-state)
clientId, consent, displayName, deviceLoginCommand, redirectUri, and
storageFactory are consumer-specific, so they are required rather than
defaulted here. Wrangler's values live in the in-package wrangler layer
(src/wrangler/, see below) rather than in the wrangler package itself.
The wrangler layer (src/wrangler/index.ts, createWranglerAuth) wires the
credential-storage layer once via createCredentialStorageContext(...) and
exposes the resulting getActiveStore (called with the active profile) as
getCredentialStore() for whoami-style code that wants to surface the active
storage location.
CORE LAYER (src/core/) + PER-CLI DESCRIPTORS (src/wrangler/, src/cf/)
The whole CLI-facing auth layer (the machinery that used to live in
packages/wrangler/src/user/) is CLI-agnostic and shared by every
Cloudflare CLI built on this package. It lives in src/core/:
factory.ts—createCloudflareAuth(descriptor, ctx): OAuth flow wiring, credential storage, config cache (@cloudflare/workers-utils'createConfigCache), account selection (fetchInternalBasewith the token the flow already holds), login / logout / refresh, andrequireAuth. Imports only@cloudflare/workers-utils.types.ts—AuthContext(the injected primitives:logger,userAgent, interactiveprompt/select,isNoDefaultValueProvidedError) andCliDescriptor(everything that varies per CLI:cliName(the executable),displayName(branded name used in prose), auth command names (login/whoami/createProfile/deviceLogin),keyringServiceName,clientId,consent,redirectUri,useDeviceFlowByDefault,getConfigPath,fileFormat,accountCachePrefix,cacheNamespace,getConfigFileLabel,getDefaultScopeKeys, …).file-storage.ts(createFileStorage(format, getPath)),auth-config-file.ts(createAuthConfigFileHelpers({getConfigPath, format})),preferences.ts(createPreferences(getConfigPath)),profile-store.ts(createCloudflareProfileStore),keyring-preference.ts(createKeyringPreference),scopes.ts(shared Cloudflare scope catalog),file-format.ts,temporary-terms.ts.
File format is the FileFormat axis (src/core/file-format.ts): a simple
"toml" | "json" union (the value doubles as the file extension) plus
parseFile / stringifyFile helpers. It's threaded through createFileStorage
and the credential store (FileCredentialStore / EncryptedFileCredentialStore
/ resolver.ts all take an optional format, defaulting to "toml" so wrangler
is unchanged; the encrypted .enc sibling is format-independent). Wrangler uses
"toml"; cf uses "json".
Each CLI is a thin descriptor + entrypoint:
src/wrangler/→@cloudflare/workers-auth/wrangler:WRANGLER_CLI(TOML, wrangler's global config dir, wrangler's OAuth app /"wrangler"keyring service) +createWranglerAuth(ctx) = createCloudflareAuth(WRANGLER_CLI, ctx). Re-exports everything wrangler'ssrc/user/*imports (createTomlFileStorage,readUserPreferences,createWranglerProfileStore,setKeyringPreference, scopes,getClientIdFromEnv,OAUTH_CALLBACK_URL, …) — no re-export shim files remain inwrangler/src/user/.src/cf/→@cloudflare/workers-auth/cf:CF_CLI(JSON files under~/.config/cloudflare, the"cloudflare"keyring service,CLOUDFLARE_CLIENT_ID)createCfAuth(ctx). OAuth-app values (client IDcbca97e7-…, callback port 8877,cf-oauth-consent-*pages, scoped-token-only auth) mirror thecfCLI's registration, and device authorization is its default interactive login flow. cf carries its own scope policy (src/cf/scopes.ts): the raw client registration is kept separate from the known-grantable catalog used for validation, types, and login defaults. Requestable scopes must both appear in the client registration and resolve in the consent service's Bach catalog; registered exceptions stay explicit negative regressions. Retain separately verified, grandfathered legacy scopes and registration order. This is distinct from wrangler's smallersrc/core/scopes.tskey → description map, so cf does not re-exportDefaultScopes.
CONVENTIONS
- License: dual MIT/Apache-2.0. Files derived from BitySA/oauth2-auth-code-pkce carry the Apache-2.0 header.
- No
console.*— use the injectedctx.logger. - No global
fetch— use undici'sfetch. UserErrorinstances must carry stabletelemetryMessagelabels (<area> <sub-area> <failure>, e.g.user oauth invalid scope). These labels are part of the telemetry contract — preserve them verbatim.- No direct Cloudflare REST API calls. This package talks to OAuth endpoints
(
/oauth2/auth,/oauth2/token,/oauth2/revoke) only. - OAuth callback server listens on the host/port derived from the consumer's
required
ctx.redirectUri; override the bind address per-call viaLoginProps.callbackHost/callbackPort.
BUILD
- tsup: two entry points —
src/index.tsandsrc/test-helpers/index.ts - ESM-only output to
dist/ @cloudflare/*,undici,msw, andvitestare kept external
CREDENTIAL STORAGE NOTES
- The encrypted file uses
AES-256-GCMvianode:crypto(no third-party crypto deps). The 12-byte IV is generated fresh per write; the 16-byte GCM auth tag is verified on every read. - The keyring entry holds only a 32-byte AES key wrapped in a small JSON
envelope (
{v, key, created}). It's well under the macOS Keychain ~2.5 KB per-item limit no matter how the credential schema grows. @napi-rs/keyring(the Windows backend's native binding) is installed lazily on first opt-in vianpm installinto<configPath>/native/keyring/, whereconfigPathis the consumer-provided global config directory (seegetConfigPathbelow) — so each CLI's binding lives under its own config dir. Pinned toPINNED_KEYRING_VERSIONso CI users runningnpm install -g @napi-rs/keyringby hand get the same version as the lazy-install path.- The credential files (
.toml/.enc) and the keyring install dir are all rooted at the consumer's config directory.@cloudflare/workers-authnever resolves that path itself (wrangler and a futurecfCLI use different global config paths); instead the consumer passesgetConfigPath: () => stringintocreateCredentialStorageContext, and the path helpers (getAuthConfigFilePath/getEncryptedAuthConfigFilePath/getKeyringInstallDir) and store constructors all take it explicitly. - The consumer's
createCredentialStorageContextcall capturesserviceName,getConfigPath,isKeyringEnabled,logger,isNonInteractiveOrCI, andloginCommandin a closure. The returnedstorageFactory(profile)re-resolves the active store on every call so the active profile,--use-keyring/--no-use-keyring, and theCLOUDFLARE_AUTH_USE_KEYRINGenv var all take effect without rebuilding the OAuth flow. Per-session memoization flags (hasWarnedAboutKeyringFallback,installFailedThisSession, ...) still live at module scope instate.ts; tests useresetCredentialStorageStateto clear them between cases andsetKeyProviderFactoryForTestingto swap in stubs.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

