Skip to content

Commit cbaef50

Browse files
fix: harden Squad input handling (#2543)
Relates to #2538. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 02f5738 commit cbaef50

28 files changed

Lines changed: 691 additions & 122 deletions

‎.changeset/secure-release-paths.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
"@bradygaster/squad-cli": patch
3+
"@bradygaster/squad-sdk": patch
4+
---
5+
6+
Harden generated configuration, remote detection, input parsing, and self-upgrade commands against unsafe or pathological inputs.
7+
8+
Avoid probing retired profile squads while resolving legacy team roots.

‎packages/squad-cli/src/cli/commands/doctor.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ function detectMode(cwd: string): ModeInfo {
101101
export function teamRootIsThisProject(cwd: string, teamRoot: string): boolean {
102102
const resolved = path.resolve(cwd, teamRoot);
103103
const normalize = (p: string) => {
104-
const n = path.resolve(p).replace(/[\\/]+$/, '');
104+
const n = path.resolve(p).replace(/[\\/]$/, '');
105105
return process.platform === 'win32' ? n.toLowerCase() : n;
106106
};
107107
const target = normalize(resolved);

‎packages/squad-cli/src/cli/commands/migrate.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -320,15 +320,15 @@ function generateSquadConfig(
320320
});
321321
}
322322
}
323-
lines.push(` members: [${team.members.map(m => `'${m}'`).join(', ')}],`);
323+
lines.push(` members: [${team.members.map(m => `'${escapeString(m)}'`).join(', ')}],`);
324324
lines.push(" }),");
325325
lines.push("");
326326

