import { bytesToSnapshotString } from '#universal/package-file-media.ts' import { loadPackageWasmDeniedSha256s } from './package-wasm-denylist.ts' import { getErrorMessage } from '@kody-internal/shared/error-message.ts' import { formatWasmExport, formatWasmImport, hasWasmBinaryHeader, readWasmBinaryInfo, } from '@kody-internal/shared/wasm-binary.ts' import { assertPublicHttpsUrl } from '#worker/mcp/events/ssrf.ts' import { normalizePackageWorkspacePath } from '#worker/package-registry/manifest.ts' import type { AuthoredPackageJson } from '#worker/package-registry/types.ts' import { sha256Hex } from '#worker/publish-offload/module-hashes.ts' import { packageWasmModuleMaxBytes } from '@kody-internal/shared/wasm-bundle-plugin.ts' import { assertPackageWasmSha256Allowed, buildPackageWasmR2Key, getPackageWasmBucket, readPackageWasmObject, } from './package-wasm-modules.ts' import { outboundTimeoutMs, withDeadline, } from '@kody-internal/shared/with-deadline.ts' export type PackageWasmExternal = { path: string url: string sha256: string target: 'server' | 'client' | 'both' source?: string build?: string } /** Declared `source` and `build` for one `.wasm` path. */ export type PackageWasmProvenance = { source?: string; build?: string } /** Size and import/export labels for one binary, for review output. */ export type PackageWasmBinaryLabelInfo = { byteSize: number imports: Array exports: Array } export class PackageWasmExternalError extends Error { override name = 'PackageWasmExternalError' } export const packageWasmFetchTimeoutMs = 15_000 const packageWasmFetchMaxRedirects = 5 function readPackageWasmEntries(manifest: AuthoredPackageJson) { return Object.entries(manifest.kody.wasm ?? {}).map(([path, entry]) => ({ ...entry, path: normalizePackageWorkspacePath(path), })) } /** `kody.wasm` entries with a pinned URL: binaries fetched at publish. */ export function readPackageWasmExternals( manifest: AuthoredPackageJson, ): Array { return readPackageWasmEntries(manifest).flatMap( ({ url, sha256, ...entry }) => url !== undefined && sha256 !== undefined ? [{ ...entry, url, sha256 }] : [], ) } /** Declared provenance by `.wasm` path, for URL and repo-file entries. */ export function readPackageWasmProvenance( manifest: AuthoredPackageJson, ): Map { return new Map( readPackageWasmEntries(manifest).map((entry) => [ entry.path, { source: entry.source, build: entry.build }, ]), ) } /** * `kody.wasm` entries without a URL only describe a repo file, so the path * must be one. */ export function findPackageWasmProvenanceProblems(input: { manifest: AuthoredPackageJson sourceFiles: Record }): Array { const sourcePaths = new Set( Object.keys(input.sourceFiles).map(normalizePackageWorkspacePath), ) return readPackageWasmEntries(input.manifest).flatMap((entry) => entry.url === undefined && !sourcePaths.has(entry.path) ? [ `kody.wasm "${entry.path}" has no url and is not a file in the package; add the file or a url and sha256.`, ] : [], ) } /** Import and export labels; empty when the bytes do not parse. */ export function readPackageWasmBinaryLabelInfo( bytes: Uint8Array, ): PackageWasmBinaryLabelInfo { try { const info = readWasmBinaryInfo(bytes) return { byteSize: bytes.byteLength, imports: info.imports.map(formatWasmImport), exports: info.exports.map(formatWasmExport), } } catch { return { byteSize: bytes.byteLength, imports: [], exports: [] } } } /** * One review line per binary: size, hash, where it comes from, what it * imports (its reach outside itself), what it exports, and provenance. */ export function formatPackageWasmLabel(input: { path: string sha256: string origin: string info: PackageWasmBinaryLabelInfo provenance: PackageWasmProvenance | undefined }) { const list = (values: Array) => values.length > 0 ? values.join(', ') : 'none' const { source, build } = input.provenance ?? {} const provenance = source || build ? [source && `source ${source}`, build && `build ${build}`] .filter(Boolean) .join('; ') : 'no provenance declared' return `WebAssembly ${input.path}: ${input.info.byteSize} bytes, sha256 ${input.sha256}, ${input.origin}. Imports: ${list(input.info.imports)}. Exports: ${list(input.info.exports)}. Provenance: ${provenance}.` } /** * Publish-time problems with `kody.wasm` that need no network: a path that * is also a repo file (which bytes would win is ambiguous). */ export function findPackageWasmExternalProblems(input: { externals: ReadonlyArray sourceFiles: Record }): Array { const sourcePaths = new Set( Object.keys(input.sourceFiles).map(normalizePackageWorkspacePath), ) return input.externals.flatMap((external) => { if (sourcePaths.has(external.path)) { return [ `kody.wasm "${external.path}" is also a file in the package; remove the file or the kody.wasm entry.`, ] } return [] }) } /** * Makes every external's bytes exist as a content-addressed `PACKAGE_WASM` * object. An object already stored under the pinned hash is reused without a * fetch; otherwise the bytes are fetched, verified against the pin in memory, * and written once (R2 checks the hash again on put). */ export async function storePackageWasmExternals(input: { env: Env externals: ReadonlyArray }): Promise> { const bucket = getPackageWasmBucket(input.env) const binaries = new Map() const denied = input.externals.length > 0 ? await loadPackageWasmDeniedSha256s(input.env) : new Set() for (const external of input.externals) { try { assertPackageWasmSha256Allowed(external.sha256, denied) } catch (error) { throw new PackageWasmExternalError( `kody.wasm "${external.path}": ${getErrorMessage(error)}`, ) } const key = buildPackageWasmR2Key(external.sha256) if (binaries.has(external.sha256)) continue const existing = await withDeadline( { label: 'bucket.get', timeoutMs: outboundTimeoutMs.r2 }, () => bucket.get(key), ) if (existing) { binaries.set( external.sha256, readPackageWasmBinaryLabelInfo( new Uint8Array(await existing.arrayBuffer()), ), ) continue } const bytes = await fetchPackageWasmExternal(external) await withDeadline( { label: 'bucket.put', timeoutMs: outboundTimeoutMs.r2 }, () => bucket.put(key, bytes, { sha256: external.sha256, customMetadata: { sourceUrl: external.url }, }), ) binaries.set(external.sha256, readPackageWasmBinaryLabelInfo(bytes)) } return binaries } const loadedExternalFiles = new WeakMap>>() /** * Reads stored externals as snapshot strings, the form bundler files use. * Reads sharing a request-scoped `scope` (the request's prepare cache) share * one string per binary, released with the request. */ export async function loadPackageWasmExternalFiles(input: { env: Env externals: ReadonlyArray scope: object /** Which bundle reads them; an external only joins the sides its `target` names. */ side?: 'server' | 'client' }): Promise> { const skippedTarget = input.side === 'client' ? 'server' : 'client' let loaded = loadedExternalFiles.get(input.scope) if (!loaded) { loaded = new Map() loadedExternalFiles.set(input.scope, loaded) } const files: Record = {} for (const external of input.externals) { if (external.target === skippedTarget) continue let content = loaded.get(external.sha256) if (!content) { content = readPackageWasmObject({ env: input.env, key: buildPackageWasmR2Key(external.sha256), sha256: external.sha256, }) .then((bytes) => bytesToSnapshotString(new Uint8Array(bytes), external.path), ) .catch((error: unknown) => { loaded.delete(external.sha256) throw error }) loaded.set(external.sha256, content) } files[external.path] = await content } return files } /** * Fetches one external over https with no credentials, revalidating every * redirect hop, bounded by a timeout and the per-module size cap, and * checks the bytes against the pinned SHA-256. */ export async function fetchPackageWasmExternal(input: { path: string url: string sha256: string }): Promise { const fail = (message: string): never => { throw new PackageWasmExternalError(`kody.wasm "${input.path}": ${message}`) } const validate = (value: string) => assertPublicHttpsUrl( value, 'url', (message) => new PackageWasmExternalError(`kody.wasm "${input.path}" ${message}`), ) const signal = AbortSignal.timeout(packageWasmFetchTimeoutMs) try { let url = validate(input.url) let response: Response for (let hop = 0; ; hop++) { response = await fetch(url, { redirect: 'manual', signal, headers: { accept: 'application/wasm' }, }) if (response.status < 300 || response.status >= 400) break const location = response.headers.get('location') await response.body?.cancel() if (!location) fail(`${url.href} redirected without a Location.`) if (hop >= packageWasmFetchMaxRedirects) { fail( `${input.url} redirected more than ${packageWasmFetchMaxRedirects} times.`, ) } url = validate(new URL(location!, url).href) } if (!response.ok) { await response.body?.cancel() fail(`fetching ${url.href} returned HTTP ${response.status}.`) } const bytes = await readCappedBody(response, () => fail( `${url.href} is over the ${packageWasmModuleMaxBytes} byte limit per WebAssembly module.`, ), ) const actual = await sha256Hex(bytes) if (actual !== input.sha256) { fail(`${url.href} has sha256 ${actual}, not the pinned ${input.sha256}.`) } if (!hasWasmBinaryHeader(bytes)) { fail(`${url.href} is not a WebAssembly binary.`) } return bytes } catch (error) { if (signal.aborted && !(error instanceof PackageWasmExternalError)) { fail( `fetching ${input.url} timed out after ${packageWasmFetchTimeoutMs / 1000} seconds.`, ) } throw error } } async function readCappedBody(response: Response, onOverCap: () => never) { const declared = Number(response.headers.get('content-length') ?? '0') if (declared > packageWasmModuleMaxBytes) { await response.body?.cancel() onOverCap() } const chunks: Array = [] let total = 0 const reader = response.body?.getReader() while (reader) { const { done, value } = await reader.read() if (done) break total += value.byteLength if (total > packageWasmModuleMaxBytes) { await reader.cancel() onOverCap() } chunks.push(value) } const bytes = new Uint8Array(total) let offset = 0 for (const chunk of chunks) { bytes.set(chunk, offset) offset += chunk.byteLength } return bytes }