Skip to content

Commit

Permalink
Validate and drop invalid imports in BuildMeta (#1063)
Browse files Browse the repository at this point in the history
  • Loading branch information
ije authored Jan 30, 2025
1 parent 86a3532 commit 6daf7d1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
18 changes: 15 additions & 3 deletions server/build_meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package server
import (
"bytes"
"errors"
"strings"

"github.com/ije/gox/utils"
)

type BuildMeta struct {
Expand All @@ -16,8 +19,7 @@ type BuildMeta struct {
}

func encodeBuildMeta(meta *BuildMeta) []byte {
buf, recycle := NewBuffer()
defer recycle()
buf := bytes.NewBuffer(nil)
buf.Write([]byte{'E', 'S', 'M', '\r', '\n'})
if meta.CJS {
buf.Write([]byte{'j', '\n'})
Expand Down Expand Up @@ -82,8 +84,18 @@ func decodeBuildMeta(data []byte) (*BuildMeta, error) {
meta.CSSEntry = string(line[2:])
case ll > 2 && line[0] == 'd' && line[1] == ':':
meta.Dts = string(line[2:])
if !endsWith(meta.Dts, ".ts", ".mts", ".cts") {
return nil, errors.New("invalid dts path")
}
case ll > 2 && line[0] == 'i' && line[1] == ':':
meta.Imports = append(meta.Imports, string(line[2:]))
importSepcifier := string(line[2:])
if !strings.HasSuffix(importSepcifier, ".mjs") {
_, q := utils.SplitByLastByte(importSepcifier, '?')
if q == "" || !strings.Contains(q, "target=") {
return nil, errors.New("invalid import specifier")
}
}
meta.Imports = append(meta.Imports, importSepcifier)
default:
return nil, errors.New("invalid build meta")
}
Expand Down
4 changes: 2 additions & 2 deletions server/build_resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ func (ctx *BuildContext) resolveExternalModule(specifier string, kind api.Resolv
}
}
// mark the resolved path for _preload_
if kind != api.ResolveJSDynamicImport {
if kind == api.ResolveJSImportStatement && !withTypeJSON {
ctx.esmImports = append(ctx.esmImports, [2]string{resolvedPathFull, resolvedPath})
}
// if it's `require("module")` call
Expand All @@ -663,7 +663,7 @@ func (ctx *BuildContext) resolveExternalModule(specifier string, kind api.Resolv
return
}

// if it's the main entry of current package
// if it's `main` entry of current package
if pkgJson := ctx.pkgJson; specifier == pkgJson.Name || specifier == pkgJson.PkgName {
resolvedPath = ctx.getImportPath(EsmPath{
PkgName: pkgJson.Name,
Expand Down

0 comments on commit 6daf7d1

Please sign in to comment.