← Back to blog
Blog Detail

JavaScript Secret Extraction from Front-End Bundles: API Keys, Tokens, and CTEM Exposure Management

Front-end JavaScript bundles ship every hardcoded API key, token, and internal endpoint straight to the browser — and attackers grep them at scale. This CTEM guide explains how JavaScript secret extraction works, how to detect and validate exposed credentials, and how Trusteed CTEM turns bundle leaks into prioritized, actionable exposure.

Trusteed Team
Trusteed Editorial
Written On
Sep 30, 2026
Category
CTEM
Read Time
13 min read
  • CTEM
  • Trusteed
  • JavaScript Security
  • Secret Scanning
  • Attack Surface Management
  • API Security
  • Exposure Management
JavaScript Secret Extraction from Front-End Bundles: API Keys, Tokens, and CTEM Exposure Management

JavaScript Secret Extraction from Front-End Bundles: API Keys, Tokens, and CTEM Exposure Management

TL;DR

  • Everything shipped to a browser is public. Minification and bundling are packaging, not confidentiality controls.
  • Front-end secret extraction — harvesting API keys, tokens, and internal endpoints out of JavaScript bundles — is the cheapest, highest-yield move in recon, and it is fully automatable.
  • Findings are not equal. A Stripe publishable key and a Firebase apiKey are designed to be visible; a live cloud access key or an unrestricted mapping key is a real exposure with a bill and a blast radius attached.
  • The hard part is not finding candidates, it is validating which are live, scoping impact, routing to an owner, and re-checking after every deploy.
  • Trusteed CTEM treats client-side secrets as continuous exposure: discover the apps, validate candidates, suppress the noise, and push only actionable findings into the SOC queue.

Dark Trusteed CTEM insight card titled 'The bundle is a public artifact': a browser loading three JavaScript chunks reveals a plaintext API key string, three classification chips separate public-by-design, sensitive, and contextual secrets with review-scope, rotate-now, and enrich-path verdicts, and a bottom strip marks re-checking post-build, post-CDN and post-archive on a continuous loop.

What is JavaScript secret extraction?

JavaScript secret extraction is the automated harvesting and analysis of an application's client-delivered JavaScript — bundles, lazy-loaded chunks, inline scripts, web workers, service workers, and source maps — to recover credentials, tokens, endpoints, identifiers, and internal metadata that the application hands to every visitor who loads the page.

Three properties make it a distinct discipline from repo secret scanning:

  • It happens post-build, not in source. A value can be absent from Git and present in dist/. Reviewers read process.env.API_KEY; the browser receives the literal string.
  • The scope is wider than "API keys." Bundles routinely contain hardcoded bearer tokens, base64 Basic auth strings, connection strings, internal admin routes, GraphQL schemas, staging hostnames, tenant IDs, and feature-flag maps that describe unreleased functionality.
  • The artifact is already distributed. By the time you find a leak, it has been cached at a CDN, mirrored by archives, indexed by scrapers, and copied into mobile webviews and Electron builds — where it is equally extractable.

It helps to sort candidates into three classes before anyone panics:

  1. Public by design — Stripe pk_* keys, reCAPTCHA site keys, Algolia search-only keys, Firebase apiKey with locked-down security rules. Not incidents, but still needing restrictions and quota review.
  2. Sensitive — cloud provider access keys, service-account JSON, server-side payment keys, SMTP and SMS provider credentials, personal access tokens, private signing keys.
  3. Contextual — internal hostnames, non-production endpoints, verbose debug config, and role/permission maps. Individually low severity; collectively they shorten an attacker's path considerably.

Why it matters now

Framework defaults inline configuration. Next.js, Vite, Nuxt, and Create React App substitute environment variables into client code when names match specific prefixes. A single misnamed variable turns a server-side secret into a public string, and nothing in code review flags it — the source looks correct.

Source maps hand over the original code. A *.js.map file served in production reveals file structure, comments, API routes, and dependency versions. That is useful for secret hunting and for version-targeted exploitation alike.

The exposure regresses. Each deploy is a fresh opportunity to reintroduce a key through a reverted config, a dependency upgrade, or a new microservice built from a shared template. A quarterly scan is a snapshot of a moving target.

The business impact is concrete. Unrestricted API keys mean quota theft and unexpected invoices on mapping, email, SMS, and LLM providers. Cloud credentials mean lateral movement into control planes. Hardcoded admin tokens mean account takeover. Exposed internal hostnames mean a targeting map for server-side request forgery.

Audit pressure is real. PCI DSS, SOC 2, and ISO 27001 all speak to secrets management, least privilege, and change control. "The key was in the bundle" is a finding under any of them.

How attacks and risks work

The workflow has four stages, and only the last one is expensive for the defender.

1. Discovery. An attacker crawls the target, parses HTML for <script src>, handles SPA routing, and enumerates chunk manifests (_next/static/chunks/, assets/index-[hash].js). They pull .map files, check archived snapshots of the app, and unpack mobile and desktop clients that embed the same build. Subdomain enumeration matters here: staging and legacy hosts frequently ship the same bundle with more debug leftovers.

