Update to Anubis v1.28.2 (#1)

This upgrades the Masyunis fork from Anubis v1.25.0 to the latest stable release, **v1.28.2** (“Wuk Lamat Echo 2”), while keeping the fork’s custom styling and removals.

## Approach

The Gitea repo is a tree snapshot of v1.25.0, not a git-level fork of [TecharoHQ/anubis](https://github.com/TecharoHQ/anubis). The histories share no commits, so a merge or rebase onto the upstream tag is not usable.

The first commit on this branch replaces the tree with a snapshot of the **v1.28.2** tag (`git rm -r` plus `git checkout v1.28.2 -- .`; the import tree is identical to the tag). A short patch series on top restores the Masyunis customizations.

## Customizations kept

- Masyunya mascots (`web/static/img/{happy,pensive,reject}.webp`), hashes match current `master`.
- `web/static/img/ATTRIBUTIONS.txt` stays deleted.
- Challenge footer: drop the `made_with` (Canada / maple-leaf) line and the CELPHASE mascot credit; keep “Protected by Anubis from Techaro”. The generated `web/index_templ.go` matches `go generate ./web`.
- Short README (the old `anubisc` typo is fixed).
- Version stamped `v1.28.2/masyunis` via Makefile ldflags. `anubis.go` `init()` does not overwrite a link-time version; `go run` / `go test` still report `devel` on purpose.
- Upstream `.github`, `.devcontainer`, `.husky`, and `.vscode` stay deleted.
- `"uk"` is removed from `lib/localization/locales/manifest.json` **on purpose**, because of Alpine locale problems. `uk.json` and its test entry stay; the served manifest lists 27 languages.
- `package.json` `prepare` no longer runs `husky` (the hooks directory is gone). The rest of the script is unchanged. `husky` remains in devDependencies, as upstream left it.

## Deploy notes

- **Cookie rename (v1.27):** with the default `DYNAMIC_COOKIE_SUFFIX=true`, cookie names become e.g. `techaro.lol-anubis-auth-<hash>`. Existing clients get a **one-time re-challenge**. That is expected, not a loop.
- **Docker / ko / yeet builds** skip the Makefile ldflags, so the displayed version is `<git-version>/masyunis`. It is `v1.28.2/masyunis` only when built from a `v1.28.2` tag (or via `make build` / `make prebaked-build`).
- Go 1.27.3 is required (upstream bump in v1.28.2). Thoth (`THOTH_URL` / `THOTH_TOKEN`) was removed upstream; those settings now warn and do nothing. New WASM challenge methods stay disabled unless opted in.

## Verification

- `make build` succeeds. `./var/anubis --version` prints `Anubis v1.28.2/masyunis`.
- `SKIP_INTEGRATION=1 go test ./...` passes (unit tests; integration package is skipped).
- Local challenge/reject pages (en and ru) show Masyunya, version `v1.28.2/masyunis`, and no Canada / CELPHASE / mascot-credit text. Screenshots:

![Challenge page (en)](https://git.unvr.site/attachments/36112ff0-5155-495c-8bd2-59606ee3bd64)
![Reject page (en)](https://git.unvr.site/attachments/2cad0256-1b0e-4f71-8d06-d1a447fd5263)

- Upstream Playwright tests (`make test` without `SKIP_INTEGRATION`) fail on this box because the browser download fails. A clean v1.28.2 tree fails the same three Playwright tests here, so this is not a fork regression.
- `npm audit` reports **4** findings in upstream’s lockfile (2 moderate, 2 high: `brace-expansion`, `fast-uri`, `lodash.trim`, `source-map-js`). Left alone.

Please review and merge when ready. I will not merge this myself.

Reviewed-on: #1
Co-authored-by: Lead <3+lead_bot@noreply.git.unvr.site>
This commit was merged in pull request #1.
This commit is contained in:
sol_bot Bot authored and matiashik committed 2026-11-28 12:10:27 +00:00
1 parent eb3e46d8d0
commit caf4d72880
529 files changed
+33015 -6659

No files matched your search

+437
View File
@@ -0,0 +1,437 @@
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net/http"
"net/netip"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/facebookgo/flagenv"
"gopkg.in/yaml.v3"
)
var (
dataDir = flag.String("data-dir", "data/crawlers", "folder holding the crawler policy files")
dryRun = flag.Bool("dry-run", false, "report what would change but don't write any files")
list = flag.Bool("list", false, "list every crawler this tool can update, then exit")
slogLevel = flag.String("slog-level", "INFO", "logging level (DEBUG, INFO, WARN, ERROR)")
timeout = flag.Duration("timeout", 30*time.Second, "how long to wait for a single feed")
userAgent = flag.String("user-agent", "Anubis-botgenerate (+https://github.com/TecharoHQ/anubis)", "User-Agent to send when fetching feeds")
)
var (
ErrNoSuchCrawler = errors.New("botgenerate: no crawler by that name")
ErrRuleNotFound = errors.New("botgenerate: policy file has no rule by that name")
ErrNoRemoteAddresses = errors.New("botgenerate: rule has no remote_addresses field")
ErrNoPrefixes = errors.New("botgenerate: feed returned no usable prefixes")
ErrUnexpectedStatus = errors.New("botgenerate: feed returned an unexpected HTTP status")
)
// Source says where one crawler's IP range list comes from.
type Source struct {
// File is the policy file to update, relative to --data-dir. Its name
// without the extension is how the crawler is named on the command line.
File string
// Rule is the name of the rule inside File whose remote_addresses list gets
// replaced. A policy file may hold more than one rule.
Rule string
// URL is the operator's published feed.
URL string
}
// Name is how this crawler is spelled on the command line.
func (s Source) Name() string {
return strings.TrimSuffix(s.File, filepath.Ext(s.File))
}
func (s Source) LogValue() slog.Value {
return slog.GroupValue(
slog.String("file", s.File),
slog.String("rule", s.Rule),
slog.String("url", s.URL),
)
}
var sources = []Source{
{
File: "applebot.yaml",
Rule: "applebot",
URL: "https://search.developer.apple.com/applebot.json",
},
{
File: "bingbot.yaml",
Rule: "bingbot",
URL: "https://www.bing.com/toolbox/bingbot.json",
},
{
File: "commoncrawl.yaml",
Rule: "common-crawl",
URL: "https://index.commoncrawl.org/ccbot.json",
},
{
File: "duckduckbot.yaml",
Rule: "duckduckbot",
URL: "https://duckduckgo.com/duckduckbot.json",
},
{
// The list of Google crawlers that respect robots.txt
// https://developers.google.com/crawling/docs/crawlers-fetchers/verify-google-requests
File: "googlebot.yaml",
Rule: "googlebot",
URL: "https://developers.google.com/static/crawling/ipranges/common-crawlers.json",
},
{
File: "mojeekbot.yaml",
Rule: "mojeekbot",
URL: "https://www.mojeek.com/mojeekbot.json",
},
{
File: "openai-gptbot.yaml",
Rule: "openai-gptbot",
URL: "https://openai.com/gptbot.json",
},
{
File: "openai-searchbot.yaml",
Rule: "openai-searchbot",
URL: "https://openai.com/searchbot.json",
},
{
File: "perplexitybot.yaml",
Rule: "perplexitybot",
URL: "https://www.perplexity.com/perplexitybot.json",
},
{
File: "qwantbot.yaml",
Rule: "qwantbot",
URL: "https://help.qwant.com/wp-content/uploads/sites/latest/qwantbot.json",
},
}
func init() {
flag.Usage = func() {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), `Usage of %[1]s:
%[1]s [flags] [crawler...]
Updates the remote_addresses list of each crawler from the IP range lists
their operators publish. If no crawler is passed, it updates everything.
After running this, run npm run format
Flags:
`, filepath.Base(os.Args[0]))
flag.PrintDefaults()
}
}
func main() {
flagenv.Parse()
flag.Parse()
var lvl slog.Level
if err := lvl.UnmarshalText([]byte(*slogLevel)); err != nil {
fmt.Fprintf(os.Stderr, "--slog-level=%q is invalid: %v\n", *slogLevel, err)
os.Exit(2)
}
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: lvl})))
if *list {
for _, src := range sources {
fmt.Printf("%-20s %s\n", src.Name(), src.URL)
}
return
}
want, err := selectSources(flag.Args())
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n\nRun %s --list to see every known crawler.\n", err, filepath.Base(os.Args[0]))
os.Exit(2)
}
u := &updater{
cli: &http.Client{Timeout: *timeout},
dataDir: *dataDir,
dryRun: *dryRun,
userAgent: *userAgent,
}
var errs []error
for _, src := range want {
if err := u.update(src); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", src.Name(), err))
}
}
if len(errs) != 0 {
slog.Error("could not update every crawler", "err", errors.Join(errs...))
os.Exit(1)
}
}
func selectSources(names []string) ([]Source, error) {
if len(names) == 0 {
return sources, nil
}
var (
want []Source
errs []error
)
for _, name := range names {
idx := slices.IndexFunc(sources, func(s Source) bool { return s.Name() == name })
if idx == -1 {
errs = append(errs, fmt.Errorf("%w: %q", ErrNoSuchCrawler, name))
continue
}
want = append(want, sources[idx])
}
if len(errs) != 0 {
return nil, errors.Join(errs...)
}
return want, nil
}
type updater struct {
cli *http.Client
dataDir string
dryRun bool
userAgent string
}
func (u *updater) update(src Source) error {
lg := slog.With("crawler", src.Name())
prefixes, err := u.fetchPrefixes(src.URL)
if err != nil {
return err
}
fname := filepath.Join(u.dataDir, src.File)
data, err := os.ReadFile(fname)
if err != nil {
return fmt.Errorf("can't read policy file: %w", err)
}
var root yaml.Node
if err := yaml.Unmarshal(data, &root); err != nil {
return fmt.Errorf("can't parse %s: %w", fname, err)
}
old, err := setRemoteAddresses(&root, src.Rule, prefixes)
if err != nil {
return fmt.Errorf("can't update %s: %w", fname, err)
}
added, removed := diff(old, prefixes)
if len(added) == 0 && len(removed) == 0 {
lg.Info("already up to date", "prefixes", len(prefixes))
return nil
}
lg.Info("IP ranges changed", "added", len(added), "removed", len(removed), "total", len(prefixes))
lg.Debug("IP ranges changed", "added", added, "removed", removed)
if u.dryRun {
return nil
}
out, err := marshal(&root)
if err != nil {
return fmt.Errorf("can't serialize %s: %w", fname, err)
}
if err := os.WriteFile(fname, out, 0o644); err != nil {
return fmt.Errorf("can't write %s: %w", fname, err)
}
lg.Info("wrote policy file", "file", fname)
return nil
}
// prefixList is the common subset of JSON fields in search engine IP prefix feeds
type prefixList struct {
Prefixes []struct {
IPv4Prefix string `json:"ipv4Prefix"`
IPv6Prefix string `json:"ipv6Prefix"`
} `json:"prefixes"`
}
func (u *updater) fetchPrefixes(url string) ([]string, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("can't build request for %s: %w", url, err)
}
req.Header.Set("User-Agent", u.userAgent)
req.Header.Set("Accept", "application/json")
resp, err := u.cli.Do(req)
if err != nil {
return nil, fmt.Errorf("can't fetch %s: %w", url, err)
}
defer resp.Body.Close() //nolint:errcheck
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%w: %s returned %s", ErrUnexpectedStatus, url, resp.Status)
}
prefixes, err := parsePrefixes(resp.Body)
if err != nil {
return nil, fmt.Errorf("can't read %s: %w", url, err)
}
return prefixes, nil
}
func parsePrefixes(r io.Reader) ([]string, error) {
var pl prefixList
if err := json.NewDecoder(r).Decode(&pl); err != nil {
return nil, fmt.Errorf("can't decode prefix list: %w", err)
}
var prefixes []string
for i, p := range pl.Prefixes {
var raw string
switch {
case p.IPv4Prefix != "":
raw = p.IPv4Prefix
case p.IPv6Prefix != "":
raw = p.IPv6Prefix
default:
return nil, fmt.Errorf("prefix %d has neither ipv4Prefix nor ipv6Prefix", i)
}
pfx, err := netip.ParsePrefix(raw)
if err != nil {
return nil, fmt.Errorf("prefix %d (%q) is not a CIDR range: %w", i, raw, err)
}
prefixes = append(prefixes, pfx.String())
}
if len(prefixes) == 0 {
return nil, ErrNoPrefixes
}
return prefixes, nil
}
func setRemoteAddresses(root *yaml.Node, rule string, prefixes []string) ([]string, error) {
if len(root.Content) == 0 {
return nil, fmt.Errorf("%w: %s (file is empty)", ErrRuleNotFound, rule)
}
for _, node := range root.Content[0].Content {
name := mappingValue(node, "name")
if name == nil || name.Value != rule {
continue
}
addrs := mappingValue(node, "remote_addresses")
if addrs == nil {
return nil, fmt.Errorf("%w: %s", ErrNoRemoteAddresses, rule)
}
old := make([]string, 0, len(addrs.Content))
for _, item := range addrs.Content {
old = append(old, item.Value)
}
var style yaml.Style
if addrs.Style&yaml.FlowStyle != 0 {
style = yaml.DoubleQuotedStyle
}
content := make([]*yaml.Node, 0, len(prefixes))
for _, prefix := range prefixes {
content = append(content, &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: prefix,
Style: style,
})
}
addrs.Kind = yaml.SequenceNode
addrs.Tag = "!!seq"
addrs.Content = content
return old, nil
}
return nil, fmt.Errorf("%w: %s", ErrRuleNotFound, rule)
}
func mappingValue(node *yaml.Node, key string) *yaml.Node {
if node.Kind != yaml.MappingNode {
return nil
}
for i := 0; i+1 < len(node.Content); i += 2 {
if node.Content[i].Value == key {
return node.Content[i+1]
}
}
return nil
}
func marshal(root *yaml.Node) ([]byte, error) {
var buf strings.Builder
enc := yaml.NewEncoder(&buf)
enc.SetIndent(2)
if err := enc.Encode(root); err != nil {
return nil, err
}
if err := enc.Close(); err != nil {
return nil, err
}
return []byte(buf.String()), nil
}
func diff(before, after []string) (added, removed []string) {
inBefore := make(map[string]struct{}, len(before))
for _, prefix := range before {
inBefore[prefix] = struct{}{}
}
inAfter := make(map[string]struct{}, len(after))
for _, prefix := range after {
inAfter[prefix] = struct{}{}
}
for _, prefix := range after {
if _, ok := inBefore[prefix]; !ok {
added = append(added, prefix)
}
}
for _, prefix := range before {
if _, ok := inAfter[prefix]; !ok {
removed = append(removed, prefix)
}
}
return added, removed
}
+586
View File
@@ -0,0 +1,586 @@
package main
import (
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
func TestParsePrefixes(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
input string
want []string
err error
}{
{
name: "ipv4 and ipv6",
input: `{"prefixes":[{"ipv4Prefix":"192.0.2.0/24"},{"ipv6Prefix":"2001:db8::/32"}]}`,
want: []string{"192.0.2.0/24", "2001:db8::/32"},
},
{
name: "ignores unrelated fields",
input: `{"creationTime":"2026-08-31T14:46:46.000000","notes":"hi","prefixes":[{"ipv4Prefix":"192.0.2.0/24"}]}`,
want: []string{"192.0.2.0/24"},
},
{
name: "no prefixes",
input: `{"prefixes":[]}`,
err: ErrNoPrefixes,
},
{
name: "empty prefix entry",
input: `{"prefixes":[{"ipv4Prefix":"192.0.2.0/24"},{}]}`,
},
{
name: "bare address is not a prefix",
input: `{"prefixes":[{"ipv4Prefix":"192.0.2.1"}]}`,
},
{
name: "garbage prefix",
input: `{"prefixes":[{"ipv4Prefix":"not-an-ip/24"}]}`,
},
{
name: "not json",
input: `<html>go away</html>`,
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got, err := parsePrefixes(strings.NewReader(tt.input))
if tt.want == nil {
if err == nil {
t.Logf("got: %v", got)
t.Fatal("wanted an error but parsing succeeded")
}
if tt.err != nil && !errors.Is(err, tt.err) {
t.Logf("want: %v", tt.err)
t.Logf("got: %v", err)
t.Error("got wrong error")
}
return
}
if err != nil {
t.Fatalf("can't parse prefix list: %v", err)
}
if !slices.Equal(got, tt.want) {
t.Logf("want: %v", tt.want)
t.Logf("got: %v", got)
t.Error("got wrong prefixes")
}
})
}
}
func TestSetRemoteAddresses(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
input string
rule string
want []string
wantOld []string
err error
}{
{
name: "block style rule",
input: `- name: googlebot
user_agent_regex: \+http\://www\.google\.com/bot\.html
action: ALLOW
remote_addresses:
- 192.0.2.0/24
`,
rule: "googlebot",
want: []string{"198.51.100.0/24"},
wantOld: []string{"192.0.2.0/24"},
},
{
name: "picks the right rule in a multi rule file",
input: `- name: first
action: ALLOW
remote_addresses: ["192.0.2.0/24"]
- name: second
action: ALLOW
remote_addresses: ["203.0.113.0/24"]
`,
rule: "second",
want: []string{"198.51.100.0/24"},
wantOld: []string{"203.0.113.0/24"},
},
{
name: "rule is missing",
input: `- name: googlebot
action: ALLOW
remote_addresses: ["192.0.2.0/24"]
`,
rule: "bingbot",
err: ErrRuleNotFound,
},
{
name: "rule has no remote_addresses",
input: `- name: yandexbot
action: ALLOW
`,
rule: "yandexbot",
err: ErrNoRemoteAddresses,
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var root yaml.Node
if err := yaml.Unmarshal([]byte(tt.input), &root); err != nil {
t.Fatalf("can't parse test fixture: %v", err)
}
old, err := setRemoteAddresses(&root, tt.rule, tt.want)
if tt.err != nil {
if !errors.Is(err, tt.err) {
t.Logf("want: %v", tt.err)
t.Logf("got: %v", err)
t.Error("got wrong error")
}
return
}
if err != nil {
t.Fatalf("can't set remote addresses: %v", err)
}
if !slices.Equal(old, tt.wantOld) {
t.Logf("want: %v", tt.wantOld)
t.Logf("got: %v", old)
t.Error("got wrong previous addresses")
}
data, err := marshal(&root)
if err != nil {
t.Fatalf("can't serialize result: %v", err)
}
var rules []struct {
Name string `yaml:"name"`
RemoteAddr []string `yaml:"remote_addresses"`
}
if err := yaml.Unmarshal(data, &rules); err != nil {
t.Fatalf("can't reparse result: %v", err)
}
idx := slices.IndexFunc(rules, func(r struct {
Name string `yaml:"name"`
RemoteAddr []string `yaml:"remote_addresses"`
}) bool {
return r.Name == tt.rule
})
if idx == -1 {
t.Fatalf("rule %s vanished from the result:\n%s", tt.rule, data)
}
if !slices.Equal(rules[idx].RemoteAddr, tt.want) {
t.Logf("want: %v", tt.want)
t.Logf("got: %v", rules[idx].RemoteAddr)
t.Error("got wrong addresses in output")
}
})
}
}
func TestSetRemoteAddressesKeepsComments(t *testing.T) {
t.Parallel()
const input = `# Indexing for search and Siri
# https://support.apple.com/en-us/119829
- name: applebot
user_agent_regex: Applebot
action: ALLOW
# https://search.developer.apple.com/applebot.json
remote_addresses: ["17.241.208.160/27"]
# trailing note
`
var root yaml.Node
if err := yaml.Unmarshal([]byte(input), &root); err != nil {
t.Fatalf("can't parse test fixture: %v", err)
}
if _, err := setRemoteAddresses(&root, "applebot", []string{"192.0.2.0/24"}); err != nil {
t.Fatalf("can't set remote addresses: %v", err)
}
data, err := marshal(&root)
if err != nil {
t.Fatalf("can't serialize result: %v", err)
}
for _, want := range []string{
"# Indexing for search and Siri",
"# https://support.apple.com/en-us/119829",
"# https://search.developer.apple.com/applebot.json",
"# trailing note",
"user_agent_regex: Applebot",
} {
if !strings.Contains(string(data), want) {
t.Logf("want to find: %q", want)
t.Logf("got:\n%s", data)
t.Error("output lost part of the original file")
}
}
}
func TestSetRemoteAddressesKeepsStyle(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
input string
want string
}{
{
name: "flow style quotes every prefix",
input: "- name: applebot\n remote_addresses: [\"192.0.2.0/24\"]\n",
want: `remote_addresses: ["198.51.100.0/24", "2001:db8::/32"]`,
},
{
name: "block style leaves prefixes bare",
input: "- name: applebot\n remote_addresses:\n - 192.0.2.0/24\n",
want: "remote_addresses:\n - 198.51.100.0/24\n - 2001:db8::/32",
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var root yaml.Node
if err := yaml.Unmarshal([]byte(tt.input), &root); err != nil {
t.Fatalf("can't parse test fixture: %v", err)
}
if _, err := setRemoteAddresses(&root, "applebot", []string{"198.51.100.0/24", "2001:db8::/32"}); err != nil {
t.Fatalf("can't set remote addresses: %v", err)
}
data, err := marshal(&root)
if err != nil {
t.Fatalf("can't serialize result: %v", err)
}
if !strings.Contains(string(data), tt.want) {
t.Logf("want to find:\n%s", tt.want)
t.Logf("got:\n%s", data)
t.Error("wrote the prefixes in the wrong style")
}
})
}
}
func TestSelectSources(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
input []string
want []string
err error
}{
{
name: "no arguments selects everything",
input: nil,
want: allSourceNames(),
},
{
name: "by name",
input: []string{"googlebot", "bingbot"},
want: []string{"googlebot", "bingbot"},
},
{
name: "unknown crawler",
input: []string{"googlebot", "clippy"},
err: ErrNoSuchCrawler,
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got, err := selectSources(tt.input)
if tt.err != nil {
if !errors.Is(err, tt.err) {
t.Logf("want: %v", tt.err)
t.Logf("got: %v", err)
t.Error("got wrong error")
}
return
}
if err != nil {
t.Fatalf("can't select sources: %v", err)
}
var names []string
for _, src := range got {
names = append(names, src.Name())
}
if !slices.Equal(names, tt.want) {
t.Logf("want: %v", tt.want)
t.Logf("got: %v", names)
t.Error("selected the wrong crawlers")
}
})
}
}
func TestSourcesMatchDataFiles(t *testing.T) {
t.Parallel()
const dir = "../../../data/crawlers"
for _, src := range sources {
t.Run(src.Name(), func(t *testing.T) {
t.Parallel()
data, err := os.ReadFile(filepath.Join(dir, src.File))
if err != nil {
t.Fatalf("can't read policy file: %v", err)
}
var rules []struct {
Name string `yaml:"name"`
RemoteAddr []string `yaml:"remote_addresses"`
}
if err := yaml.Unmarshal(data, &rules); err != nil {
t.Fatalf("can't parse policy file: %v", err)
}
for _, rule := range rules {
if rule.Name != src.Rule {
continue
}
if len(rule.RemoteAddr) == 0 {
t.Errorf("rule %s has no remote_addresses to update", src.Rule)
}
return
}
t.Errorf("%s declares no rule named %q", src.File, src.Rule)
})
}
}
func TestUpdate(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("User-Agent"); got != "test-agent" {
t.Errorf("wanted User-Agent test-agent, got: %s", got)
}
w.Header().Set("Content-Type", "application/json")
writePrefixes(t, w)
}))
t.Cleanup(srv.Close)
dir := t.TempDir()
fname := filepath.Join(dir, "googlebot.yaml")
const input = `- name: googlebot
action: ALLOW
# source of truth
remote_addresses:
- 192.0.2.0/24
`
if err := os.WriteFile(fname, []byte(input), 0o644); err != nil {
t.Fatalf("can't write test fixture: %v", err)
}
src := Source{File: "googlebot.yaml", Rule: "googlebot", URL: srv.URL}
t.Run("dry run leaves the file alone", func(t *testing.T) {
u := &updater{cli: srv.Client(), dataDir: dir, dryRun: true, userAgent: "test-agent"}
if err := u.update(src); err != nil {
t.Fatalf("can't update: %v", err)
}
got, err := os.ReadFile(fname)
if err != nil {
t.Fatalf("can't read file back: %v", err)
}
if string(got) != input {
t.Logf("want:\n%s", input)
t.Logf("got:\n%s", got)
t.Error("dry run wrote to the file")
}
})
t.Run("writes the new prefixes", func(t *testing.T) {
u := &updater{cli: srv.Client(), dataDir: dir, userAgent: "test-agent"}
if err := u.update(src); err != nil {
t.Fatalf("can't update: %v", err)
}
got, err := os.ReadFile(fname)
if err != nil {
t.Fatalf("can't read file back: %v", err)
}
for _, want := range []string{"198.51.100.0/24", "2001:db8::/32", "# source of truth"} {
if !strings.Contains(string(got), want) {
t.Logf("want to find: %q", want)
t.Logf("got:\n%s", got)
t.Error("output is missing something")
}
}
if strings.Contains(string(got), "192.0.2.0/24") {
t.Logf("got:\n%s", got)
t.Error("stale prefix survived the update")
}
})
}
func TestUpdateRejectsBadFeed(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
status int
body string
wantErr error
}{
{name: "server error", status: http.StatusInternalServerError, body: "nope", wantErr: ErrUnexpectedStatus},
{name: "empty feed", status: http.StatusOK, body: `{"prefixes":[]}`, wantErr: ErrNoPrefixes},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.status)
if _, err := w.Write([]byte(tt.body)); err != nil {
t.Errorf("can't write response: %v", err)
}
}))
t.Cleanup(srv.Close)
dir := t.TempDir()
fname := filepath.Join(dir, "googlebot.yaml")
const input = "- name: googlebot\n action: ALLOW\n remote_addresses:\n - 192.0.2.0/24\n"
if err := os.WriteFile(fname, []byte(input), 0o644); err != nil {
t.Fatalf("can't write test fixture: %v", err)
}
u := &updater{cli: srv.Client(), dataDir: dir, userAgent: "test-agent"}
err := u.update(Source{File: "googlebot.yaml", Rule: "googlebot", URL: srv.URL})
if !errors.Is(err, tt.wantErr) {
t.Logf("want: %v", tt.wantErr)
t.Logf("got: %v", err)
t.Error("got wrong error")
}
got, err := os.ReadFile(fname)
if err != nil {
t.Fatalf("can't read file back: %v", err)
}
if string(got) != input {
t.Logf("got:\n%s", got)
t.Error("a failed fetch must not touch the policy file")
}
})
}
}
func TestDiff(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
old, cur []string
wantAdded []string
wantRemoved []string
}{
{
name: "no change",
old: []string{"192.0.2.0/24"},
cur: []string{"192.0.2.0/24"},
},
{
name: "reordering is not a change",
old: []string{"192.0.2.0/24", "198.51.100.0/24"},
cur: []string{"198.51.100.0/24", "192.0.2.0/24"},
wantAdded: nil,
},
{
name: "added and removed",
old: []string{"192.0.2.0/24", "203.0.113.0/24"},
cur: []string{"192.0.2.0/24", "198.51.100.0/24"},
wantAdded: []string{"198.51.100.0/24"},
wantRemoved: []string{"203.0.113.0/24"},
},
{
name: "first run",
cur: []string{"192.0.2.0/24"},
wantAdded: []string{"192.0.2.0/24"},
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
added, removed := diff(tt.old, tt.cur)
if !slices.Equal(added, tt.wantAdded) {
t.Logf("want: %v", tt.wantAdded)
t.Logf("got: %v", added)
t.Error("got wrong added prefixes")
}
if !slices.Equal(removed, tt.wantRemoved) {
t.Logf("want: %v", tt.wantRemoved)
t.Logf("got: %v", removed)
t.Error("got wrong removed prefixes")
}
})
}
}
func allSourceNames() []string {
var names []string
for _, src := range sources {
names = append(names, src.Name())
}
return names
}
func writePrefixes(t *testing.T, w http.ResponseWriter) {
t.Helper()
const body = `{"prefixes":[{"ipv4Prefix":"198.51.100.0/24"},{"ipv6Prefix":"2001:db8::/32"}]}`
if _, err := w.Write([]byte(body)); err != nil {
t.Errorf("can't write response: %v", err)
}
}
+49 -16
View File
@@ -7,26 +7,19 @@ import (
"net/http"
"net/netip"
"strings"
"github.com/TecharoHQ/anubis/internal/iplist"
)
// FetchBlocklist reads the blocklist over HTTP and returns every non-commented
// ParseBlocklist reads a plain-text blocklist and returns every non-commented
// line parsed as an IP address in CIDR notation. IPv4 addresses are returned as
// /32, IPv6 addresses as /128.
//
// This function was generated with GLM 4.7.
func FetchBlocklist(url string) ([]string, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
func ParseBlocklist(list io.Reader) ([]string, error) {
var addrs []string
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP request failed with status: %s", resp.Status)
}
var lines []string
scanner := bufio.NewScanner(resp.Body)
scanner := bufio.NewScanner(list)
for scanner.Scan() {
line := scanner.Text()
// Skip empty lines and comments (lines starting with #)
@@ -46,12 +39,52 @@ func FetchBlocklist(url string) ([]string, error) {
} else {
cidr = fmt.Sprintf("%s/128", addr.String())
}
lines = append(lines, cidr)
addrs = append(addrs, cidr)
}
if err := scanner.Err(); err != nil && err != io.EOF {
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
return addrs, nil
}
// FetchBlocklist fetches url over HTTP and parses the response body as a
// blocklist. JSON responses (detected via the Content-Type header or a
// ".json" URL suffix) are parsed with ParsePrefixList; everything else is
// treated as a plain-text list and parsed with ParseBlocklist.
func FetchBlocklist(url string) ([]string, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close() //nolint:errcheck
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP request failed with status: %s", resp.Status)
}
if isJSONBlocklist(url, resp.Header.Get("Content-Type")) {
return ParsePrefixList(resp.Body)
}
return ParseBlocklist(resp.Body)
}
func isJSONBlocklist(url, contentType string) bool {
if contentType == "json" {
return true
}
return strings.HasSuffix(strings.ToLower(url), ".json")
}
// ParsePrefixList decodes a JSON document read from list in the Google/OpenAI
// bot IP range format and returns every IPv4 and IPv6 prefix it contains.
func ParsePrefixList(list io.Reader) ([]string, error) {
pl, err := iplist.Parse(list)
if err != nil {
return nil, err
}
return pl.CIDRs(), nil
}
+11 -4
View File
@@ -90,14 +90,21 @@ func main() {
if err != nil {
log.Fatalf("can't create output file %q: %v", foutName, err)
}
defer fout.Close()
fmt.Fprintf(fout, "# Generated by %s on %s from %s\n\n", filepath.Base(os.Args[0]), time.Now().Format(time.RFC3339), blocklistURL)
if _, err := fmt.Fprintf(fout, "# Generated by %s on %s from %s\n\n", filepath.Base(os.Args[0]), time.Now().Format(time.RFC3339), blocklistURL); err != nil {
log.Fatalf("can't write signature line: %v", err)
}
data, err := yaml.Marshal([]*Rule{result})
if err != nil {
log.Fatalf("can't marshal yaml")
log.Fatalf("can't marshal yaml: %v", err)
}
fout.Write(data)
if _, err := fout.Write(data); err != nil {
log.Fatalf("can't write data: %v", err)
}
if err := fout.Close(); err != nil {
log.Fatalf("can't close file: %v", err)
}
}
+108
View File
@@ -0,0 +1,108 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
"github.com/tetratelabs/wazero/experimental"
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
"github.com/tetratelabs/wazero/sys"
)
func defaultCacheDir() string {
dir, err := os.UserCacheDir()
if err != nil {
path := filepath.Join(os.Getenv("HOME"), ".cache", "techaro.lol", "anubis", "wazero-exec")
_ = os.MkdirAll(path, 0755)
return path
}
path := filepath.Join(dir, "techaro.lol", "anubis", "wazero-exec")
_ = os.MkdirAll(path, 0755)
return path
}
var (
cacheDir = flag.String("cache-dir", defaultCacheDir(), "default compilation cache folder")
)
func main() {
flag.Parse()
if flag.NArg() == 0 {
fmt.Fprintf(os.Stderr, "usage: %s <file.wasm> [args]\n\n", filepath.Base(os.Args[0]))
flag.Usage()
os.Exit(2)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := run(ctx, flag.Arg(0), flag.Args()); err != nil {
fmt.Fprintf(os.Stderr, "can't run program %s: %v\n", flag.Arg(0), err)
var exitErr *sys.ExitError
if errors.As(err, &exitErr) && exitErr.ExitCode() != 0 {
os.Exit(int(exitErr.ExitCode()))
}
os.Exit(1)
}
}
func run(ctx context.Context, fname string, args []string) error {
cache, err := wazero.NewCompilationCacheWithDir(*cacheDir)
if err != nil {
return fmt.Errorf("can't open cache folder %q: %w", *cacheDir, err)
}
cfg := wazero.NewRuntimeConfig().
WithCompilationCache(cache).
WithCoreFeatures(api.CoreFeaturesV2 | experimental.CoreFeaturesExceptionHandling | experimental.CoreFeaturesExtendedConst | experimental.CoreFeaturesTailCall)
runtime := wazero.NewRuntimeWithConfig(ctx, cfg)
wasi_snapshot_preview1.MustInstantiate(ctx, runtime)
bin, err := os.ReadFile(fname)
if err != nil {
return fmt.Errorf("can't read file %s: %w", fname, err)
}
compiled, err := runtime.CompileModule(ctx, bin)
if err != nil {
return fmt.Errorf("can't compile binary %s: %w", fname, err)
}
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("[unexpected] can't get cwd: %w", err)
}
fsConfig := wazero.NewFSConfig().WithDirMount(cwd, "/")
config := wazero.NewModuleConfig().
WithStdin(os.Stdin).WithStdout(os.Stdout).WithStderr(os.Stderr).
WithArgs(args...).WithName(filepath.Base(fname)).WithFSConfig(fsConfig).
WithSysNanosleep().WithSysNanotime().WithSysWalltime()
for _, kp := range os.Environ() {
kv := strings.SplitN(kp, "=", 2)
config = config.WithEnv(kv[0], kv[1])
}
mod, err := runtime.InstantiateModule(ctx, compiled, config)
if err != nil {
return fmt.Errorf("can't instantiate module: %w", err)
}
if err := mod.Close(ctx); err != nil {
return err
}
return nil
}
+15
View File
@@ -0,0 +1,15 @@
# Pre-built wasm2js binaries
The existience of this folder is a bit of a crime. Let me elaborate.
Anubis uses WebAssembly based checks so that it can have the proof of work run as _efficiently as possible_. This includes using the simd128 extension in WebAssembly so that clients take maximum possible advantage of their hardware. The goal of this is to make Anubis _go away as fast as it can_ so people don't see it for too long and complain.
However, many "privacy browsers", iOS Lockdown Mode, and other "enhanced web privacy" configuration guides tell people to disable WebAssembly. This would mean that clients that can't/won't execute WebAssembly are de-facto blocked from the service Anubis protects.
As a middle ground, the WebAssembly modules are compiled down to JavaScript a-la [Metal in The Birth and Death of JavaScript](https://www.destroyallsoftware.com/talks/the-birth-and-death-of-javascript). This will at least let the check logic run on client machines. It won't run efficiently as most of the configurations that disable WebAssembly also disable browser JIT engines, but it will _eventually_ finish.
The catch that makes this folder need to exist is that the tool that's being used for this, [wasm2js from binaryen](https://github.com/WebAssembly/binaryen), is packaged in distro repositories. The downside of the distro packaging is that it is _woefully_ out of date compared to what is required to actually compile the WebAssembly to JavaScript. This leaves us in a bit of a pickle.
The middle path here is to use WebAssembly to ship _the known working version_ of wasm2js in the git repo as well as the [build.sh](./build.sh) script used to build it. The build scripts will use this version of wasm2js as much as possible. These builds are known to be byte-for-byte reproducible as of [wasi-sdk v34.0-rc.2](https://github.com/WebAssembly/wasi-sdk/releases/tag/wasi-sdk-34-rc.2).
Hopefully this will be robust enough to survive reality, but this is the kind of thing you only learn the efficacy of the hard way.
+248
View File
@@ -0,0 +1,248 @@
#!/usr/bin/env bash
#
# CW(Xe): Script was generated by Claude after I tried to do this manually and
# gave up.
#
# Build binaryen tools (wasm2js, wasm-opt) as WASI preview 1 WebAssembly
# modules. See the TOOLS array below to add or remove targets.
#
# Output: ./<tool>_<BINARYEN_VERSION>.wasm
# (default wasm2js_130.wasm, wasm-opt_130.wasm)
#
# Dependencies are fetched automatically if missing: wasi-sdk is downloaded
# from its GitHub release and binaryen is git-cloned at the requested tag.
# Pin versions with the WASI_SDK_VERSION and BINARYEN_VERSION env vars.
#
# How it works / notable decisions:
#
# * Toolchain: we use the wasi-sdk CMake toolchain file `wasi-sdk-p1.cmake`,
# which targets `wasm32-wasip1` and points CMake at the bundled clang/lld.
#
# * Static binary: WASI has no dynamic linker, so libbinaryen is built as a
# static archive (-DBUILD_SHARED_LIBS=OFF) and statically linked into the
# final module. This is the only thing that links on WASI.
#
# * C++ exceptions: binaryen's parser and tools use `throw`, so we cannot
# build with -fno-exceptions. wasi-sdk ships two libc++ flavors: the default
# `noeh` (no exceptions) and an `eh` variant. Passing `-fwasm-exceptions`
# makes the clang driver select the `eh` include/lib dirs. We also link
# `-lunwind` to satisfy the `_Unwind_*` / exception-tag symbols.
#
# * EH encoding: by default LLVM emits the *legacy* wasm exception-handling
# opcodes (`try`/`catch`), which modern runtimes (e.g. wasmtime >= ~45) no
# longer accept. `-mllvm -wasm-use-legacy-eh=false` makes it emit the
# standardized exnref-based EH (`try_table`) instead, so the module runs on
# current runtimes with the exceptions proposal enabled.
#
# * Threads: binaryen calls find_package(Threads) and links pthread (wasi-libc
# provides stubs). At runtime ThreadPool::getNumCores() returns 1 on wasip1,
# so no threads are ever spawned and it runs single-threaded.
#
# * Reproducibility: the goal is a byte-for-byte identical module on any
# machine. Ninja invokes clang with absolute source paths, so __FILE__
# (used all over binaryen via WASM_UNREACHABLE) would otherwise bake the
# build machine's checkout path into the module's data segments. We rewrite
# that prefix to a stable token with -ffile-prefix-map so the output does
# not depend on where the tree lives. Everything else feeding the module is
# already pinned (wasi-sdk version, binaryen tag, compile/link flags), and
# the wasm format carries no build timestamp, so the raw clang/lld output is
# deterministic. We deliberately do NOT post-process with wasm-opt: its
# availability and version vary per machine, which would defeat the
# guarantee. Note this takes an explicit flag: clang's wasm driver runs
# `wasm-opt -O3` on its own whenever a wasm-opt is on PATH and optimization
# is on, so we pass --no-wasm-opt at link time to suppress it (see the
# REPRO_LINK_FLAGS note below).
#
# * Clean build: cmake/ninja are incremental, so re-running over an existing
# build tree only recompiles what changed and leaves stale object files
# behind. If those objects were produced by an older revision of this script
# (different flags), they leak into the final module and the output is no
# longer a function of the current inputs alone. We therefore wipe the build
# directory before configuring so every run is a full, flag-consistent build
# from scratch.
#
# * Stripping: the linker emits ~2.5 MB of DWARF (.debug_*), a multi-megabyte
# `name` section, and a `producers` section that records the exact clang
# revision. The producers string in particular would tie the bytes to one
# wasi-sdk build, and the debug/name sections only bloat a module we run
# headless. We strip all of them with the wasi-sdk's OWN `llvm-strip`
# (--strip-all), which is pinned by WASI_SDK_VERSION just like the compiler,
# so the strip step is as deterministic as the rest of the toolchain. This
# is NOT wasm-opt: llvm-strip ships in the sdk we already pin, so it adds no
# new floating dependency. `target_features` is intentionally preserved --
# it advertises the proposals (exceptions, etc.) the module needs and
# --strip-all keeps it.
#
# * ASLR: the wasi-sdk clang that compiles binaryen has address-sensitive
# ordering in its WebAssembly exception-handling codegen -- pointer values
# leak into the iteration order of a few passes, which shuffles a handful of
# try_table basic blocks and their branch labels. With address-space layout
# randomization on, the same source compiles to ~29 differing bytes from one
# run to the next. We pin pointer layout by re-exec'ing the whole build under
# `setarch -R` (ADDR_NO_RANDOMIZE), which is inherited by cmake/ninja/clang.
# This is Linux-only; see the re-exec guard below.
#
# CAVEAT -- same architecture only. setarch fixes ASLR within one host, but
# the underlying ordering is keyed on raw pointer VALUES (clang's
# WebAssemblyCFGStackify iterates DenseMap<MachineBasicBlock*, ...> in
# pointer-hash order). The x86_64 and arm64 wasi-sdk clang binaries hand out
# different pointers, so the two arches still produce ~29 differing bytes (a
# few reordered try_table blocks) even though every section is otherwise
# identical. This is an upstream LLVM determinism bug, not something we can
# pin from here; fixing it needs LLVM to sort those EH pads by block number.
# The committed modules are the x86_64 build; CI records the expected
# checksums for both architectures (shasums.x86_64 / shasums.arm64) and
# accepts a match against either, so each runner verifies its own arch.
#
# To run the resulting module, the host runtime must enable the exceptions
# proposal and grant filesystem access, e.g.:
#
# wasmtime run -W exceptions=y --dir . ./wasm2js_130.wasm input.wasm -o out.js
#
set -euo pipefail
# Pin any timestamp a tool in the chain might embed. Nothing in the current
# toolchain consumes this (the wasm format has no build-time field and we emit
# no debug info), but exporting it keeps the build deterministic if a future
# wasi-sdk or binaryen starts honoring it. Fixed constant, not "now".
export SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-1700000000}"
# Resolve the directory this script lives in so it works from anywhere.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
# --- Versions (override via the environment) -------------------------------
# wasi-sdk: full release version, e.g. 33.0. The GitHub release tag uses only
# the major component (wasi-sdk-33) while the tarball uses the full version.
WASI_SDK_VERSION="${WASI_SDK_VERSION:-34.0}"
# binaryen: the numeric release, used both for the git tag (version_130) and
# the output filename (wasm2js_130.wasm).
BINARYEN_VERSION="${BINARYEN_VERSION:-130}"
# Map the host's uname onto wasi-sdk's <arch>-<os> asset naming.
case "$(uname -s)" in
Darwin) WASI_SDK_OS="macos" ;;
Linux) WASI_SDK_OS="linux" ;;
*)
echo "error: unsupported OS $(uname -s); set WASI_SDK to a prebuilt sdk" >&2
exit 1
;;
esac
case "$(uname -m)" in
x86_64 | amd64) WASI_SDK_ARCH="x86_64" ;;
arm64 | aarch64) WASI_SDK_ARCH="arm64" ;;
*)
echo "error: unsupported arch $(uname -m); set WASI_SDK to a prebuilt sdk" >&2
exit 1
;;
esac
WASI_SDK_MAJOR="${WASI_SDK_VERSION%%.*}"
WASI_SDK_DIRNAME="wasi-sdk-${WASI_SDK_VERSION}-${WASI_SDK_ARCH}-${WASI_SDK_OS}"
WASI_SDK_URL="https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-${WASI_SDK_MAJOR}/${WASI_SDK_DIRNAME}.tar.gz"
BINARYEN_TAG="version_${BINARYEN_VERSION}"
BINARYEN_URL="https://github.com/WebAssembly/binaryen.git"
# All build inputs live under ./var; outputs land in the script directory.
VAR_DIR="$SCRIPT_DIR/var"
WASI_SDK="${WASI_SDK:-$VAR_DIR/$WASI_SDK_DIRNAME}"
BINARYEN_SRC="$VAR_DIR/binaryen"
BUILD_DIR="$BINARYEN_SRC/build-wasi"
TOOLCHAIN="$WASI_SDK/share/cmake/wasi-sdk-p1.cmake"
# llvm-strip from the same pinned wasi-sdk; used to drop debug/name/producers.
STRIP="$WASI_SDK/bin/llvm-strip"
mkdir -p "$VAR_DIR"
# --- Fetch wasi-sdk ---------------------------------------------------------
if [[ ! -f "$TOOLCHAIN" ]]; then
echo ">> Downloading wasi-sdk $WASI_SDK_VERSION"
echo " $WASI_SDK_URL"
tmp_tarball="$(mktemp "$VAR_DIR/.wasi-sdk.XXXXXX.tar.gz")"
trap 'rm -f "$tmp_tarball"' EXIT
curl -fL --retry 3 -o "$tmp_tarball" "$WASI_SDK_URL"
# The tarball unpacks to $WASI_SDK_DIRNAME/ in the destination directory.
tar -xzf "$tmp_tarball" -C "$VAR_DIR"
rm -f "$tmp_tarball"
trap - EXIT
fi
if [[ ! -f "$TOOLCHAIN" ]]; then
echo "error: wasi-sdk toolchain not found at $TOOLCHAIN" >&2
echo " set WASI_SDK to the wasi-sdk install prefix" >&2
exit 1
fi
# --- Fetch binaryen ---------------------------------------------------------
if [[ ! -d "$BINARYEN_SRC/.git" ]]; then
echo ">> Cloning binaryen at $BINARYEN_TAG"
git clone --depth 1 --branch "$BINARYEN_TAG" --recurse-submodules \
"$BINARYEN_URL" "$BINARYEN_SRC"
fi
# Flags that enable standardized wasm exception handling against wasi-sdk's
# `eh` libc++ variant. Needed at both compile and link time.
EH_COMPILE_FLAGS="-fwasm-exceptions -mllvm -wasm-use-legacy-eh=false"
EH_LINK_FLAGS="-fwasm-exceptions -lunwind"
# Reproducibility: strip the absolute checkout path out of every __FILE__ so the
# module is identical regardless of where binaryen was cloned. BUILD_DIR lives
# under BINARYEN_SRC, so generated-source paths are normalized by the same map.
REPRO_COMPILE_FLAGS="-ffile-prefix-map=$BINARYEN_SRC=."
# Reproducibility: clang's wasm driver silently runs `wasm-opt -O3` on the
# linked module whenever an optimization level is set (Release => -O3) AND a
# wasm-opt happens to be on PATH. That makes the bytes depend on whichever
# wasm-opt is installed -- and an old one (e.g. the binaryen 108 that ships in
# some distros) cannot even parse the exnref exception handling we emit, so the
# link dies with "[parse exception: Bad type form -1] / error parsing wasm".
# Disable the auto-pass so the module is purely the linker's deterministic
# output (this is what the wasm-opt note in the header is really about).
REPRO_LINK_FLAGS="--no-wasm-opt"
# Reproducibility: start from a pristine build tree. cmake/ninja only rebuild
# changed objects, so a stale tree from an earlier (differently-flagged) run
# would silently contaminate the output. Wiping it guarantees the module is a
# function of the current inputs alone.
echo ">> Wiping build directory for a clean build"
rm -rf "$BUILD_DIR"
echo ">> Configuring (wasm32-wasip1, static, exceptions=exnref)"
cmake -S "$BINARYEN_SRC" -B "$BUILD_DIR" -G Ninja \
-DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" \
-DWASI_SDK_PREFIX="$WASI_SDK" \
-DCMAKE_BUILD_TYPE=Release \
-DBUILD_TESTS=OFF \
-DBUILD_SHARED_LIBS=OFF \
-DENABLE_WERROR=OFF \
-DINSTALL_LIBS=OFF \
-DCMAKE_C_FLAGS="$EH_COMPILE_FLAGS $REPRO_COMPILE_FLAGS" \
-DCMAKE_CXX_FLAGS="$EH_COMPILE_FLAGS $REPRO_COMPILE_FLAGS" \
-DCMAKE_EXE_LINKER_FLAGS="$EH_LINK_FLAGS $REPRO_LINK_FLAGS"
# Tools to build, as binaryen CMake target names. Each is emitted to
# ./<tool>_<BINARYEN_VERSION>.wasm.
TOOLS=(wasm2js wasm-opt)
echo ">> Building: ${TOOLS[*]}"
cmake --build "$BUILD_DIR" --target "${TOOLS[@]}"
# Install the stripped linker output. We intentionally skip any wasm-opt pass:
# optimizing here would make the result depend on whichever wasm-opt happens to
# be installed, which is exactly the non-determinism we are eliminating. The
# only post-processing is llvm-strip from the pinned wasi-sdk (see header note);
# combined with the pinned toolchain and the -ffile-prefix-map applied above,
# the module is reproducible.
BUILD_BIN="$BUILD_DIR/bin"
for tool in "${TOOLS[@]}"; do
out="./${tool}_${BINARYEN_VERSION}.wasm"
echo ">> Installing $tool -> $out (stripped)"
"$STRIP" --strip-all "$BUILD_BIN/$tool" -o "$out"
ls -l "$out" | awk '{print " size:", $5, "bytes"}'
done
echo ">> Done. Outputs in $SCRIPT_DIR:"
ls -1 ./*_"${BINARYEN_VERSION}".wasm
+2
View File
@@ -0,0 +1,2 @@
*
!.gitignore
Binary file not shown.
Binary file not shown.