-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathcommon.ts
More file actions
288 lines (261 loc) · 9.62 KB
/
Copy pathcommon.ts
File metadata and controls
288 lines (261 loc) · 9.62 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
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
import { downloadR2Image, imageToBase64 } from "../../utils/images";
import { ConversationMessage, mapImagesInMultiModalMessage } from "../inferutils/common";
export function extractCommands(rawOutput: string, onlyInstallCommands: boolean = false): string[] {
const commands: string[] = [];
// Helper function to check if command is an install command
const isInstallCommand = (command: string): boolean => {
return /^(?:npm|yarn|pnpm|bun)\s+(?:install|add)(?:\s|$)/.test(command);
};
// Extract commands from code blocks (with or without language indicators)
// Handles: ```bash, ```sh, ```, ``` command, etc.
const codeBlockRegex = /```(?:[a-zA-Z]*)?\s*\n?([\s\S]*?)\n?```/gi;
let codeBlockMatch;
while ((codeBlockMatch = codeBlockRegex.exec(rawOutput)) !== null) {
const blockContent = codeBlockMatch[1].trim();
// Split by newlines and filter out empty lines and comments
const blockCommands = blockContent
.split('\n')
.map((line) => line.trim())
.filter(
(line) =>
line && !line.startsWith('#') && !line.startsWith('//'),
)
.map((line) => {
// Remove shell prompts like $ or >
return line.replace(/^[$>]\s*/, '');
})
.filter((line) => {
// Filter by install commands if onlyInstallCommands is true
return !onlyInstallCommands || isInstallCommand(line);
});
commands.push(...blockCommands);
}
// Extract inline commands (wrapped in backticks)
const inlineCommandRegex = /`([^`\n]+)`/g;
let inlineMatch;
while ((inlineMatch = inlineCommandRegex.exec(rawOutput)) !== null) {
const command = inlineMatch[1].trim();
// Only include if it looks like a command and matches install filter if needed
if (looksLikeCommand(command)) {
if (!onlyInstallCommands || isInstallCommand(command)) {
commands.push(command);
}
}
}
// Define command patterns based on whether we only want install commands
let commandPatterns;
if (onlyInstallCommands) {
// Only include package manager install/add commands
commandPatterns = [
/(?:^|\s)((?:npm|yarn|pnpm|bun)\s+(?:install|add)(?:\s+[^\n]+)?)/gm,
];
} else {
// Include all command patterns
commandPatterns = [
// Package managers
/(?:^|\s)((?:npm|yarn|pnpm|bun)\s+(?:install|add|run|build|start|dev|test)(?:\s+[^\n]+)?)/gm,
// Directory operations
/(?:^|\s)(mkdir\s+[^\n]+)/gm,
/(?:^|\s)(cd\s+[^\n]+)/gm,
// File operations
/(?:^|\s)(touch\s+[^\n]+)/gm,
/(?:^|\s)(cp\s+[^\n]+)/gm,
/(?:^|\s)(mv\s+[^\n]+)/gm,
// Git commands
/(?:^|\s)(git\s+(?:init|clone|add|commit|push|pull)(?:\s+[^\n]+)?)/gm,
// Build tools
/(?:^|\s)((?:make|cmake|gradle|mvn)\s+[^\n]+)/gm,
// Environment setup
/(?:^|\s)(export\s+[^\n]+)/gm,
/(?:^|\s)(source\s+[^\n]+)/gm,
];
}
// Extract commands using the appropriate patterns
for (const pattern of commandPatterns) {
let match;
while ((match = pattern.exec(rawOutput)) !== null) {
const command = match[1].trim();
if (command && !commands.includes(command)) {
commands.push(command);
}
}
}
// Filter commands if onlyInstallCommands is true
let filteredCommands = [...new Set(commands)];
if (onlyInstallCommands) {
// Filter to only keep package manager install/add commands
filteredCommands = filteredCommands.filter(command => {
return /^(?:npm|yarn|pnpm|bun)\s+(?:install|add)(?:\s|$)/.test(command);
});
}
return filteredCommands;
}
/**
* Maximum number of commands to keep in bootstrap history
* Prevents unbounded growth while allowing sufficient dependency management
*/
export const MAX_BOOTSTRAP_COMMANDS = 50;
/**
* WHITELIST: Only commands that install/add/remove/update SPECIFIC packages.
* Supports: scoped packages (@org/pkg), versions (pkg@1.2.3), ranges (^, ~, =).
*/
const PACKAGE_MANAGERS = new Set(['npm', 'yarn', 'pnpm', 'bun']);
const PACKAGE_ACTIONS = new Set(['add', 'install', 'remove', 'uninstall', 'update']);
/**
* Flag allowlist. Only flags that cannot alter lifecycle-script / trust behaviour are
* permitted. Flags such as --trust, --unsafe-perm, --allow-scripts, --foreground-scripts
* are deliberately excluded so they can never reach the bootstrap argv (VEC-A).
*/
const ALLOWED_FLAGS = new Set([
'-D', '--save-dev', '-d', '--dev',
'-E', '--save-exact', '--exact',
'-P', '--save-prod', '--save',
'-O', '--save-optional', '--save-peer',
'--no-save', '--legacy-peer-deps',
]);
/**
* A valid package spec: bare/scoped name with optional version or range.
* Must NOT contain a protocol (://), which blocks remote URL / git installs that can run
* untrusted postinstall scripts (VEC-A / VEC-B).
*/
const PACKAGE_SPEC = /^[\w@][\w@/.\-^~=]*$/;
// Defense-in-depth deny list: any shell metacharacter disqualifies the command.
const SHELL_METACHAR = /[;&|`$<>(){}[\]"'\\\n\r]/;
/**
* Check if a command is valid for bootstrap script.
* WHITELIST approach: Only allows package management commands with specific package names.
*
* @returns true if command is valid for bootstrap, false otherwise
*
* Valid examples:
* - "bun add react"
* - "npm install lodash@^4.17.21"
* - "bun add @cloudflare/workers@1.0.0"
* - "bun remove @types/node"
* - "npm update react-dom@~18.2.0"
* - "npm install package@>=1.0.0"
*
* Invalid (rejected):
* - File operations: "rm -rf src/file.tsx", "mv file.txt", "cp -r dir"
* - Plain installs: "bun install", "npm install"
* - Run commands: "bun run build", "npm run dev"
* - Any non-package-manager commands
*/
export function isValidBootstrapCommand(command: string): boolean {
const trimmed = command.trim();
if (SHELL_METACHAR.test(trimmed)) return false;
const tokens = trimmed.split(/\s+/);
if (tokens.length < 3) return false;
const [manager, action, ...rest] = tokens;
if (!PACKAGE_MANAGERS.has(manager)) return false;
if (!PACKAGE_ACTIONS.has(action)) return false;
let hasPackageSpec = false;
for (const token of rest) {
if (token.startsWith('-')) {
// Only allowlisted flags may pass; everything else (e.g. --trust) is rejected.
if (!ALLOWED_FLAGS.has(token)) return false;
} else {
// Reject remote URL / git installs and any malformed spec.
if (token.includes('://') || !PACKAGE_SPEC.test(token)) return false;
hasPackageSpec = true;
}
}
// At least one concrete package spec is required (rejects "bun install", "bun add --trust").
return hasPackageSpec;
}
/**
* Check if a command should NOT be saved to bootstrap.
* Inverse of isValidBootstrapCommand
*/
export function isBootstrapRuntimeCommand(command: string): boolean {
return !isValidBootstrapCommand(command);
}
/**
* Extract package operation key for deduplication.
* Assumes command has already been validated by isValidBootstrapCommand.
*
* @example
* getPackageOperationKey("bun add react") -> "add:react"
* getPackageOperationKey("npm install lodash@^4.0.0") -> "install:lodash@^4.0.0"
* getPackageOperationKey("bun add @cloudflare/workers") -> "add:@cloudflare/workers"
*/
export function getPackageOperationKey(command: string): string | null {
if (!isValidBootstrapCommand(command)) return null;
const [, action, ...rest] = command.trim().split(/\s+/);
// Normalize token order so "add react react-dom" === "add react-dom react".
const tokens = rest.slice().sort().join(' ');
return `${action}:${tokens}`;
}
/**
* Validate and clean bootstrap commands in a single pass.
* Validates, deduplicates, and limits size.
*
* @param commands - Raw command list
* @param maxCommands - Maximum number of commands to keep (defaults to MAX_BOOTSTRAP_COMMANDS)
* @returns Cleaned command list with metadata about what was removed
*/
export function validateAndCleanBootstrapCommands(
commands: string[],
maxCommands: number = MAX_BOOTSTRAP_COMMANDS
): { validCommands: string[]; invalidCommands: string[]; deduplicated: number } {
const seen = new Map<string, string>();
const invalidCommands: string[] = [];
let totalValid = 0;
// validate + deduplicate
for (const cmd of commands) {
const key = getPackageOperationKey(cmd);
if (key) {
totalValid++;
seen.set(key, cmd); // Latest wins for duplicates
} else {
invalidCommands.push(cmd);
}
}
// Extract deduplicated commands and apply size limit (keep most recent)
const deduplicated = Array.from(seen.values());
const validCommands = deduplicated.slice(-maxCommands);
const deduplicatedCount = totalValid - deduplicated.length;
return {
validCommands,
invalidCommands,
deduplicated: deduplicatedCount
};
}
export function looksLikeCommand(text: string): boolean {
// Check if the text looks like a shell command
const commandIndicators = [
/^(?:npm|yarn|pnpm|bun|node|deno)\s/,
/^(?:mkdir|cd|touch|cp|mv|rm|ls|cat|grep|find)\s/,
/^(?:git|svn|hg)\s/,
/^(?:make|cmake|gcc|clang)\s/,
/^(?:docker|podman)\s/,
/^(?:curl|wget)\s/,
/^(?:python|pip|conda)\s/,
/^(?:ruby|gem|bundle)\s/,
/^(?:go|cargo|rustc)\s/,
/^(?:java|javac|mvn|gradle)\s/,
/^(?:php|composer)\s/,
/^(?:export|source|alias)\s/,
];
return commandIndicators.some((pattern) => pattern.test(text));
}
export async function prepareMessagesForInference(env: Env, messages: ConversationMessage[]) : Promise<ConversationMessage[]> {
// For each multimodal image, convert the image to base64 data url
const processedMessages = await Promise.all(messages.map(m => {
return mapImagesInMultiModalMessage(structuredClone(m), async (c) => {
const url = c.image_url.url;
if (url.includes('base64,')) {
return c;
}
const image = await downloadR2Image(env, url);
return {
...c,
image_url: {
...c.image_url,
url: await imageToBase64(env, image)
},
};
});
}));
return processedMessages;
}