327327
// Agents section
328328
lines.push(" agents: [");
329329
agents.forEach((agent, idx) => {
330330
const isLast = idx === agents.length - 1;
331-
lines.push(` defineAgent({ name: '${agent.name}', role: '${escapeString(agent.role)}', charter: '${agent.charter}', status: '${agent.status}' })${isLast ? '' : ','}`);
331+
lines.push(` defineAgent({ name: '${escapeString(agent.name)}', role: '${escapeString(agent.role)}', charter: '${escapeString(agent.charter)}', status: '${agent.status}' })${isLast ? '' : ','}`);
332332
});
333333
lines.push(" ],");
334334
lines.push("");
@@ -339,12 +339,12 @@ function generateSquadConfig(
339339
lines.push(" rules: [");
340340
routing.rules.forEach((rule, idx) => {
341341
const isLast = idx === routing.rules.length - 1;
342-
const agentsStr = `[${rule.agents.map(a => `'${a}'`).join(', ')}]`;
342+
const agentsStr = `[${rule.agents.map(a => `'${escapeString(a)}'`).join(', ')}]`;
343343
const desc = rule.description ? `, description: '${escapeString(rule.description)}'` : '';
344-
lines.push(` { pattern: '${rule.pattern}', agents: ${agentsStr}${desc} }${isLast ? '' : ','}`);
344+
lines.push(` { pattern: '${escapeString(rule.pattern)}', agents: ${agentsStr}${desc} }${isLast ? '' : ','}`);
345345
});
346346
lines.push(" ],");
347-
lines.push(` defaultAgent: '${routing.defaultAgent}',`);
347+
lines.push(` defaultAgent: '${escapeString(routing.defaultAgent)}',`);
348348
lines.push(" fallback: 'coordinator',");
349349
lines.push(" }),");
350350
lines.push("");
@@ -359,6 +359,9 @@ function generateSquadConfig(
359359
lines.push(" capacity: {");
360360
Object.entries(casting.capacity).forEach(([universe, count], idx, arr) => {
361361
const isLast = idx === arr.length - 1;
362+
if (!Number.isFinite(count)) {
363+
throw new Error(`Casting capacity for '${universe}' must be a finite number`);
364+
}
362365
lines.push(` '${escapeString(universe)}': ${count}${isLast ? '' : ','}`);
363366
});
364367
lines.push(" },");
@@ -373,10 +376,12 @@ function generateSquadConfig(
373376
}
374377

375378
/**
376-
* Escape single quotes in string literals
379+
* Escape content for a single-quoted JavaScript string literal.
377380
*/
378381
function escapeString(str: string): string {
379-
return str.replace(/'/g, "\\'").replace(/\n/g, '\\n');
382+
return str.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
383+
.replace(/\r/g, '\\r').replace(/\n/g, '\\n')
384+
.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
380385
}
381386

382387
/**

‎packages/squad-cli/src/cli/core/team-md.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,14 @@ export function insertCopilotSection(content: string, autoAssign: boolean = fals
9090
* Remove @copilot section from team.md
9191
*/
9292
export function removeCopilotSection(content: string): string {
93-
return content.replace(/\n## Coding Agent\n[\s\S]*?(?=\n## |\n*$)/, '');
93+
const heading = '\n## Coding Agent\n';
94+
const start = content.indexOf(heading);
95+
if (start === -1) return content;
96+
const nextSection = content.indexOf('\n## ', start + heading.length);
97+
if (nextSection !== -1) return content.slice(0, start) + content.slice(nextSection);
98+
let end = content.length;
99+
while (end > start + heading.length && content[end - 1] === '\n') end--;
100+
return content.slice(0, start) + content.slice(end);
94101
}
95102

96103
/**

‎packages/squad-cli/src/cli/core/upgrade.ts‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
1010
import { FSStorageProvider, stripTeamCapabilitiesBlock, syncTeamCapabilities } from '@bradygaster/squad-sdk';
1111
import { clearResolveSquadCache, isRetiredProfileTeamRoot } from '@bradygaster/squad-sdk/resolution';
1212
import { squadRepoLauncherScript } from '@bradygaster/squad-sdk/client';
13+
import { detectPlatformFromUrl } from '@bradygaster/squad-sdk/platform';
1314
import {
1415
backfillCastingRegistryFromTeam,
1516
detectHistoricalCastingSchema,
@@ -271,8 +272,7 @@ function detectIsGitHubForMcp(dest: string, config: Record<string, unknown>): bo
271272

272273
try {
273274
const remoteUrl = execFileSync('git', ['remote', 'get-url', 'origin'], { cwd: dest, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
274-
const remoteUrlLower = remoteUrl.toLowerCase();
275-
if (remoteUrlLower.includes('dev.azure.com') || remoteUrlLower.includes('visualstudio.com') || remoteUrlLower.includes('ssh.dev.azure.com')) {
275+
if (detectPlatformFromUrl(remoteUrl) === 'azure-devops') {
276276
return false;
277277
}
278278
} catch {
@@ -332,7 +332,7 @@ function stripRetiredProfileTeamRoot(squadDir: string, dest: string, dryRun: boo
332332
*/
333333
export function stripAgentStamps(s: string): string {
334334
return s
335-
.replace(/<!-- squad-cli v[\d.]+[-\w.]* -->\n?/g, '')
335+
.replace(/<!-- squad-cli v[\d.][-\w.]* -->\n?/g, '')
336336
.replace(/<!-- version: [^>]+ -->/g, '<!-- version: X -->')
337337
.replace(/- \*\*Version:\*\* \S+/g, '- **Version:** X')
338338
.replace(/`Squad v[^`]+`/g, '`Squad vX`')
@@ -1893,11 +1893,12 @@ export function detectSelfUpgradeTag(currentVersion: string): SelfUpgradeTag {
18931893
/** The exact command `selfUpgradeCli` runs for a package manager and dist-tag. */
18941894
export function selfUpgradeCommand(packageManager: SelfUpgradePackageManager, insiderOrTag: boolean | SelfUpgradeTag): string {
18951895
const tag: SelfUpgradeTag = typeof insiderOrTag === 'boolean' ? (insiderOrTag ? 'insider' : 'latest') : insiderOrTag;
1896-
const pkg = `@bradygaster/squad-cli@${tag}`;
1896+
if (tag !== 'latest' && tag !== 'insider') throw new Error('Invalid self-upgrade tag');
18971897
switch (packageManager) {
1898-
case 'pnpm': return `pnpm add -g ${pkg}`;
1899-
case 'yarn': return `yarn global add ${pkg}`;
1900-
default: return `npm install -g ${pkg}`;
1898+
case 'pnpm': return tag === 'insider' ? 'pnpm add -g @bradygaster/squad-cli@insider' : 'pnpm add -g @bradygaster/squad-cli@latest';
1899+
case 'yarn': return tag === 'insider' ? 'yarn global add @bradygaster/squad-cli@insider' : 'yarn global add @bradygaster/squad-cli@latest';
1900+
case 'npm': return tag === 'insider' ? 'npm install -g @bradygaster/squad-cli@insider' : 'npm install -g @bradygaster/squad-cli@latest';
1901+
default: throw new Error('Invalid self-upgrade package manager');
19011902
}
19021903
}
19031904

‎packages/squad-cli/src/cli/shell/index.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1275,9 +1275,14 @@ export async function runShell(): Promise<void> {
12751275
recordShellError('dispatch', err instanceof Error ? err.constructor.name : 'unknown');
12761276
const errorMsg = err instanceof Error ? err.message : String(err);
12771277
if (shellApi) {
1278+
const quotaExceeded = errorMsg.toLowerCase().split(/[\r\n\u2028\u2029]/).some((line) => {
1279+
const quota = line.indexOf('quota');
1280+
return quota !== -1 && line.indexOf('exceed', quota + 5) !== -1;
1281+
});
12781282
const isRateLimit =
12791283
err instanceof RateLimitError ||
1280-
/rate.?limit|quota.*exceed|429/i.test(errorMsg);
1284+
/rate.?limit|429/i.test(errorMsg) ||
1285+
quotaExceeded;
12811286
let guidance;
12821287
if (isRateLimit) {
12831288
const retryAfter =

‎packages/squad-sdk/src/agents/onboarding.ts‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,24 @@ export async function onboardAgent(
444444
* @param role - Agent role
445445
* @returns True if config was updated, false if not found or JSON format
446446
*/
447+
function findRulesArray(content: string): { start: number; end: number; entries: string } | undefined {
448+
const start = /rules:\s*\[/.exec(content);
449+
if (!start) return undefined;
450+
const entriesStart = start.index + start[0].length;
451+
let cursor = entriesStart;
452+
while (cursor < content.length) {
453+
const close = content.indexOf(']', cursor);
454+
if (close === -1) return undefined;
455+
let after = close + 1;
456+
while (after < content.length && /\s/.test(content[after]!)) after++;
457+
if (after < content.length && ',})'.includes(content[after]!)) {
458+
return { start: start.index, end: close + 1, entries: content.slice(entriesStart, close) };
459+
}
460+
cursor = close + 1;
461+
}
462+
return undefined;
463+
}
464+
447465
export async function addAgentToConfig(
448466
teamRoot: string,
449467
agentName: string,
@@ -527,21 +545,18 @@ export async function addAgentToConfig(
527545
if (workType) {
528546
const workTypePattern = new RegExp(`workType:\\s*['"]${workType}['"]`);
529547
if (!workTypePattern.test(updatedContent)) {
530-
const rulesPattern = /rules:\s*\[([\s\S]*?)\](?=\s*[,}\)])/;
531-
const rulesMatch = updatedContent.match(rulesPattern);
548+
const rulesMatch = findRulesArray(updatedContent);
532549
if (rulesMatch) {
533550
const newRule = ` {
534551
workType: '${workType}',
535552
agents: ['@${agentName}'],
536553
confidence: 'high'
537554
}`;
538-
const existingRules = rulesMatch[1]!.trimEnd();
555+
const existingRules = rulesMatch.entries.trimEnd();
539556
const separator = existingRules.trim() ? ',\n' : '\n';
540557
const updatedRules = existingRules + separator + newRule;
541-
updatedContent = updatedContent.replace(
542-
rulesPattern,
543-
`rules: [${updatedRules}\n ]`
544-
);
558+
updatedContent = updatedContent.slice(0, rulesMatch.start) +
559+
`rules: [${updatedRules}\n ]` + updatedContent.slice(rulesMatch.end);
545560
modified = true;
546561
}
547562
}

‎packages/squad-sdk/src/backend/durable-http-backend.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,9 @@ export function validateBaseUrl(baseUrl: string | undefined): string {
232232
`baseUrl must use https:// (plain http:// is allowed only for localhost / 127.0.0.1 / ::1); got '${url.protocol}//${url.host}'`, 400);
233233
}
234234
if (url.username || url.password) throw new BackendError('invalid-request', 'baseUrl must not embed credentials', 400);
235-
return baseUrl.replace(/\/+$/, '');
235+
let end = baseUrl.length;
236+
while (end > 0 && baseUrl[end - 1] === '/') end--;
237+
return baseUrl.slice(0, end);
236238
}
237239

238240
function toError(res: Response, text: string): BackendError {

‎packages/squad-sdk/src/casting/handwritten-registry.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ export function toAgentId(value: string): string {
6666
.replace(/[\u0300-\u036f]/g, '')
6767
.toLowerCase()
6868
.replace(/[^a-z0-9]+/g, '-')
69-
.replace(/^-+|-+$/g, '');
69+
.replace(/^-|-$/g, '');
7070
}
7171

7272
export interface DroppedRecord { name: string; reason: string }
@@ -757,13 +757,24 @@ export interface TeamRosterMember {
757757
charterId?: string;
758758
}
759759

760-
const UNIVERSE_LINE = /^\s*(?:[-*]\s+)?\*{0,2}universe\*{0,2}\s*:\s*\*{0,2}\s*([^\n|*]+?)\s*$/im;
761-
const UNIVERSE_CELL = /^\s*\|\s*\*{0,2}universe\*{0,2}\s*\|\s*([^|\n]+?)\s*\|/im;
760+
const UNIVERSE_LINE = /^(?:[-*]\s+)?\*{0,2}universe\*{0,2}\s*:(.*)$/i;
761+
const UNIVERSE_CELL = /^\|\s*\*{0,2}universe\*{0,2}\s*\|([^|]+)\|/i;
762762

763763
/** Parse specialist rows from `team.md` (`## Members` table, else the first Name/Role table). */
764764
export function parseTeamRoster(teamMd: string): { members: TeamRosterMember[]; universe?: string } {
765-
const universe = (UNIVERSE_LINE.exec(teamMd)?.[1] ?? UNIVERSE_CELL.exec(teamMd)?.[1])?.replace(/[*_`]/g, '').trim();
766765
const lines = teamMd.split(/\r?\n/);
766+
let universeLine: string | undefined;
767+
let universeCell: string | undefined;
768+
for (const line of lines) {
769+
const text = line.trim();
770+
const lineMatch = UNIVERSE_LINE.exec(text);
771+
if (universeLine === undefined && lineMatch) {
772+
const candidate = lineMatch[1]!.trimStart().replace(/^\*{0,2}/, '').trimStart();
773+
if (candidate && !/[*|]/.test(candidate)) universeLine = candidate;
774+
}
775+
if (universeCell === undefined) universeCell = UNIVERSE_CELL.exec(text)?.[1];
776+
}
777+
const universe = (universeLine ?? universeCell)?.replace(/[*_`]/g, '').trim();
767778
const membersHeading = lines.findIndex((l) => /^##\s+members\b/i.test(l.trim()));
768779
const scope = membersHeading === -1
769780
? lines

‎packages/squad-sdk/src/client/adapters/apply.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,16 @@ export function removeLines(existing: string, lines: readonly string[], id: stri
7373
return rows.join('\n');
7474
}
7575

76-
const SECTION_RE = /^\s*(\[\[?)\s*([^\]\r\n]+?)\s*(\]\]?)\s*(?:#.*)?$/;
76+
const SECTION_RE = /^\s*(\[\[?)([^\]\r\n]+)(\]\]?)\s*(?:#.*)?$/;
77+
78+
function withoutTrailingLineBreaks(value: string): string {
79+
let end = value.length;
80+
while (end > 0 && value[end - 1] === '\n') {
81+
end--;
82+
if (end > 0 && value[end - 1] === '\r') end--;
83+
}
84+
return value.slice(0, end);
85+
}
7786

7887
function segmentsEqual(a: readonly string[], b: readonly string[]): boolean {
7988
return a.length === b.length && a.every((s, idx) => s === b[idx]);
@@ -471,7 +480,7 @@ export function upsertTomlTable(
471480
if (!(k in merged)) merged[k] = v;
472481
}
473482
const body = Object.entries(merged).map(([k, v]) => `${k} = ${v}`);
474-
const cleanedExisting = lines.join(nl).replace(/(\r?\n)*$/, '');
483+
const cleanedExisting = withoutTrailingLineBreaks(lines.join(nl));
475484
const prefix = cleanedExisting === '' ? '' : cleanedExisting + nl + nl;
476485
return `${prefix}${[header, ...body].join(nl)}${nl}`;
477486
}
@@ -798,7 +807,7 @@ export function removeTomlTable(existing: string, table: string): string {
798807
}
799808
if (!changed) return existing;
800809
const joined = lines.join(nl);
801-
return joined.trim() === '' ? '' : joined.replace(/(\r?\n)*$/, nl);
810+
return joined.trim() === '' ? '' : withoutTrailingLineBreaks(joined) + nl;
802811
}
803812

804813
const MCP_CONTAINERS = ['mcpServers', 'mcp', 'servers'];

0 commit comments

Comments
 (0)