2. Extraction. Provider-specific regex patterns catch the obvious cases — cloud access key formats, payment keys, chat platform tokens, source-control tokens. Entropy scoring catches unknown formats. AST-aware passes reassemble credentials built from concatenated or base64-encoded strings. Open-source tooling does this in seconds per application.

3. Validation. This is where signal is created. A candidate becomes a finding only when someone confirms whether it is live, revoked, or restricted: a read-only vendor call where the provider permits one, an HTTP referrer check on browser keys, a security-rules check on backend-as-a-service projects, a signature and expiry check on a JSON Web Token. Skip this step and you generate hundreds of alerts, most of which are values that were always meant to be visible.

4. Exploitation. Common paths include billing and quota abuse against metered third-party APIs; data exfiltration from a backend the key unlocks; credential replay against cloud control planes; access to unreferenced admin routes; and using internal endpoint names as SSRF targets from a server-side component. The last one compounds: a single hostname disclosed in a bundle can be the pivot for a chain that never touches the front end again.

There is a supply-chain dimension too. Bundles include third-party JavaScript you did not write. Inventorying those scripts — and the keys and endpoints they reference — belongs in the same program.

Detection and visibility

Dark SOC-style insight card: a four-stage left-to-right JavaScript bundle secret pipeline — crawl owned surface, extract candidates (flagged by a gold 'bundle hash changed' badge), validate live/revoked/restricted credentials, and route via asset + owner + should_alarm — above three telemetry tiles for coverage percentage, mean time to revoke, and keys without vendor restrictions, with a should_alarm logic strip and the Trusteed Threat Research footer.

Good visibility for this exposure class looks like a pipeline, not a grep:

  • Continuous crawling of the whole owned web surface — apex domains, subdomains, staging, regional, and legacy hosts, plus the API hosts those bundles reference.
  • Bundle-hash tracking. You should know a new artifact shipped, and what changed inside it: a new key, a new endpoint, a new debug flag.
  • Candidate-to-finding validation with evidence: the exact bundle URL, the artifact hash, the matched pattern, and the outcome of a non-destructive validity check.
  • Asset and ownership linkage. Which domain, service, or team owns this artifact; which environment it runs in; whether the credential is shared across applications, which multiplies blast radius.
  • Vendor and scope enrichment. Who issued the key, what permissions it grants, and whether referrer, application, or IP restrictions are configured.
  • Source map exposure detection. A .map request returning 200 instead of 404 is its own finding.
  • Change alerts keyed to risk, not to regex hits. Only new or newly-live exposures should wake an analyst.
  • Coverage and trend metrics. Percentage of in-scope applications scanned per period, mean time from first exposure to revocation, and the count of live keys without vendor restrictions.
  • Correlation with vendor-side logs where available. Calls from unexpected referrers or ASNs are the strongest evidence that a candidate key is actively abused.

Reduce risk: best practices

  1. Treat the client bundle as a public artifact. Assume it is indexed, archived, and mirrored. If a value must remain secret, it cannot live in the browser.
  2. Audit framework inlining rules. Allowlist which environment variable prefixes may reach the client (NEXT_PUBLIC_, VITE_, REACT_APP_, PUBLIC_, NUXT_PUBLIC_) and fail the build when an unexpected prefix appears in output.
  3. Scan build output, not just source. Point secret detection at dist/, .next/, build/, out/, published static sites, and container images, not only at the repository.
  4. Move privileged calls behind a backend-for-frontend. Issue short-lived, narrowly scoped tokens from a gateway and keep long-lived vendor credentials server-side.
  5. Apply vendor-side restrictions to every browser key — HTTP referrer allowlists, application or bundle ID restrictions, IP allowlists for server keys, and least-privilege scopes.
  6. Do not publish source maps to production, or serve them only to authenticated internal users.
  7. Rotate with a plan, not a panic. Rotate, revoke the old credential at the vendor, purge CDN caches, then re-scan the same URL to confirm the artifact actually changed.
  8. Register every key in a secrets manager with an owner, purpose, environment, and rotation interval. Untracked keys are the ones that survive for years.
  9. Feed validated exposures into the SOC queue with evidence attached, so analysts are reading findings instead of reading bundles.
  10. Re-test continuously. This class of exposure regresses with every release cycle.
  11. Include non-web clients. APK, IPA, and Electron packages carry the same artifacts and deserve the same treatment.
  12. Measure outcomes — mean time to detect a new bundle exposure, mean time to revoke, and the share of live keys with restrictions configured.

How Trusteed CTEM helps

