Source Map Leaks Expose Source Code in AI Coding Tools: Causes and Defenses

    This article examines how a nearly 60MB Source Map file shipped inside an AI coding tool's release package exposed roughly 33MB of unobfuscated TypeScript source, including permission logic, multi-agent orchestration, and an experimental module. It explains why dead code elimination does not protect source maps, assesses the resulting security and supply chain risks, and provides build-side and runtime-side defense checklists covering release gates, least privilege, sub-agent message validation, and auditing.

    When a Source Map Leak Exposed an AI Coding Tool’s Source Code

    1. What Happened: One Debug File Opened Up an Entire Platform

    During a routine dependency audit in the early hours of the morning, a security researcher found a mapping file of nearly 60MB sitting inside the release package of an AI coding tool. Recorded in Source Map v3 format, its sourcesContent field held the complete TypeScript code of over a thousand source files, stitched together verbatim: 1,900-plus TS/TSX files, roughly 33MB of unobfuscated source. Everything was readable as-is, from the tool’s permission decision logic to sub-agent orchestration, from internal project codenames to an early experimental “AI pet” feature.

    The story spread fast. Within hours, mirror projects in several public code hosting repositories had accumulated over a thousand stars and nearly two thousand forks, and almost every discussion centered on the same question: why did a compiled artifact ship with its original manuscript attached.

    It was not the first time. Back when the tool was first released as a research preview, developers had already found similar mapping files in the dependency directory. The vendor’s response at the time was textbook: urgently remove the mapping files, then delist historical versions from the package manager registry. The researcher’s recovery process was dramatic in its own right — the vendor had already cleared the local cache and the researcher was about to give up, only to notice the file was still open in an editor, and a single undo operation recovered the on-scene evidence.

    A year passed. The tool’s version number climbed from early minor releases all the way to 2.x, features multiplied several times over, yet the configuration around mapping files in the build pipeline was never hardened into an ironclad rule. As of this writing, the latest version on the package manager has been rolled back to the previous patch release — the familiar emergency-unpublish routine ran through once again.

    This cycle illustrates a fact that is easy to overlook: security is not a one-time fix, it is a constraint on the pipeline. As long as the constraint never enters the build script, never enters the CI gate, and never enters the release checklist, it will fail again in the next version, on the next branch, in the hands of the next on-call engineer.

    2. What Was Exposed: From a “CLI Tool” to an “Agent Platform”

    What leaked a year ago was essentially a simple command-line interface tool; what leaked this time is a complete agent runtime platform. The difference in scale means more than “the code was seen” — it means the architectural thinking was seen.

    2.1 Tech Stack: Selection Logic at a Glance

    • Runtime: packaged and distributed on top of a high-performance JS/TS application runtime;
    • Terminal UI: REPL and interactive components built with a React-based terminal rendering approach (Ink-style);
    • Model calls: incremental responses handled with manual streaming rather than a high-level wrapper, making it easy to control rendering and interruption token by token;
    • Type validation: full-chain schema validation with Zod v4 at the boundaries, with runtime and compile-time sharing a single definition.

    The largest single file in the source is close to 900KB (one REPL component file), the tool interface definition has 47 fields, and the permission decision pipeline sets more than 10 checkpoints. These numbers themselves show that the complexity center of gravity for this class of tools has shifted from “text completion” to “permissions, orchestration, and state management”.

    2.2 The Permission System: What 10+ Checkpoints Mean

    An AI coding tool that can read and write files, execute commands, and access the network is essentially a credentialed automation agent. The multi-checkpoint permission pipeline in the source typically covers the following layers:

    1. Parameter validity checks (whether a path escapes its bounds, whether a command is on the allowlist);
    2. Scope checks (whether operations are confined to the workspace directory);
    3. Dangerous pattern detection (recursive deletion, force push, piping into a remote script);
    4. User confirmation policy (fully automatic / confirm each time / allow by category);
    5. Audit records written to disk for later traceability.

    After a leak, what attackers most want to see is precisely the boundaries and blind spots of this decision logic. Even if no credentials are hardcoded, attackers can use it to construct stealthier bypass paths — which is why a source code leak is as dangerous as a credential leak: the visibility of defensive logic is itself an attack surface.

    2.3 Multi-Agent Orchestration: The Coordinator Only Dispatches

    The new coordination module splits “one brain” into “multiple brains plus a dispatch desk”. The coordinator itself holds only 4 tools (create agent / send message / stop task / subscribe to status), performs no concrete work, and is only responsible for dispatching and reaping.

    Its core decision is a binary choice: Continue or Spawn. The deciding factor is context overlap with existing sub-agents: if a new task shares substantial context with a running agent, it is reused; otherwise a new one is created. The engineering value of this approach lies in controlling duplicated consumption of the context window, but it also introduces a new risk surface — the message channel between sub-agents. If message bodies are not validated for provenance, any sub-agent that has been induced to act can inject instructions into other agents.

    2.4 KAIROS: Cut at Build Time, Yet Shipped with the Source Map

    More notable is the experimental module under the internal codename KAIROS. The source uses feature flags extensively: feature('KAIROS') is evaluated at bundle time, and branches returning false are completely removed by dead code elimination (DCE), so this logic is nowhere to be seen in external build artifacts.

    But it still leaked along with the source map.

    This is the most instructive technical detail of the whole incident: DCE operates on the “build output”, while a Source Map describes the “original source”. The two have different goals and different protection scopes. Many teams assume that “code being shaken out means it is protected”, but in reality, as long as the mapping file is still there, removed branches, commented-out experimental code, internal naming, and directory structure all return to the attacker intact.

    2.5 Voice, Plugins, and Skills: New Attack Surfaces from Extensibility

    • Voice interaction module: mentioned in public documentation, but implementation details had always been a black box; this time they were exposed as well;
    • Plugin and skill system: skills declare activation rules through frontmatter metadata such as allowed-tools, effort, model, and paths.

    The metadata design of the skill system is especially worth watching: allowed-tools determines which tools a skill can use, and paths determines under which file paths it is activated. Once a skill’s source is untrusted, an attacker only needs to craft a skill file that auto-activates in a specific directory and requests a high-privilege toolset, achieving a supply-chain-style attack that “triggers as soon as the project is opened”.

    3. Root Cause: Why Source Maps Ship

    Source Maps were designed to map compressed, transpiled code back to original source and line numbers in a debugger. They encode sources (source file paths), sourcesContent (source contents), mappings (position mappings), and names (symbol names) into a JSON file. By design, they are a development-time asset, not a runtime asset.

    The causes of leaks usually converge into the following categories:

    1. Bundler config defaults: some build tools enable the sourcemap option by default in development, and that setting carries all the way into the production config;
    2. Broken config inheritance and overrides: in a monorepo or multi-stage pipeline, a sub-package inherits a permissive config and the override order goes wrong;
    3. No cleanup in the release script: after artifacts are bundled, no separate step deletes the mapping files;
    4. A “size/debuggability” tradeoff: full mappings are deliberately kept for easier production troubleshooting;
    5. No release gate: CI has no assertion checking whether the artifacts contain mapping files.

    In one sentence: the problem is not the Source Map itself, but the absence of a boundary between “development assets” and “release assets”.

    4. Impact: Who Should Worry, and About What

    Risk type Concrete manifestation Affected party
    IP exposure Architecture design, internal naming, and experimental directions all made public Tool vendors
    Expanded attack surface Permission decision logic and boundary check lists become visible Users of the tool
    Supply chain risk Skill/plugin metadata rules reverse engineered, enabling malicious skills Enterprise teams
    Compliance issues If the source contains customer data or internal endpoint addresses, data compliance is implicated Regulated industries
    Trust cost Users must re-evaluate the decision to “hand over repository permissions” All users

    For users, the real lesson is this: when you hand a repository’s read/write permissions to an AI coding tool, you are actually trusting the entire build pipeline behind it. The tool’s security claims only cover the part of the code it wrote itself; they cannot cover the release habits of the dozens of dependencies behind it.

    5. Defense Checklist: Build Side

    5.1 Treat Mapping Files as Confidential Artifacts

    There must be one hard check before release. The following is an indicative gate script that can go into the release stage of a pipeline:

    1. #!/usr/bin/env bash
    2. set -euo pipefail
    3. DIST_DIR="./dist"
    4. if find "$DIST_DIR" -type f \( -name "*.map" -o -name "*.map.gz" \) | grep -q .; then
    5. echo "[FAIL] Source Map files found in release artifacts. Release blocked."
    6. find "$DIST_DIR" -type f -name "*.map" -print
    7. exit 1
    8. fi
    9. echo "[PASS] No mapping files found."

    The value of this script is not how complex it is, but that it turns a “convention” into an “assertion”. Conventions rely on people remembering; assertions rely on machines blocking.

    5.2 Distinguish “Debug Mappings” from “Source Exposure”

    If observability in production is genuinely required, the correct approach is not to keep sourcesContent, but to:

    • upload mapping files to a private error tracking service and only restore stacks by symbol on the backend;
    • keep only lightweight mappings without sourcesContent in release artifacts, or strip them entirely;
    • desensitize symbolication in error stacks returned externally, showing only file names and line numbers without backfilling source snippets.

    5.3 Truly Delete Sensitive Branches at Build Time

    Feature flags must be used together with dead code elimination, and the elimination result must be verified:

    1. // Build-time constant, inlined during bundling
    2. declare const __ENABLE_EXPERIMENTAL__: boolean;
    3. export function resolveMode(flag: string): Mode {
    4. if (__ENABLE_EXPERIMENTAL__ && flag === "INTERNAL_DEMO") {
    5. return loadExperimentalPath(); // should be fully removed by DCE when disabled
    6. }
    7. return loadStablePath();
    8. }

    The verification method is: after the build completes, search the artifacts in full text for the function name or branch string and confirm it is genuinely absent. Do not assume tree shaking always works.

    5.4 Dual Scanning of Dependencies and Artifacts

    • Audit third-party dependencies regularly, focusing on whether packages carry mapping files, test fixtures, or internal scripts;
    • Run secret scanning on your own artifacts to prevent debug logs, internal addresses, and temporary credentials from leaving along with the source;
    • Abnormal growth in artifact size is often mapping files at work, so a size threshold can also be made into a gate.

    6. Defense Checklist: Runtime and Permission Design

    A source leak is only the entry point; what really determines the size of the loss is the permission model.

    6.1 Least Privilege Plus Scope Constraints

    Tool calls should be confined to the workspace directory by default; resolve paths and normalize them before comparing prefixes, to avoid symlink and relative-path bypasses:

    1. import path from "node:path";
    2. import fs from "node:fs";
    3. function assertInsideWorkspace(target: string, workspace: string): void {
    4. const realTarget = fs.realpathSync(target);
    5. const realRoot = fs.realpathSync(workspace);
    6. const rel = path.relative(realRoot, realTarget);
    7. if (rel.startsWith("..") || path.isAbsolute(rel)) {
    8. throw new Error("Path escapes the workspace. Access denied.");
    9. }
    10. }

    6.2 Explicit Confirmation for Dangerous Operations

    Operations such as deletion, force push, formatting, bulk rewriting, and outbound network transmission should go through “second confirmation plus an impact preview” rather than executing directly. The preview should include at least: the number of affected files, markers for irreversible operations, and the rollback method.

    6.3 Provenance Validation for Sub-Agent Messages

    In multi-agent scenarios, message channels must carry a source identifier and a privilege tier. A sub-agent must not elevate its own privileges or execute a new tool merely because “a message arrived”; the dispatcher must apply quotas and depth limits to spawn requests to prevent recursive spawning from exhausting context and compute.

    6.4 Trust Tiering for Skills and Plugins

    Validate skill/plugin metadata against an allowlist: the toolset requested by allowed-tools must be a subset of the current session’s permissions; paths activation conditions may only point inside the workspace; skills from untrusted sources are disabled by default, and their requested permission list is shown before installation.

    6.5 End-to-End Auditing

    Write a parameter summary of every tool call, the decision rationale, and the user confirmation result into a logging service, and wire it into monitoring and alerting. Post-incident traceability determines whether you “review and improve” or “start guessing again”.

    7. Practical Recommendations for Teams

    1. Write the mapping file check into the release definition as a gate that cannot be skipped, with no exception even for emergency releases;
    2. Build a “development asset / release asset” inventory specifying which files may never enter the artifact repository, for example mapping files, test fixtures, internal design documents, and local environment configs;
    3. Route experimental features uniformly through feature flags plus DCE, and perform a “deletion verification” after every build;
    4. Run an admission assessment on third-party AI coding tools, focusing on the permission model, whether a read-only mode is supported, and whether self-hosting or private deployment is allowed;
    5. Converge permissions to the minimum viable set; in cloud scenarios, build audit and isolation layers with common capabilities such as object storage, message queues, container platforms, logging services, and monitoring and alerting, avoiding building “convenience” on top of “full permissions”;
    6. Rehearse regularly: assume your source leaks tomorrow — can your credential rotation, dependency audit, and impact assessment finish within a few hours?

    8. Conclusion

    The recurrence of this kind of incident is essentially not one person’s oversight, but the lack of a non-negotiable constraint in the build pipeline. A mapping file of nearly 60MB brought “experimental code already cut at compile time” back into public view, and that irony alone says enough: DCE protects the artifact, a Source Map exposes the source, and neither can substitute for the other.

    For users, it is also a reminder: handing repository permissions to an AI coding tool extends your trust to the entire supply chain behind it. Real security does not come from a tool’s marketing language, but from verifiable gates, convergeable permissions, and traceable audits. Only when those three are solid will the next “mapping file discovered in the early hours” story be someone else’s.