|
| 1 | +import "../common/logger"; |
| 2 | +import fs from "fs/promises"; |
| 3 | +import { spawn } from "child_process"; |
| 4 | +import { Request as ServerRequest, Response as ServerResponse } from "express"; |
| 5 | +import { NpmRegistryService, NpmRegistryConfigEntry } from "../services/npmRegistry"; |
| 6 | + |
| 7 | + |
| 8 | +type PackagesVersionInfo = { |
| 9 | + "dist-tags": { |
| 10 | + latest: string |
| 11 | + }, |
| 12 | + versions: { |
| 13 | + [version: string]: { |
| 14 | + dist: { |
| 15 | + tarball: string |
| 16 | + } |
| 17 | + } |
| 18 | + } |
| 19 | +}; |
| 20 | + |
| 21 | + |
| 22 | +/** |
| 23 | + * Initializes npm registry cache directory |
| 24 | + */ |
| 25 | +const CACHE_DIR = process.env.NPM_CACHE_DIR || "/tmp/npm-package-cache"; |
| 26 | +try { |
| 27 | + fs.mkdir(CACHE_DIR, { recursive: true }); |
| 28 | +} catch (error) { |
| 29 | + console.error("Error creating cache directory", error); |
| 30 | +} |
| 31 | + |
| 32 | + |
| 33 | +/** |
| 34 | + * Fetches package info from npm registry |
| 35 | + */ |
| 36 | +const fetchRegistryBasePath = "/npm/registry"; |
| 37 | +export async function fetchRegistry(request: ServerRequest, response: ServerResponse) { |
| 38 | + try { |
| 39 | + const path = request.path.replace(fetchRegistryBasePath, ""); |
| 40 | + logger.info(`Fetch registry info for path: ${path}`); |
| 41 | + |
| 42 | + const pathPackageInfo = parsePackageInfoFromPath(path); |
| 43 | + if (!pathPackageInfo) { |
| 44 | + return response.status(400).send(`Invalid package path: ${path}`); |
| 45 | + } |
| 46 | + const {organization, name} = pathPackageInfo; |
| 47 | + const packageName = organization ? `@${organization}/${name}` : name; |
| 48 | + |
| 49 | + const registryResponse = await fetchFromRegistry(packageName, path); |
| 50 | + response.json(await registryResponse.json()); |
| 51 | + } catch (error) { |
| 52 | + logger.error("Error fetching registry", error); |
| 53 | + response.status(500).send("Internal server error"); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | + |
| 58 | +/** |
| 59 | + * Fetches package files from npm registry if not yet cached |
| 60 | + */ |
| 61 | +const fetchPackageFileBasePath = "/npm/package"; |
| 62 | +export async function fetchPackageFile(request: ServerRequest, response: ServerResponse) { |
| 63 | + try { |
| 64 | + const path = request.path.replace(fetchPackageFileBasePath, ""); |
| 65 | + logger.info(`Fetch file for path: ${path}`); |
| 66 | + |
| 67 | + const pathPackageInfo = parsePackageInfoFromPath(path); |
| 68 | + if (!pathPackageInfo) { |
| 69 | + return response.status(400).send(`Invalid package path: ${path}`); |
| 70 | + } |
| 71 | + |
| 72 | + logger.info(`Fetch file for package: ${JSON.stringify(pathPackageInfo)}`); |
| 73 | + const {organization, name, version, file} = pathPackageInfo; |
| 74 | + const packageName = organization ? `@${organization}/${name}` : name; |
| 75 | + let packageVersion = version; |
| 76 | + |
| 77 | + let packageInfo: PackagesVersionInfo | null = null; |
| 78 | + if (version === "latest") { |
| 79 | + const packageInfo: PackagesVersionInfo = await fetchPackageInfo(packageName); |
| 80 | + packageVersion = packageInfo["dist-tags"].latest; |
| 81 | + } |
| 82 | + |
| 83 | + const packageBaseDir = `${CACHE_DIR}/${packageName}/${packageVersion}/package`; |
| 84 | + const packageExists = await fileExists(`${packageBaseDir}/package.json`) |
| 85 | + if (!packageExists) { |
| 86 | + if (!packageInfo) { |
| 87 | + packageInfo = await fetchPackageInfo(packageName); |
| 88 | + } |
| 89 | + |
| 90 | + if (!packageInfo || !packageInfo.versions || !packageInfo.versions[packageVersion]) { |
| 91 | + return response.status(404).send("Not found"); |
| 92 | + } |
| 93 | + |
| 94 | + const tarball = packageInfo.versions[packageVersion].dist.tarball; |
| 95 | + logger.info("Fetching tarball...", tarball); |
| 96 | + await fetchAndUnpackTarball(tarball, packageName, packageVersion); |
| 97 | + } |
| 98 | + |
| 99 | + // Fallback to index.mjs if index.js is not present |
| 100 | + if (file === "index.js" && !await fileExists(`${packageBaseDir}/${file}`)) { |
| 101 | + logger.info("Fallback to index.mjs"); |
| 102 | + return response.sendFile(`${packageBaseDir}/index.mjs`); |
| 103 | + } |
| 104 | + |
| 105 | + return response.sendFile(`${packageBaseDir}/${file}`); |
| 106 | + } catch (error) { |
| 107 | + logger.error("Error fetching package file", error); |
| 108 | + response.status(500).send("Internal server error"); |
| 109 | + } |
| 110 | +}; |
| 111 | + |
| 112 | + |
| 113 | +/** |
| 114 | + * Helpers |
| 115 | + */ |
| 116 | + |
| 117 | +function parsePackageInfoFromPath(path: string): {organization: string, name: string, version: string, file: string} | undefined { |
| 118 | + logger.info(`Parse package info from path: ${path}`); |
| 119 | + //@ts-ignore - regex groups |
| 120 | + const packageInfoRegex = /^\/?(?<fullName>(?:@(?<organization>[a-z0-9-~][a-z0-9-._~]*)\/)?(?<name>[a-z0-9-~][a-z0-9-._~]*))(?:@(?<version>[-a-z0-9><=_.^~]+))?\/(?<file>[^\r\n]*)?$/; |
| 121 | + const matches = path.match(packageInfoRegex); |
| 122 | + logger.info(`Parse package matches: ${JSON.stringify(matches)}`); |
| 123 | + if (!matches?.groups) { |
| 124 | + return; |
| 125 | + } |
| 126 | + |
| 127 | + let {organization, name, version, file} = matches.groups; |
| 128 | + version = /^\d+\.\d+\.\d+(-[\w\d]+)?/.test(version) ? version : "latest"; |
| 129 | + |
| 130 | + return {organization, name, version, file}; |
| 131 | +} |
| 132 | + |
| 133 | +function fetchFromRegistry(packageName: string, urlOrPath: string): Promise<Response> { |
| 134 | + const config: NpmRegistryConfigEntry = NpmRegistryService.getInstance().getRegistryEntryForPackage(packageName); |
| 135 | + const registryUrl = config?.registry.url; |
| 136 | + |
| 137 | + const headers: {[key: string]: string} = {}; |
| 138 | + switch (config?.registry.auth.type) { |
| 139 | + case "none": |
| 140 | + break; |
| 141 | + case "basic": |
| 142 | + const basicUserPass = config?.registry.auth?.credentials; |
| 143 | + headers["Authorization"] = `Basic ${basicUserPass}`; |
| 144 | + break; |
| 145 | + case "bearer": |
| 146 | + const bearerToken = config?.registry.auth?.credentials; |
| 147 | + headers["Authorization"] = `Bearer ${bearerToken}`; |
| 148 | + break; |
| 149 | + } |
| 150 | + |
| 151 | + let url = urlOrPath; |
| 152 | + if (!urlOrPath.startsWith("http")) { |
| 153 | + const separator = urlOrPath.startsWith("/") ? "" : "/"; |
| 154 | + url = `${registryUrl}${separator}${urlOrPath}`; |
| 155 | + } |
| 156 | + |
| 157 | + logger.debug(`Fetch from registry: ${url}`); |
| 158 | + return fetch(url, {headers}); |
| 159 | +} |
| 160 | + |
| 161 | +function fetchPackageInfo(packageName: string): Promise<PackagesVersionInfo> { |
| 162 | + return fetchFromRegistry(packageName, packageName).then(res => res.json()); |
| 163 | +} |
| 164 | + |
| 165 | +async function fetchAndUnpackTarball(url: string, packageName: string, packageVersion: string) { |
| 166 | + const response: Response = await fetchFromRegistry(packageName, url); |
| 167 | + const arrayBuffer = await response.arrayBuffer(); |
| 168 | + const buffer = Buffer.from(arrayBuffer); |
| 169 | + const path = `${CACHE_DIR}/${url.split("/").pop()}`; |
| 170 | + await fs.writeFile(path, buffer); |
| 171 | + await unpackTarball(path, packageName, packageVersion); |
| 172 | + await fs.unlink(path); |
| 173 | +} |
| 174 | + |
| 175 | +async function unpackTarball(path: string, packageName: string, packageVersion: string) { |
| 176 | + const destinationPath = `${CACHE_DIR}/${packageName}/${packageVersion}`; |
| 177 | + await fs.mkdir(destinationPath, { recursive: true }); |
| 178 | + await new Promise<void> ((resolve, reject) => { |
| 179 | + const tar = spawn("tar", ["-xvf", path, "-C", destinationPath]); |
| 180 | + tar.stdout.on("data", (data) => logger.info(data)); |
| 181 | + tar.stderr.on("data", (data) => console.error(data)); |
| 182 | + tar.on("close", (code) => { |
| 183 | + code === 0 ? resolve() : reject(); |
| 184 | + }); |
| 185 | + }); |
| 186 | +} |
| 187 | + |
| 188 | +async function fileExists(filePath: string): Promise<boolean> { |
| 189 | + try { |
| 190 | + await fs.access(filePath); |
| 191 | + return true; |
| 192 | + } catch (error) { |
| 193 | + return false; |
| 194 | + } |
| 195 | +} |
0 commit comments