Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | 7x 7x 7x 7x 7x 7x 11x 11x 11x 11x 3x 3x 7x 7x 11x 11x 13x 13x 13x 1x 1x 12x 1x 1x 11x 10x 2x 2x 8x 1x 1x 7x 7x 7x 7x 7x 1x 1x 1x 6x 7x 7x 11x 11x 8x 6x 6x 1x 1x 1x 5x 5x 1x 4x 4x 4x 4x 4x 2x 2x 1x 3x 3x 11x 11x 11x 11x 5x 6x 6x 6x 6x 6x 6x 6x 6x 1x 5x 4x 2x 6x 3x 3x 3x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 7x 20x 6x 14x 11x 3x 3x 7x 7x | // Copyright 2026 ForgeKit Contributors
// SPDX-License-Identifier: Apache-2.0
// https://github.com/SubhanshuMG/ForgeKit
import * as https from 'https';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { spawnSync } from 'child_process';
import { Template, TemplateFile } from '../types';
import { validateExternalTemplateId } from './security';
interface ExternalTemplateManifest {
id: string;
name: string;
description: string;
language: string;
files: TemplateFile[];
}
interface ParsedGitHub {
owner: string;
repo: string;
branch: string;
}
interface ParsedNpm {
packageName: string;
}
function parseGitHubId(id: string): ParsedGitHub {
// id format: "owner/repo" or "owner/repo#branch"
const rest = id.replace(/^github:/, '');
const [ownerRepo, branch] = rest.split('#');
const [owner, repo] = ownerRepo.split('/');
return { owner, repo, branch: branch || 'main' };
}
function parseNpmId(id: string): ParsedNpm {
const packageName = id.replace(/^npm:/, '');
return { packageName };
}
const MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024; // 100 MB hard cap
// Allowed hostnames for redirect targets. Prevents SSRF by ensuring
// redirects from api.github.com stay within GitHub's infrastructure
// and redirects from registry.npmjs.org stay within npm's CDN.
const ALLOWED_REDIRECT_HOSTS = new Set([
'api.github.com',
'codeload.github.com',
'github.com',
'objects.githubusercontent.com',
'registry.npmjs.org',
'registry.yarnpkg.com',
]);
function httpsGet(url: string, headers: Record<string, string>): Promise<Buffer> {
return new Promise((resolve, reject) => {
const makeRequest = (requestUrl: string, redirectCount: number): void => {
Iif (redirectCount > 5) {
reject(new Error('Too many redirects'));
return;
}
const parsedUrl = new URL(requestUrl);
// Never follow redirects to plain HTTP — prevents MITM downgrade attacks
if (parsedUrl.protocol !== 'https:') {
reject(new Error(`Insecure redirect to non-HTTPS URL rejected: ${requestUrl}`));
return;
}
// SSRF protection: only allow redirects to known-safe hostnames.
// Prevents a compromised or malicious redirect from reaching internal
// network services (e.g., cloud metadata endpoints).
if (redirectCount > 0 && !ALLOWED_REDIRECT_HOSTS.has(parsedUrl.hostname)) {
reject(new Error(
`Security: redirect to untrusted host "${parsedUrl.hostname}" rejected. ` +
`Only redirects to GitHub and npm infrastructure are allowed.`
));
return;
}
const req = https.get(
requestUrl,
{
headers: {
'User-Agent': 'forgekit-cli/0.4.0',
...headers,
},
},
(res) => {
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
makeRequest(res.headers.location, redirectCount + 1);
return;
}
if (res.statusCode && res.statusCode >= 400) {
reject(new Error(`HTTP ${res.statusCode} fetching ${requestUrl}`));
return;
}
const chunks: Buffer[] = [];
let totalBytes = 0;
res.on('data', (chunk: Buffer) => {
totalBytes += chunk.length;
if (totalBytes > MAX_DOWNLOAD_BYTES) {
req.destroy();
reject(new Error(`Download exceeded ${MAX_DOWNLOAD_BYTES / 1024 / 1024} MB limit`));
return;
}
chunks.push(chunk);
});
res.on('end', () => resolve(Buffer.concat(chunks)));
res.on('error', reject);
}
);
req.on('error', reject);
};
makeRequest(url, 0);
});
}
function createTempDir(prefix: string): string {
return fs.mkdtempSync(path.join(os.tmpdir(), `forgekit-${prefix}-`));
}
/**
* Recursively walks a directory and throws if any symlinks are found.
* Prevents symlink traversal attacks from malicious tarballs where a
* symlink targets a path outside the extraction directory.
*/
function rejectSymlinks(dir: string): void {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isSymbolicLink()) {
throw new Error(
`Security: extracted template contains a symlink "${fullPath}". ` +
`Symlinks in templates are not allowed as they can escape the extraction directory.`
);
}
Iif (entry.isDirectory()) {
rejectSymlinks(fullPath);
}
}
}
function loadManifest(dir: string): ExternalTemplateManifest {
const manifestPath = path.join(dir, 'forgekit.json');
if (!fs.existsSync(manifestPath)) {
throw new Error(
`Template is missing forgekit.json manifest. ` +
`External templates must include a forgekit.json file at the repository root.`
);
}
const raw = fs.readFileSync(manifestPath, 'utf-8');
const manifest = JSON.parse(raw) as ExternalTemplateManifest;
Iif (!manifest.id || !manifest.name || !manifest.description || !manifest.files) {
throw new Error(
'Invalid forgekit.json: must include id, name, description, and files fields.'
);
}
// Validate that all file src paths stay within the extraction directory.
// Prevents a malicious forgekit.json from reading files outside the tarball
// (e.g. file.src = "../../etc/passwd").
const resolvedDir = path.resolve(dir);
for (const file of manifest.files) {
const resolvedSrc = path.resolve(dir, file.src);
if (!resolvedSrc.startsWith(resolvedDir + path.sep) && resolvedSrc !== resolvedDir) {
throw new Error(
`Security: template manifest file src "${file.src}" would escape the extraction directory. Aborting.`
);
}
}
return manifest;
}
function manifestToTemplate(manifest: ExternalTemplateManifest): Template {
return {
id: manifest.id,
name: manifest.name,
description: manifest.description,
stack: [manifest.language],
version: '0.0.0',
author: 'external',
files: manifest.files,
hooks: [],
variables: [],
};
}
async function loadGitHubTemplate(id: string): Promise<Template> {
const { owner, repo, branch } = parseGitHubId(id);
const url = `https://api.github.com/repos/${owner}/${repo}/tarball/${branch}`;
let tarball: Buffer;
try {
tarball = await httpsGet(url, { Accept: 'application/vnd.github+json' });
} catch (err) {
throw new Error(
`Failed to download template from GitHub (${owner}/${repo}#${branch}): ${(err as Error).message}`
);
}
const tmpDir = createTempDir('gh');
try {
const tarPath = path.join(tmpDir, 'template.tar.gz');
fs.writeFileSync(tarPath, tarball);
const extractDir = path.join(tmpDir, 'extracted');
fs.mkdirSync(extractDir, { recursive: true });
// Security: block symlinks in tarballs to prevent symlink traversal attacks
// where a malicious tarball places a symlink pointing outside the extraction
// directory and then writes through it. --no-same-permissions ensures files
// are created with safe default permissions.
const result = spawnSync('tar', [
'xzf', tarPath,
'-C', extractDir,
'--strip-components=1',
'--no-same-permissions',
], {
encoding: 'utf-8',
timeout: 30000,
});
if (result.status !== 0) {
throw new Error(`Failed to extract GitHub template tarball: ${result.stderr || 'unknown error'}`);
}
// After extraction, verify no symlinks exist in the extracted directory.
// Symlinks in user-supplied tarballs are a classic traversal vector.
// This MUST run before loadManifest to prevent symlink-based file reads.
rejectSymlinks(extractDir);
const manifest = loadManifest(extractDir);
return manifestToTemplate(manifest);
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}
async function loadNpmTemplate(id: string): Promise<Template> {
const { packageName } = parseNpmId(id);
// Verify package exists
const dryRun = spawnSync('npm', ['pack', packageName, '--dry-run', '--json'], {
encoding: 'utf-8',
timeout: 30000,
});
if (dryRun.status !== 0) {
throw new Error(`npm package "${packageName}" not found or not accessible.`);
}
const tmpDir = createTempDir('npm');
try {
const packResult = spawnSync('npm', ['pack', packageName], {
encoding: 'utf-8',
cwd: tmpDir,
timeout: 30000,
});
if (packResult.status !== 0) {
throw new Error(`Failed to download npm package "${packageName}": ${packResult.stderr || 'unknown error'}`);
}
const tgzFile = packResult.stdout.trim().split('\n').pop();
Iif (!tgzFile) {
throw new Error(`Failed to determine downloaded package filename for "${packageName}".`);
}
const tgzPath = path.join(tmpDir, tgzFile);
const extractDir = path.join(tmpDir, 'extracted');
fs.mkdirSync(extractDir, { recursive: true });
const tarResult = spawnSync('tar', [
'xzf', tgzPath,
'-C', extractDir,
'--no-same-permissions',
], {
encoding: 'utf-8',
timeout: 30000,
});
Iif (tarResult.status !== 0) {
throw new Error(`Failed to extract npm package: ${tarResult.stderr || 'unknown error'}`);
}
// After extraction, verify no symlinks exist in the extracted directory.
// This MUST run before loadManifest to prevent symlink-based file reads.
rejectSymlinks(extractDir);
// npm pack extracts into a "package/" subdirectory
const packageDir = path.join(extractDir, 'package');
const manifest = loadManifest(packageDir);
return manifestToTemplate(manifest);
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}
export async function loadExternalTemplate(templateId: string): Promise<Template> {
if (!validateExternalTemplateId(templateId)) {
throw new Error(`Invalid external template ID: "${templateId}".`);
}
if (templateId.startsWith('github:')) {
return loadGitHubTemplate(templateId);
}
if (templateId.startsWith('npm:')) {
return loadNpmTemplate(templateId);
}
throw new Error(`Unsupported template prefix in "${templateId}". Use github: or npm: prefixes.`);
}
export function isExternalTemplate(templateId: string): boolean {
return templateId.startsWith('github:') || templateId.startsWith('npm:');
}
|