forked from nexu-io/open-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin-installation.ts
More file actions
252 lines (224 loc) · 8.59 KB
/
Copy pathplugin-installation.ts
File metadata and controls
252 lines (224 loc) · 8.59 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
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
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import stream from 'node:stream';
import util from 'node:util';
import yauzl from 'yauzl';
const pipeline = util.promisify(stream.pipeline);
export interface PluginInstallResult {
ok: boolean;
plugin: InstalledPluginLike | null;
warnings: unknown[];
message: string;
log: string[];
}
export interface PluginInstallationHelpersDeps {
db: PluginDbLike;
installFromLocalFolder: (db: PluginDbLike, args: InstallFromLocalFolderArgs) => AsyncIterable<InstallFromLocalFolderEvent>;
PLUGIN_REGISTRY_ROOTS: string[];
PLUGIN_LOCKFILE_PATH: string;
PLUGIN_UPLOAD_MAX_BYTES: number;
}
interface PluginDbLike {
prepare(sql: string): {
all(...params: unknown[]): unknown[];
get(...params: unknown[]): unknown;
run(...params: unknown[]): unknown;
};
}
interface InstalledPluginLike {
title?: string;
[key: string]: unknown;
}
interface InstallFromLocalFolderArgs {
source: string;
roots: string[];
_stagedFolder: string;
_stagedSourceKind: string;
lockfilePath: string;
}
interface InstallFromLocalFolderEvent {
kind?: string;
message?: string;
warnings?: unknown[];
plugin?: InstalledPluginLike;
}
export function normalizeProjectPluginFolderPath(input: unknown) {
const value = String(input ?? '').replace(/\\/g, '/').trim();
if (!value || value.includes('\0') || value.startsWith('/') || /^[A-Za-z]:\//.test(value)) {
throw new Error('plugin folder path must be a relative project path');
}
const parts = value.split('/').filter(Boolean);
if (parts.length === 0 || parts.some((part) => part === '.' || part === '..')) {
throw new Error('plugin folder path must not contain traversal segments');
}
return parts.join('/');
}
export async function resolveProjectChildDirectory(projectRoot: string, relativePath: string) {
const rootReal = await fs.promises.realpath(projectRoot);
const candidate = path.resolve(projectRoot, relativePath);
const real = await fs.promises.realpath(candidate);
if (!real.startsWith(rootReal + path.sep) && real !== rootReal) {
throw new Error('plugin folder path escapes project dir');
}
const st = await fs.promises.stat(real);
if (!st.isDirectory()) {
const err: NodeJS.ErrnoException = new Error('plugin folder path is not a directory');
err.code = 'ENOTDIR';
throw err;
}
return real;
}
export async function folderLooksLikePlugin(folder: string) {
const names = ['open-design.json', 'SKILL.md', path.join('.claude-plugin', 'plugin.json')];
for (const name of names) {
if (fs.existsSync(path.join(folder, name))) return true;
}
return false;
}
export async function findUploadedPluginRoot(stagedFolder: string) {
if (await folderLooksLikePlugin(stagedFolder)) return stagedFolder;
const entries = await fs.promises.readdir(stagedFolder, { withFileTypes: true });
const dirs = entries.filter((entry) => entry.isDirectory());
const files = entries.filter((entry) => entry.isFile());
if (files.length === 0 && dirs.length === 1) {
const nested = path.join(stagedFolder, dirs[0]!.name);
if (await folderLooksLikePlugin(nested)) return nested;
}
return stagedFolder;
}
export function safeUploadRelativePath(input: unknown) {
const value = String(input || '').replace(/\\/g, '/');
if (!value || value.includes('\0') || value.startsWith('/') || /^[A-Za-z]:\//.test(value)) {
throw new Error('invalid upload path');
}
const parts = value.split('/').filter(Boolean);
if (parts.length === 0 || parts.some((part) => part === '.' || part === '..')) {
throw new Error(`unsafe upload path: ${value}`);
}
return parts.join(path.sep);
}
export async function extractPluginZipToFolder(buffer: Buffer, stagedFolder: string, maxBytes: number) {
if (buffer.length > maxBytes) throw new Error('zip file too large');
const zip = await new Promise<yauzl.ZipFile>((resolve, reject) => {
yauzl.fromBuffer(buffer, { lazyEntries: true }, (err, zipfile) => {
if (err || !zipfile) reject(err ?? new Error('failed to load zip'));
else resolve(zipfile);
});
});
return new Promise<void>((resolve, reject) => {
let totalBytes = 0;
let entryCount = 0;
zip.on('error', reject);
zip.on('end', () => {
if (entryCount === 0) reject(new Error('zip contains no files'));
else resolve();
});
zip.on('entry', (entry: yauzl.Entry) => {
if (entry.fileName.endsWith('/')) {
zip.readEntry();
return;
}
entryCount++;
const unixMode = typeof entry.externalFileAttributes === 'number' ? (entry.externalFileAttributes >>> 16) : 0;
if ((unixMode & 0o170000) === 0o120000) {
reject(new Error(`zip entry is a symbolic link: ${entry.fileName}`));
return;
}
let rel: string;
try {
rel = safeUploadRelativePath(entry.fileName);
} catch (err) {
reject(err);
return;
}
zip.openReadStream(entry, async (err, readStream) => {
if (err || !readStream) {
reject(err ?? new Error(`failed to read entry: ${entry.fileName}`));
return;
}
const dest = path.join(stagedFolder, rel);
try {
await fs.promises.mkdir(path.dirname(dest), { recursive: true });
readStream.on('data', (chunk: Buffer) => {
totalBytes += chunk.length;
if (totalBytes > maxBytes) {
readStream.destroy(new Error('zip extracted size exceeds 50 MiB'));
}
});
await pipeline(readStream, fs.createWriteStream(dest));
zip.readEntry();
} catch (pipeErr) {
reject(pipeErr);
}
});
});
zip.readEntry();
});
}
export function createPluginInstallationHelpers(deps: PluginInstallationHelpersDeps) {
async function finishUploadedPluginInstall(stagedFolder: string, source: string): Promise<PluginInstallResult> {
const warnings: unknown[] = [];
const log: string[] = [];
let plugin = null;
let message = 'Install finished.';
try {
const pluginRoot = await findUploadedPluginRoot(stagedFolder);
for await (const ev of deps.installFromLocalFolder(deps.db, {
source,
roots: deps.PLUGIN_REGISTRY_ROOTS,
_stagedFolder: pluginRoot,
_stagedSourceKind: 'user',
lockfilePath: deps.PLUGIN_LOCKFILE_PATH,
})) {
if (ev.message) log.push(ev.message);
if (Array.isArray(ev.warnings)) warnings.splice(0, warnings.length, ...ev.warnings);
if (ev.kind === 'success') {
if (!ev.plugin) continue;
plugin = ev.plugin;
message = `Installed ${ev.plugin.title ?? 'plugin'}.`;
break;
}
if (ev.kind === 'error') {
message = ev.message ?? 'Install failed.';
break;
}
}
return { ok: Boolean(plugin), plugin, warnings, message, log };
} finally {
await fs.promises.rm(stagedFolder, { recursive: true, force: true }).catch(() => undefined);
}
}
async function stageUploadedPluginZip(buffer: Buffer, source: string) {
const stagedFolder = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'od-plugin-zip-'));
try {
await extractPluginZipToFolder(buffer, stagedFolder, deps.PLUGIN_UPLOAD_MAX_BYTES);
return await finishUploadedPluginInstall(stagedFolder, source);
} catch (err) {
await fs.promises.rm(stagedFolder, { recursive: true, force: true }).catch(() => undefined);
throw err;
}
}
async function stageUploadedPluginFolder(files: Array<{ buffer: Buffer; originalname: string }>, rawPaths: unknown) {
const stagedFolder = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'od-plugin-folder-'));
try {
if (files.length === 0) return null;
const paths = Array.isArray(rawPaths) ? rawPaths : rawPaths ? [rawPaths] : [];
let totalBytes = 0;
for (let i = 0; i < files.length; i += 1) {
const file = files[i]!;
totalBytes += file.buffer.length;
if (totalBytes > deps.PLUGIN_UPLOAD_MAX_BYTES) throw new Error('folder upload exceeds 50 MiB');
const rel = safeUploadRelativePath(paths[i] || file.originalname);
const dest = path.join(stagedFolder, rel);
await fs.promises.mkdir(path.dirname(dest), { recursive: true });
await fs.promises.writeFile(dest, file.buffer);
}
return await finishUploadedPluginInstall(stagedFolder, 'upload:folder');
} catch (err) {
await fs.promises.rm(stagedFolder, { recursive: true, force: true }).catch(() => undefined);
throw err;
}
}
return { finishUploadedPluginInstall, stageUploadedPluginZip, stageUploadedPluginFolder };
}