Skip to content

Commit

Permalink
Fix NPM packages name validation (go-gitea#26595)
Browse files Browse the repository at this point in the history
- Added new tests to cover corner cases
- Replace existing regex with new one
Closes go-gitea#26551 

---
As @silverwind suggested, I started from
[validate-npm-package-name](https://github.com/npm/validate-npm-package-name),
but found this solution too complicated.
Then I tried to fix existing regex myself, but thought, that exclude all
restricted symbols is harder, than set only allowed symbols.
Then I search a bit more and found
[package-name-regex](https://github.com/dword-design/package-name-regex)
and regex from it works for all new test cases.

Let me know, if more information or help with this PR is needed.
  • Loading branch information
TimberBro authored and GiteaBot committed Aug 20, 2023
1 parent b643b2c commit 1c0037e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion modules/packages/npm/creator.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ var (
ErrInvalidIntegrity = util.NewInvalidArgumentErrorf("failed to validate integrity")
)

var nameMatch = regexp.MustCompile(`\A((@[^\s\/~'!\(\)\*]+?)[\/])?([^_.][^\s\/~'!\(\)\*]+)\z`)
var nameMatch = regexp.MustCompile(`^(@[a-z0-9-][a-z0-9-._]*/)?[a-z0-9-][a-z0-9-._]*$`)

// Package represents a npm package
type Package struct {
Expand Down
18 changes: 18 additions & 0 deletions modules/packages/npm/creator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,17 @@ func TestParsePackage(t *testing.T) {
test(t, " test")
test(t, "test ")
test(t, "te st")
test(t, "Test")
test(t, "_test")
test(t, ".test")
test(t, "^test")
test(t, "te^st")
test(t, "te|st")
test(t, "te)(st")
test(t, "te'st")
test(t, "te!st")
test(t, "te*st")
test(t, "te~st")
test(t, "invalid/scope")
test(t, "@invalid/_name")
test(t, "@invalid/.name")
Expand All @@ -93,6 +104,13 @@ func TestParsePackage(t *testing.T) {

test(t, "test")
test(t, "@scope/name")
test(t, "@scope/q")
test(t, "q")
test(t, "@scope/package-name")
test(t, "@scope/package.name")
test(t, "@scope/package_name")
test(t, "123name")
test(t, "----")
test(t, packageFullName)
})

Expand Down

0 comments on commit 1c0037e

Please sign in to comment.