Skip to content

Commit 1c0037e

Browse files
TimberBroGiteaBot
authored andcommitted
Fix NPM packages name validation (go-gitea#26595)
- 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.
1 parent b643b2c commit 1c0037e

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

modules/packages/npm/creator.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ var (
3434
ErrInvalidIntegrity = util.NewInvalidArgumentErrorf("failed to validate integrity")
3535
)
3636

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

3939
// Package represents a npm package
4040
type Package struct {

modules/packages/npm/creator_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,17 @@ func TestParsePackage(t *testing.T) {
6767
test(t, " test")
6868
test(t, "test ")
6969
test(t, "te st")
70+
test(t, "Test")
71+
test(t, "_test")
72+
test(t, ".test")
73+
test(t, "^test")
74+
test(t, "te^st")
75+
test(t, "te|st")
76+
test(t, "te)(st")
77+
test(t, "te'st")
78+
test(t, "te!st")
79+
test(t, "te*st")
80+
test(t, "te~st")
7081
test(t, "invalid/scope")
7182
test(t, "@invalid/_name")
7283
test(t, "@invalid/.name")
@@ -93,6 +104,13 @@ func TestParsePackage(t *testing.T) {
93104

94105
test(t, "test")
95106
test(t, "@scope/name")
107+
test(t, "@scope/q")
108+
test(t, "q")
109+
test(t, "@scope/package-name")
110+
test(t, "@scope/package.name")
111+
test(t, "@scope/package_name")
112+
test(t, "123name")
113+
test(t, "----")
96114
test(t, packageFullName)
97115
})
98116

0 commit comments

Comments
 (0)