Source Map Leak in Frontend Build Artifacts: Postmortem of a Source Code Exposure Incident in an AI Coding Tool
A detailed postmortem of a source code exposure incident involving an AI coding tool's CLI client, which accidentally shipped a ~60MB source map file to a public package registry. This article explains how Source Map files can fully reconstruct original source code, why development artifacts leak into production builds, the secondary risks introduced by public object storage, and a step-by-step recovery process. It also provides a pre-publish checklist, artifact inspection script, incident response order, and actionable recommendations for teams using AI coding tools.
1. Incident Background and Classification
A CLI client for an AI coding tool was published to a public package registry with a nearly 60MB source map file included. Any developer who could access that registry only needed a simple parsing operation to fully restore a readable original source directory structure from the compressed and obfuscated artifacts, including internal module organization, helper scripts, and configuration files.
It is worth noting that this type of incident was not a first occurrence. A similar AI coding tool had experienced an identical configuration omission in an earlier version. Both incidents shared the same root cause: the boundary between development-mode artifacts and release-mode artifacts was not enforced by automation.
First, it is necessary to clarify the classification of the incident. This type of leak exposed client-side code, not server-side model weights, training data, or internal inference service implementation. Therefore, the direct risks concentrate on three areas:
- Intellectual property: internal implementation ideas, prompt organization, module naming, and architecture layering were fully obtained by external parties;
- Security: API endpoints, authentication logic, and parameter validation branches in the client code were exposed to attackers, making it easier to craft targeted inputs;
- Supply chain: the rapid propagation of mirrored repositories caused the content to escape the original publisher’s control. Subsequent deletion actions can only reduce visibility, but cannot truly retract copies that have already spread.
2. Leak Mechanism: How a Source Map File “Restores” Source Code
2.1 Prerequisites of the Package Distribution Chain
Modern CLI tools are typically distributed via package managers. Developers package their code into an installable release artifact, and users can obtain the executable entry point through a single install command. A release artifact generally contains two parts: the compressed and obfuscated main logic file, and metadata describing file location relationships.
The purpose of obfuscation is to reduce file size and increase reading difficulty. It belongs to readability protection, not access control. Obfuscation replaces variable names with short identifiers, removes whitespace, and compresses control flow, but business semantics such as string constants, API endpoints, and error messages are often still retained. This means obfuscation itself cannot be relied on as a source code protection measure.
2.2 Why Development Artifacts Enter the Release
The default behavior of build tools is usually “complete delivery.” That is, in development mode, source map files are automatically generated to allow browser debuggers, stack trace tools, and production error reporting systems to map exception stacks back to original files and line numbers.
The problem lies in the exclusion rules of the release configuration. A typical scenario is that a team starts from a default template that assumes development artifacts are used only on the local machine, so no artifact whitelist is configured. When the release process switches to a production build, the source map option is enabled, but the exclusion rules are not added. The release artifact is then uploaded as a whole, and the configuration omission goes to the public internet with the artifacts.
The following is an illustrative configuration to explain this risk:
{"scripts": {"dev": "builder dev --sourcemap","build": "builder build --sourcemap"},"files": ["dist/cli.js"]}
In the configuration above, files appears to be a whitelist, but in some packager semantics, there is an override difference between files and the artifact directory. When the entire artifact directory is uploaded, the whitelist may fail. A safer approach is to set separate artifact lists for the packaging and publishing stages, and to perform explicit validation before publishing:
{"scripts": {"build": "builder build --sourcemap=external","publish:check": "node scripts/verify-artifacts.js","prepublishOnly": "npm run build && npm run publish:check"}}
The value of lifecycle hooks like prepublishOnly is that no matter who executes the publish command, validation will run unconditionally, without relying on individual memory or manual checks.
2.3 Secondary Risks Introduced Along the Way
In addition to the source map file, the leaked artifacts also referenced a public object storage URL pointing to the complete source code directory after packaging. This shows that the impact of an incident is often not limited to a single file:
- The read permission of the object storage bucket was set to public, allowing any inferable key name to be enumerated;
- The packaged copy of the build artifacts and the release artifact formed two independent leak paths. Deleting one cannot block the other;
- The public read permission of the bucket usually comes from a historical configuration for “temporary debugging convenience,” which has gone unreviewed for a long time.
3. Recovery Principle: With the Map File, Source Code Is Plaintext
A source map file is essentially a JSON text in which two arrays correspond to each other:
sources: stores the relative paths of original files, which can directly restore the directory structure after recovery;sourcesContent: stores the complete original content of each file.
Therefore, the recovery process requires no reverse engineering techniques and is essentially an array traversal and file write operation:
import fs from "node:fs";import path from "node:path";const map = JSON.parse(fs.readFileSync("cli.js.map", "utf8"));map.sources.forEach((rel, i) => {const content = map.sourcesContent?.[i];if (content == null) return; // cannot restore when content is not inlinedconst target = path.join("restored", rel);fs.mkdirSync(path.dirname(target), { recursive: true });fs.writeFileSync(target, content);});
Two engineering details need to be added. First, whether source code is leaked depends entirely on whether the sourcesContent field is inlined. If the build configuration only retains the sources paths without inlining content, external parties can only see file paths and mapping relationships, and the restored result will be an empty shell. This also explains why “turning off source maps” and “turning off content inlining” are two different remediation actions. Second, even if inlining is turned off, the exposed file paths themselves will still leak clues about architecture layering, internal module naming, and technology stack, which is medium-sensitivity information leakage.
4. Pre-Publish Checklist
It is recommended to solidify the following checks as automated pipeline stages, with any failure interrupting the release:
- Artifact size baseline comparison. A sudden order-of-magnitude increase in artifact size compared to the previous version almost always indicates accidental file inclusion. The baseline can be persisted in CI, and exceeding a threshold (e.g., 30%) triggers an alert.
- Artifact extension blacklist scan. Iterate through the artifact list and fail if any hit on
.map,.d.ts,*.orig,*.bak,.env*,*.log,.DS_Store, or other patterns occurs. - Artifact sensitive content scan. Perform keyword and pattern matching on artifacts to identify hardcoded credentials, internal domains, private API endpoints, and internal ticket numbers.
- Package content whitelist validation. Explicitly declare the set of files allowed to be published. Any undeclared file is considered a violation, rather than relying on default ignore rules.
- Credential and key scan moved to the commit stage. Perform bidirectional scans in commit hooks and pipelines to prevent configurations from entering the version repository before they enter artifacts.
- Publish permission minimization. Use short-lived tokens for publish credentials, limited to a single package scope, to avoid long-lived tokens lingering on multiple development machines.
Below is a skeleton of an artifact check script that can be directly integrated:
import fs from "node:fs";import path from "node:path";const BLOCKED = [/\.map$/, /\.env/, /\.log$/, /\.bak$/, /\.orig$/];const MAX_SIZE_MB = 20;const files = JSON.parse(fs.readFileSync("pack-list.json", "utf8")).files;const violations = [];for (const f of files) {if (BLOCKED.some((re) => re.test(f))) violations.push(`Hit blacklist extension: ${f}`);const size = fs.statSync(f).size / 1024 / 1024;if (size > MAX_SIZE_MB) violations.push(`File size exceeds limit (${size.toFixed(1)}MB): ${f}`);}if (violations.length) {console.error(violations.join("\n"));process.exit(1);}console.log("Artifact validation passed");
5. Incident Response: Order of Operations After Discovering a Leak
Once a source map file is confirmed to have entered a public repository, the response actions should proceed in the following order, with the focus on first containing and then tracing:
- Step 1: Withdraw the release version. Mark the affected version as deprecated or delisted so that new users cannot pull artifacts containing the map file. This is containment, and it has the highest priority.
- Step 2: Block secondary paths. Check and tighten the read/write permissions of associated object storage buckets, change public read to private, and perform batch rotation of objects in the bucket if necessary.
- Step 3: Rotate credentials. If any token, cookie, or internal API endpoint appears in the artifact or referenced files, treat them as leaked and immediately revoke and re-issue.
- Step 4: Content assessment and spread assessment. Count the number of mirrored copies and download times to form an incident timeline and provide a basis for subsequent decisions.
- Step 5: Root cause fix and recurrence prevention. Integrate the validation script into the release pipeline, add lifecycle hooks, and explicitly distinguish development-mode from production-mode artifacts in the build configuration.
It should be frankly acknowledged that deletion actions cannot truly retract content that has already spread. Once a mirrored repository is pulled and redistributed in large quantities, the actual impact of the incident exceeds the publisher’s control. Therefore, resources should be prioritized for pre-publish interception rather than post-hoc cleanup. At the same time, there is no need to over-panic—client-side source code leakage does not directly lead to server-side capabilities being compromised. The real risk comes from the exposed API surface and the possible protection bypass paths that can be reverse-engineered.
6. Recommendations for Users of AI Coding Tools
For developers and teams using such tools, this case provides several actionable criteria:
- Distinguish client-side code from server-side capabilities. The publicly released client code of a tool typically has a lower value density than the server-side implementation; leak incidents affect the vendor more than the user’s existing work.
- Pay attention to version traceability. Prefer pinning version numbers rather than using a floating
latesttag. Lock the exact version in the dependency list to avoid passively importing incident-affected upstream versions into the local environment. - Disable content inlining during local builds. In self-built build configurations, explicitly disable source content inlining, retaining only the minimum necessary error mapping capability, balancing debugging efficiency with information protection.
- Establish internal artifact audit habits. Before releasing self-developed tools externally, solidify the checks from Section 4 into a template configuration so that low-level errors like “leaking a .map file” can be automatically intercepted by the pipeline rather than relying on individual diligence.
7. Conclusion
The lesson from this incident can be condensed into one sentence: the boundary between development and production must be enforced by machines, not by human memory. A source map file is an efficiency tool in debugging scenarios, but a source code snapshot in release scenarios. A single configuration omission is enough to expose the complete implementation to the public internet. Making artifact validation, permission minimization, credential rotation, and response procedures into repeatable engineering standards is the real way to converge on this type of problem.
