Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 55 additions & 5 deletions packages/plugin/src/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,28 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { resolveSourceCode } from "./source-resolver.js";

/**
* The parts of a solc build info file the explorer reads: compiler version,
* source language and EVM version.
*/
export interface ExplorerBuildInfo {
solcVersion?: string;
solcLongVersion?: string;
input: {
language?: string;
settings: {
evmVersion?: string;
};
};
}

export interface ArtifactData {
abi: unknown[];
contractName: string;
sourceName?: string;
buildInfoId?: string;
sourceCode?: string;
buildInfo?: unknown;
buildInfo?: ExplorerBuildInfo;
deployments: string[];
}

Expand All @@ -22,6 +37,39 @@ const CHAIN_ID = 31337;

let hasLoggedArtifacts = false;

/**
* Reduce a solc build info file to the fields the explorer reads.
*
* Build info carries the full standard JSON input - every source in the
* compilation job - and each contract from that job points at the same file.
* Injecting it whole repeats megabytes per contract, overflows the browser's
* localStorage quota and leaves every contract showing as unverified. Source
* resolution falls back to `input.sources`, so trim only after it has run.
*
* @param buildInfo - Parsed build info, shape unverified
* @returns The fields the explorer reads, or undefined without build info
*/
export function toExplorerBuildInfo(
buildInfo: unknown,
): ExplorerBuildInfo | undefined {
if (typeof buildInfo !== "object" || buildInfo === null) return undefined;

const { solcVersion, solcLongVersion, input } = buildInfo as {
solcVersion?: string;
solcLongVersion?: string;
input?: { language?: string; settings?: { evmVersion?: string } };
};

return {
solcVersion,
solcLongVersion,
input: {
language: input?.language,
settings: { evmVersion: input?.settings?.evmVersion },
},
};
}

export function findIgnitionDeployment(projectRoot: string): string | null {
const deploymentPath = path.join(
projectRoot,
Expand Down Expand Up @@ -112,16 +160,15 @@ export function loadArtifacts(
};

// Try to load build info
let buildInfo: unknown;
if (artifactData.buildInfoId && existsSync(buildInfoDir)) {
const buildInfoPath = path.join(
buildInfoDir,
`${artifactData.buildInfoId}.json`,
);
if (existsSync(buildInfoPath)) {
try {
artifactData.buildInfo = JSON.parse(
readFileSync(buildInfoPath, "utf-8"),
);
buildInfo = JSON.parse(readFileSync(buildInfoPath, "utf-8"));
} catch {
// Ignore build info errors
}
Expand All @@ -134,10 +181,13 @@ export function loadArtifacts(
projectRoot,
sourceName: artifactData.sourceName,
inputSourceName: artifact.inputSourceName as string | undefined,
buildInfo: artifactData.buildInfo,
buildInfo,
});
}

// Keep only the build info fields the explorer reads
artifactData.buildInfo = toExplorerBuildInfo(buildInfo);

// Store by lowercase address
addressMap[deployedAddress.toLowerCase()] = artifactData;
}
Expand Down
14 changes: 11 additions & 3 deletions packages/plugin/src/deployment-tracker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import path from "node:path";
import type { ArtifactData, AddressMap } from "./artifacts.js";
import {
toExplorerBuildInfo,
type ArtifactData,
type AddressMap,
} from "./artifacts.js";
import { resolveSourceCode } from "./source-resolver.js";

interface CompiledArtifact {
Expand Down Expand Up @@ -96,6 +100,7 @@ export class DeploymentTracker {
};

// Try to load build info (before source, which falls back to it)
let buildInfo: unknown;
if (artifact.buildInfoId) {
const buildInfoPath = path.join(
this.projectRoot,
Expand All @@ -105,7 +110,7 @@ export class DeploymentTracker {
);
if (existsSync(buildInfoPath)) {
try {
entry.buildInfo = JSON.parse(readFileSync(buildInfoPath, "utf-8"));
buildInfo = JSON.parse(readFileSync(buildInfoPath, "utf-8"));
} catch {
// ignore
}
Expand All @@ -118,10 +123,13 @@ export class DeploymentTracker {
projectRoot: this.projectRoot,
sourceName: artifact.sourceName,
inputSourceName: artifact.inputSourceName,
buildInfo: entry.buildInfo,
buildInfo,
});
}

// Keep only the build info fields the explorer reads
entry.buildInfo = toExplorerBuildInfo(buildInfo);

this.trackedDeployments[contractAddress.toLowerCase()] = entry;
}

Expand Down
43 changes: 38 additions & 5 deletions packages/plugin/src/services/webapp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,26 @@ const MIME_TYPES: Record<string, string> = {
".eot": "application/vnd.ms-fontobject",
};

/**
* localStorage key the explorer reads injected artifacts from.
*/
const ARTIFACTS_STORAGE_KEY = "OPENSCAN_ARTIFACTS_JSON_V1";

/**
* Payload size, in characters, at which injection risks exceeding the
* browser's localStorage quota. Quotas run 5-10 MB per origin and a character
* can cost 2 bytes (Chromium stores any value holding a non-Latin-1 character
* as UTF-16), so the tightest quotas fit roughly 2.5M characters.
*/
const ARTIFACTS_WARN_CHARS = 2_000_000;

/**
* Whether the oversized payload warning has been printed. Artifacts are
* re-injected on every HTML request, so an ungated warning would repeat on
* every page load.
*/
let hasWarnedPayloadSize = false;

/**
* WebappService - Custom HTTP server for serving static files
* No external dependencies - uses only Node.js built-in modules
Expand Down Expand Up @@ -217,17 +237,30 @@ export class WebappService extends Service {
return html;
}

// Double-encode: first JSON.stringify produces the data string,
// second wraps it as a safe JS string literal with proper escaping.
const jsonString = JSON.stringify(JSON.stringify(artifacts));
const payload = JSON.stringify(artifacts);

if (!hasWarnedPayloadSize && payload.length > ARTIFACTS_WARN_CHARS) {
hasWarnedPayloadSize = true;
console.warn(
`[openscan] Injected artifacts are ${(payload.length / 1_000_000).toFixed(1)}M characters, near or over the browser's localStorage quota. Contracts may show as unverified.`,
);
}

// Double-encode: the serialized payload is wrapped again as a safe JS
// string literal with proper escaping.
const jsonString = JSON.stringify(payload);

// Escape </script> to prevent premature tag closure
const safeJsonString = jsonString.replace(/<\/script>/gi, "<\\/script>");

// Remove the key before writing it, so a failed write (e.g. over quota)
// leaves no artifacts from a previous deploy mapped onto reused addresses.
// Log the error name so QuotaExceededError is recognisable at a glance.
const scriptTag =
`<script>` +
`try{localStorage.setItem("OPENSCAN_ARTIFACTS_JSON_V1",${safeJsonString})}` +
`catch(e){console.warn("[openscan] Failed to inject artifacts:",e)}` +
`try{localStorage.removeItem("${ARTIFACTS_STORAGE_KEY}");` +
`localStorage.setItem("${ARTIFACTS_STORAGE_KEY}",${safeJsonString})}` +
`catch(e){console.warn("[openscan] Failed to inject artifacts ("+e.name+"):",e)}` +
`</script>`;

return html.replace("<body>", `<body>${scriptTag}`);
Expand Down
Loading