Dark Trusteed CTEM capability card titled 'From bundle artifact to actionable exposure', listing six capabilities with icons: attack surface and asset inventory, finding validation and SOC gate, exploitability context using EPSS and KEV, API surface testing worker, deep DAST worker, and continuous scan plans and reporting. Footer shows the operator console app.trusteed.io and the Trusteed Threat Research mark.

  • Continuous discovery of the apps that matter. Trusteed CTEM maps domains, subdomains, IPs, services, and technologies across your external attack surface — including the forgotten staging and legacy hosts whose bundles attackers reach first — so JavaScript extraction runs against a real, current inventory rather than a hardcoded list.
  • Validation before alarm. Candidates are validated and contextualized, and the platform's SOC gate keeps only findings with real, exploitable impact in the actionable queue, so a publishable browser key does not sit next to a live cloud credential. The result is noise reduction, not another alert stream.
  • Exploitability and threat context. Findings are enriched with catalog CVE data and EPSS/KEV context where applicable, so client-side exposure competes for remediation priority on evidence instead of on pattern matches.
  • Deeper testing where risk concentrates. A dedicated API surface worker and a deep DAST worker extend coverage beyond bundle extraction to the endpoints and application logic those exposed keys and tokens lead to.
  • Continuous scan plans, not point-in-time audits. Scheduled plans re-check artifacts after deploys, so a reintroduced key surfaces in the next cycle and is tracked as managed exposure rather than a one-off report.
  • Framework-oriented reporting. Compliance and customer-facing views let teams show auditors and stakeholders how secret exposure is discovered, validated, and remediated over time — inside app.trusteed.io alongside the rest of their exposure data.

Trusteed CTEM vs point tools

Capability Typical point tool (regex/CI secret scanner, Nuclei templates) Trusteed CTEM
Scope of discovery A repository, a CI pipeline, or a single URL you paste in External and internal attack surface inventory: domains, subdomains, IPs, services, technologies
Trigger model Point-in-time; runs when invoked Continuous scan plans, re-checked after deploys
Output Raw candidates or template hits Validated findings with evidence, asset context, and ownership
Noise handling Every pattern match becomes an alert SOC gate keeps only actionable, exploitable findings
Prioritization A severity string Exploitability context, CVE catalog data, EPSS/KEV where applicable
Depth beyond bundle extraction None API surface testing worker plus deep DAST worker for critical apps
Operator workflow CLI output or a ticket dump Dashboards and queues in app.trusteed.io
Reporting None, or a CSV export Framework-oriented compliance and customer reporting

Point tools are genuinely good at what they do: fast, cheap, scriptable signal generation. What they do not provide is the inventory that defines what should be scanned, the validation that separates noise from risk, the prioritization that decides what gets fixed first, or the continuous loop that catches regressions.

FAQ

Is an API key in JavaScript always a security issue? No. Some values are public by design — Stripe publishable keys, reCAPTCHA site keys, Firebase apiKey values with locked-down security rules. The question is whether the credential is sensitive and whether it is restricted. A live, unrestricted key with permissions beyond browser use is a real exposure. A referrer-restricted browser key still deserves scope and quota review, but it is not an incident.

Do minified bundles actually protect secrets? No. Minification shortens identifiers and strips whitespace; string literals remain intact and recoverable. If source maps are served alongside the bundle, an attacker gets the original, readable source plus comments and module boundaries. Client-side obfuscation raises effort for a human reader and barely raises it for a script.

Are source maps a real risk? They are a force multiplier. They expose original file structure, internal API paths, comments, and library versions — useful for both secret hunting and version-targeted exploitation. Restrict them to authenticated internal users, and verify that .map requests return 404 in production.

Can't we just rotate the key when it is found? Rotation is part of the fix, not the whole fix. Old artifacts remain cached at CDNs, in archives, and in third-party copies. Rotate, revoke the old credential at the vendor, purge caches, verify the artifact changed, and fix the build path so the next release does not reintroduce it.

How is this different from secret scanning in Git? Git scanning catches credentials committed to a repository. Bundle extraction catches credentials that are deployed to the internet — a different artifact, a different distribution channel, and often a different owning team. You need both. Only one of them is reachable by an attacker with curl and ten minutes.

How is CTEM different from a scanner for this problem? A scanner produces a candidate list. CTEM adds the inventory that defines what to scan, validation that confirms which candidates are live and exploitable, prioritization against business and threat context, routing to the right owner, continuous re-checking after change, and measurable outcomes. Scanner output is an input to CTEM, not a substitute for it.

What about mobile apps and desktop clients? The same bundle ships inside APKs, IPAs, and Electron applications, where extraction is straightforward after unpacking. Include client binaries in the same inventory, validation, and rotation workflow as web artifacts.

How quickly should an exposed secret be revoked? Define SLAs by class. Live and unrestricted credentials: hours, not weeks. Live but vendor-restricted: days, with evidence of the restriction attached. Public-by-design values: scope and quota review on a normal cycle. Whatever the SLA, measure actual mean time to revoke — that number is the program.

Related resources

Join Our Newsletter

Trusteed keeps you informed: emerging risks, platform updates, and practical guides for faster defense.

JavaScript Secret Extraction: Bundles, API Keys & CTEM