Skip to content

Commit 7846d7c

Browse files
Fix token generation infinite loop bug
Extract alphanumeric characters only when replacing leading/trailing hyphens in generatePortToken(). Previous implementation could randomly select hyphens when trying to remove them, causing potential infinite loops. - Only select from alphanumeric chars when fixing hyphen positions - Add edge case handling for all-hyphen tokens (regenerate) - Ensures RFC 952/1123 DNS hostname compliance Co-authored-by: whoiskatrin <whoiskatrin@users.noreply.github.com>
1 parent cf54f93 commit 7846d7c

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

packages/sandbox/src/sandbox.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1679,14 +1679,21 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
16791679
.toLowerCase();
16801680

16811681
// Ensure token doesn't end with hyphen (RFC 952/1123 requirement)
1682-
// Replace trailing hyphens with alphanumeric chars from the token
1682+
// Replace trailing/leading hyphens with alphanumeric chars only
1683+
const alphanumericChars = token.replace(/-/g, '').split('');
1684+
if (alphanumericChars.length === 0) {
1685+
// Edge case: token is all hyphens, regenerate
1686+
return this.generatePortToken();
1687+
}
1688+
16831689
while (token.endsWith('-')) {
1684-
token = token.slice(0, -1) + token.charAt(Math.floor(Math.random() * (token.length - 1)));
1690+
const randomChar = alphanumericChars[Math.floor(Math.random() * alphanumericChars.length)];
1691+
token = token.slice(0, -1) + randomChar;
16851692
}
16861693

1687-
// Ensure token doesn't start with hyphen
16881694
while (token.startsWith('-')) {
1689-
token = token.charAt(Math.floor(Math.random() * (token.length - 1))) + token.slice(1);
1695+
const randomChar = alphanumericChars[Math.floor(Math.random() * alphanumericChars.length)];
1696+
token = randomChar + token.slice(1);
16901697
}
16911698

16921699
return token;

0 commit comments

Comments
 (0)