-
Notifications
You must be signed in to change notification settings - Fork 221
Expand file tree
/
Copy pathtar-extract.ts
More file actions
170 lines (153 loc) · 5.93 KB
/
tar-extract.ts
File metadata and controls
170 lines (153 loc) · 5.93 KB
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
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import * as tar from 'tar';
import { InstallException } from './errors.js';
import { log } from './log.js';
import { MAX_ENTRY_SIZE } from './types.js';
import { isAllowedEntryType, isInside } from './util.js';
const PACKAGE_PREFIX = 'package/';
/**
* Extract a slice of an OCI layer tarball into `destination/pluginPath`.
*
* Mirrors the Python `extract_oci_plugin` with the same security guards:
* - reject absolute or `..`-containing plugin paths
* - enforce per-entry size limit (MAX_ENTRY_SIZE) against zip bombs
* - skip sym/hard links whose targets would escape `destination`
* - reject device files / FIFOs (`tar` `filter` only emits regular types)
*
* Uses streaming via `node-tar` — no full-archive read into memory.
*/
export async function extractOciPlugin(
tarball: string,
pluginPath: string,
destination: string,
): Promise<void> {
assertSafePluginPath(pluginPath);
const destAbs = path.resolve(destination);
const pluginDir = path.join(destAbs, pluginPath);
await fs.rm(pluginDir, { recursive: true, force: true });
await fs.mkdir(destAbs, { recursive: true });
// Boundary-safe path prefix — prevents `plugin-one` from matching sibling
// directories with the same prefix (e.g., `plugin-one-evil/`).
const pluginPathBoundary = pluginPath.endsWith('/') ? pluginPath : pluginPath + '/';
// Errors thrown inside `tar` filter callbacks are sometimes swallowed by the
// parser; capture them in a closure and re-throw after extraction completes.
let pending: InstallException | null = null;
await tar.x({
file: tarball,
cwd: destAbs,
preservePaths: false,
filter: (filePath, entry) => {
if (pending) return false;
const stat = entry as tar.ReadEntry;
if (filePath !== pluginPath && !filePath.startsWith(pluginPathBoundary)) return false;
if (stat.size > MAX_ENTRY_SIZE) {
pending = new InstallException(`Zip bomb detected in ${filePath}`);
return false;
}
if (stat.type === 'SymbolicLink' || stat.type === 'Link') {
const linkName = stat.linkpath ?? '';
const linkTarget = path.resolve(destAbs, linkName);
if (!isInside(linkTarget, destAbs)) {
log(
`\t==> WARNING: skipping file containing link outside of the archive: ${filePath} -> ${linkName}`,
);
return false;
}
}
if (!isAllowedEntryType(stat.type)) {
pending = new InstallException(`Disallowed tar entry type ${stat.type} for ${filePath}`);
return false;
}
return true;
},
});
if (pending) throw pending;
}
/**
* Extract an NPM tarball (`npm pack` output). Entries all start with `package/`
* which is stripped. Matches `extract_npm_package` in fast.py, including the
* realpath-based escape check for symlinks inside the archive.
*
* Returns the directory name (basename) the package was extracted into.
*/
export async function extractNpmPackage(archive: string): Promise<string> {
if (!archive.endsWith('.tgz')) {
throw new InstallException(`Expected .tgz archive, got ${archive}`);
}
const pkgDir = archive.slice(0, -'.tgz'.length);
const pkgDirReal = path.resolve(pkgDir);
await fs.rm(pkgDir, { recursive: true, force: true });
await fs.mkdir(pkgDir, { recursive: true });
let pending: InstallException | null = null;
await tar.x({
file: archive,
cwd: pkgDir,
preservePaths: false,
filter: (filePath, entry) => {
if (pending) return false;
const stat = entry as tar.ReadEntry;
if (stat.type === 'Directory') return false;
if (stat.type === 'File') {
if (!filePath.startsWith(PACKAGE_PREFIX)) {
pending = new InstallException(
`NPM package archive does not start with 'package/' as it should: ${filePath}`,
);
return false;
}
if (stat.size > MAX_ENTRY_SIZE) {
pending = new InstallException(`Zip bomb detected in ${filePath}`);
return false;
}
stat.path = filePath.slice(PACKAGE_PREFIX.length);
return true;
}
if (stat.type === 'SymbolicLink' || stat.type === 'Link') {
const linkPath = stat.linkpath ?? '';
if (!linkPath.startsWith(PACKAGE_PREFIX)) {
pending = new InstallException(
`NPM package archive contains a link outside of the archive: ${filePath} -> ${linkPath}`,
);
return false;
}
stat.path = filePath.slice(PACKAGE_PREFIX.length);
stat.linkpath = linkPath.slice(PACKAGE_PREFIX.length);
const linkTarget = path.resolve(pkgDir, stat.linkpath);
if (!isInside(linkTarget, pkgDirReal)) {
pending = new InstallException(
`NPM package archive contains a link outside of the archive: ${stat.path} -> ${stat.linkpath}`,
);
return false;
}
return true;
}
pending = new InstallException(
`NPM package archive contains a non-regular file: ${filePath}`,
);
return false;
},
});
if (pending) throw pending;
await fs.rm(archive, { force: true });
return path.basename(pkgDirReal);
}
/**
* Validate a plugin path against traversal attempts. Segment-based — a bare
* `..` substring in a filename (`my..plugin`) is allowed; a `..` path segment
* (`foo/../bar`) is not. Absolute paths, empty segments, and `.` segments are
* also rejected.
*/
function assertSafePluginPath(pluginPath: string): void {
if (path.isAbsolute(pluginPath)) {
throw new InstallException(`Invalid plugin path (absolute): ${pluginPath}`);
}
if (pluginPath.length === 0) {
throw new InstallException('Invalid plugin path (empty)');
}
const segments = pluginPath.split(/[/\\]/);
for (const segment of segments) {
if (segment === '' || segment === '.' || segment === '..') {
throw new InstallException(`Invalid plugin path (path traversal detected): ${pluginPath}`);
}
}
}