Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/RELEASE_SETUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,24 @@ Only one release runs at a time. GitHub concurrency retains at most one pending

The app reads `https://github.com/riko2chen/Sayo/releases/latest/download/appcast.xml`. It will remain unavailable until the first complete release is published. After initial publication, perform a real old-version-to-new-version update acceptance test, including download, signature verification, installation, and restart. Local fixture tests do not prove that online path.

## Homebrew tap

The public tap is `riko2chen/homebrew-sayo`; users install with `brew install --cask riko2chen/sayo/sayo`. The tap follows published stable GitHub Releases, so merging a version into main alone does not update Homebrew.

Prepare a new local tap checkout from the reviewed sources:

```sh
python3 scripts/prepare_homebrew_tap.py --output .build/homebrew-sayo
python3 .build/homebrew-sayo/update_cask.py
python3 -m unittest discover -s .build/homebrew-sayo/tests -v
```

The first command exports an explicit list of public files into a new directory. The second reads the latest public release, checks the appcast and checksum manifest, downloads and verifies the DMG, and creates `Casks/sayo.rb`. Neither command pushes or creates a repository. Publish that directory as `riko2chen/homebrew-sayo` only with maintainer authorization; use its own Git history, never the source checkout's private archive.

The tap includes an hourly `Sync latest Sayo release` workflow, also available through **Run workflow** for immediate synchronization after a release. GitHub can delay scheduled runs and disable schedules in inactive public repositories. The workflow uses only the tap's `GITHUB_TOKEN` with Contents write permission. It needs no cross-repository token or signing credentials. Unchanged releases create no commits; downgrades and changes to an existing release's checksum fail without replacing the current Cask.

When changing the updater or Cask template, export to a fresh directory and update the corresponding files in the tap through a reviewed commit. Tests under `Distribution/homebrew/tests` run both in this repository's release test suite and in the exported tap.

## Local archive protection

Run `python3 scripts/install_local_guards.py` to install the local push guard. In a migration checkout, archive metadata and a push lock live in Git's common directory, outside tracked source. The guard rejects local/private history even if aliased as main or a tag. It also rejects internal files in public ancestry. It never removes an existing push lock. Do not use `--no-verify`, `--all`, or `--mirror` to bypass archive protection.
Expand Down
36 changes: 36 additions & 0 deletions Distribution/homebrew/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Homebrew tap for Sayo

Install [Homebrew](https://brew.sh/) first, then run:

```sh
brew install --cask riko2chen/sayo/sayo
```

This installs Sayo in Applications and adds the `sayo` command to your Homebrew bin directory. Open Sayo, grant Accessibility permission, and configure a model service.

To update:

```sh
brew update
brew upgrade --cask --greedy riko2chen/sayo/sayo
```

You can also check for updates inside Sayo. To uninstall the app and command:

```sh
brew uninstall --cask riko2chen/sayo/sayo
```

## 中文

先安装 [Homebrew](https://brew.sh/),再运行上面的安装命令。安装完成后,打开「应用程序」中的 Sayo,按引导授予辅助功能权限并配置模型服务。安装时也会添加 `sayo` 命令。

更新可使用上面的 `brew update` 和 `brew upgrade` 命令,或在 Sayo 内检查更新。卸载命令会移除应用和命令行入口,保留用户配置。

## Maintenance

The `Sync latest Sayo release` workflow checks the latest published stable release of [riko2chen/Sayo](https://github.com/riko2chen/Sayo) hourly and can also be run manually. GitHub may delay scheduled runs or disable schedules in inactive public repositories; use the workflow's **Run workflow** button to sync immediately.

The updater checks versioned asset URLs, the checksum manifest, GitHub's asset digest when present, and the appcast metadata. Before changing the Cask, it downloads the DMG and verifies its size and SHA-256. It rejects downgrades and checksum changes to an existing version. Unchanged releases do not cause a download or commit.

The workflow uses this tap's `GITHUB_TOKEN` to commit only `Casks/sayo.rb`. It needs no signing credentials or access to the Sayo source repository. Source templates and tests are maintained under `Distribution/homebrew` in the Sayo repository.
161 changes: 161 additions & 0 deletions Distribution/homebrew/tests/test_update_cask.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import copy
import hashlib
import importlib.util
import io
import json
import os
from pathlib import Path
import shutil
import tempfile
import unittest
from unittest.mock import patch

ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("update_cask", ROOT / "update_cask.py")
updater = importlib.util.module_from_spec(spec)
spec.loader.exec_module(updater)


class HomebrewUpdateTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
(self.root / "Casks").mkdir()
shutil.copyfile(ROOT / "Casks/sayo.rb.in", self.root / "Casks/sayo.rb.in")
self.path = self.root / "Casks/sayo.rb"
self.payload = b"Test DMG bytes"
self.sha = hashlib.sha256(self.payload).hexdigest()
self.prefix = "https://github.com/riko2chen/Sayo/releases/download/v0.2.0/"
self.filename = "Sayo-0.2.0-2000.dmg"
self.release = {"tag_name": "v0.2.0", "draft": False, "prerelease": False,
"published_at": "2026-09-28T00:00:00Z", "assets": []}
for name in (self.filename, "SHA256SUMS", "appcast.xml"):
self.release["assets"].append({"name": name, "state": "uploaded",
"browser_download_url": self.prefix + name,
"size": len(self.payload), "digest": "sha256:" + self.sha})
self.manifest = f"{self.sha} {self.filename}\n"
self.feed = f'''<rss xmlns:sparkle="{updater.SPARKLE}"><channel><item>
<sparkle:version>2000</sparkle:version><sparkle:shortVersionString>0.2.0</sparkle:shortVersionString>
<sparkle:minimumSystemVersion>14.0</sparkle:minimumSystemVersion>
<enclosure url="{self.prefix}{self.filename}" length="{len(self.payload)}" sparkle:edSignature="test-signature"/>
</item></channel></rss>'''

def read(self, url):
if url == f"https://api.github.com/repos/{updater.REPOSITORY}/releases/latest":
return json.dumps(self.release).encode()
return {self.prefix + "SHA256SUMS": self.manifest.encode(),
self.prefix + "appcast.xml": self.feed.encode()}[url]

def update(self, payload=None):
with patch.object(updater, "read_url", side_effect=self.read), \
patch.object(updater, "urlopen", return_value=io.BytesIO(self.payload if payload is None else payload)) as download:
result = updater.update(self.root)
return result, download

def seed(self):
self.update()
return self.path.read_bytes()

def test_new_release_downloads_and_validates_bytes_then_repeated_run_is_a_noop(self):
changed, download = self.update()
self.assertTrue(changed)
self.assertEqual(download.call_args.args[0].full_url, self.prefix + self.filename)
text = self.path.read_text()
self.assertIn('version "0.2.0,2000"', text)
self.assertIn(f'sha256 "{self.sha}"', text)
self.assertNotIn("@VERSION@", text)
changed, download = self.update()
self.assertFalse(changed)
download.assert_not_called()

def test_draft_prerelease_unpublished_and_missing_assets_never_create_a_cask(self):
original = copy.deepcopy(self.release)
for change in ({"draft": True}, {"prerelease": True}, {"published_at": None}, {"assets": []}):
with self.subTest(change=change):
self.release = dict(original, **change)
with self.assertRaises(ValueError):
self.update()
self.assertFalse(self.path.exists())

def test_download_size_or_hash_failure_never_creates_a_cask(self):
for payload in (b"bad", b"x" * len(self.payload), self.payload + b"extra"):
with self.subTest(payload=payload), self.assertRaisesRegex(ValueError, "mismatch"):
self.update(payload)
self.assertFalse(self.path.exists())

def test_downgrades_and_changed_checksums_preserve_the_existing_cask(self):
original = self.seed().decode()
for previous, message in ((original.replace("0.2.0,2000", "0.3.0,3000"), "downgrade"),
(original.replace(self.sha, "a" * 64), "checksum")):
self.path.write_text(previous)
with self.assertRaisesRegex(ValueError, message):
self.update()
self.assertEqual(self.path.read_text(), previous)

def test_asset_urls_and_github_digest_must_match(self):
original = copy.deepcopy(self.release)
for field, value in (("browser_download_url", "https://example.com/other.dmg"),
("digest", "sha256:" + "a" * 64)):
self.release = copy.deepcopy(original)
self.release["assets"][0][field] = value
with self.assertRaises(ValueError):
self.update()
self.assertFalse(self.path.exists())

def test_manifest_and_appcast_mismatches_preserve_an_existing_cask(self):
original = self.seed()
manifest, feed = self.manifest, self.feed
variants = [(manifest + manifest, feed), (manifest.replace(self.filename, "other.dmg"), feed)]
for before, after in ((">2000<", ">2001<"), (">0.2.0<", ">0.2.1<"),
(">14.0<", ">15.0<"), (f'length="{len(self.payload)}"', 'length="99"'),
('sparkle:edSignature="test-signature"', ''),
(self.prefix + self.filename, "https://example.com/other.dmg")):
variants.append((manifest, feed.replace(before, after)))
for self.manifest, self.feed in variants:
with self.subTest(feed=self.feed, manifest=self.manifest), self.assertRaises(ValueError):
self.update()
self.assertEqual(self.path.read_bytes(), original)

def test_network_failure_keeps_the_installed_recipe(self):
original = self.seed()
with patch.object(updater, "read_url", side_effect=OSError("unavailable")):
with self.assertRaises(OSError):
updater.update(self.root)
self.assertEqual(self.path.read_bytes(), original)

def test_newer_release_replaces_previous_recipe_only_after_download_verification(self):
original = self.seed()
self.release = json.loads(json.dumps(self.release).replace("0.2.0", "0.2.1").replace("2000", "2001"))
self.prefix = self.prefix.replace("0.2.0", "0.2.1")
self.filename = self.filename.replace("0.2.0", "0.2.1").replace("2000", "2001")
self.manifest = self.manifest.replace("0.2.0", "0.2.1").replace("2000", "2001")
self.feed = self.feed.replace("0.2.0", "0.2.1").replace("2000", "2001")
with self.assertRaisesRegex(ValueError, "mismatch"):
self.update(b"corrupt")
self.assertEqual(self.path.read_bytes(), original)
changed, _ = self.update()
self.assertTrue(changed)
self.assertIn('version "0.2.1,2001"', self.path.read_text())

def test_version_bounds_and_unexpected_template_tokens_are_rejected(self):
for version in ("0.100.0", "0.1.1000", "0.2.0-beta", "00.2.0", "0.2.0/other"):
with self.subTest(version=version), self.assertRaises(ValueError):
updater.version_build(version)
template = self.root / "Casks/sayo.rb.in"
template.write_text(template.read_text() + "\n@UNEXPECTED@\n")
with self.assertRaisesRegex(ValueError, "Unresolved"):
self.update()
self.assertFalse(self.path.exists())

def test_token_is_only_used_for_github_api_requests(self):
for url, authenticated in (("https://api.github.com/repos/riko2chen/Sayo/releases/latest", True),
(self.prefix + "SHA256SUMS", False)):
with patch.dict(os.environ, {"GH_TOKEN": "test-token"}), \
patch.object(updater, "urlopen", return_value=io.BytesIO(b"{}")) as request:
updater.read_url(url)
self.assertEqual(request.call_args.args[0].get_header("Authorization") is not None, authenticated)


if __name__ == "__main__":
unittest.main()
34 changes: 34 additions & 0 deletions Distribution/homebrew/update.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: Sync latest Sayo release
on:
workflow_dispatch:
schedule:
- cron: '17 * * * *'
push:
branches: [main]
paths: ['update_cask.py', 'Casks/sayo.rb.in', 'tests/**', '.github/workflows/update.yml']
permissions:
contents: read
concurrency:
group: update-sayo-cask
cancel-in-progress: false
jobs:
update:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- name: Test release validation
run: python3 -m unittest discover -s tests -v
- name: Verify latest published release and update Cask
env:
GH_TOKEN: ${{ github.token }}
run: python3 update_cask.py
- name: Commit updated Cask
run: |
git add Casks/sayo.rb
if git diff --cached --quiet; then exit 0; fi
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
git commit -m 'Update Sayo Cask from published release'
git push origin HEAD:main
134 changes: 134 additions & 0 deletions Distribution/homebrew/update_cask.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""Update this tap from a published Sayo release. Never publishes or installs."""
import hashlib
import json
import os
from pathlib import Path
import re
import sys
from urllib.request import Request, urlopen
import xml.etree.ElementTree as ET

ROOT = Path(__file__).resolve().parent
REPOSITORY = "riko2chen/Sayo"
SPARKLE = "http://www.andymatuschak.org/xml-namespaces/sparkle"


def read_url(url):
headers = {"User-Agent": "Sayo-Homebrew"}
if url.startswith("https://api.github.com/"):
headers["Accept"] = "application/vnd.github+json"
if token := os.environ.get("GH_TOKEN"):
headers["Authorization"] = f"Bearer {token}"
with urlopen(Request(url, headers=headers), timeout=60) as response:
return response.read()


def version_build(version):
if not re.fullmatch(r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)", version):
raise ValueError("Expected a stable major.minor.patch version")
major, minor, patch = map(int, version.split("."))
if minor > 99 or patch > 999:
raise ValueError("Version components exceed Sayo's build-number bounds")
return major * 100000 + minor * 1000 + patch


def published_metadata(release):
if release.get("draft") is not False or release.get("prerelease") is not False or not release.get("published_at"):
raise ValueError("Only published stable releases can update Homebrew")
tag = release["tag_name"]
if not tag.startswith("v"):
raise ValueError("Expected a version tag")
version = tag[1:]
build = version_build(version)
filename = f"Sayo-{version}-{build}.dmg"
prefix = f"https://github.com/{REPOSITORY}/releases/download/{tag}/"
assets = {}
for name in (filename, "SHA256SUMS", "appcast.xml"):
matches = [asset for asset in release["assets"] if asset["name"] == name]
if len(matches) != 1 or matches[0].get("state") != "uploaded":
raise ValueError(f"Missing or duplicate published asset: {name}")
asset = matches[0]
if asset.get("browser_download_url") != prefix + name:
raise ValueError("Release asset URL does not match the official versioned URL")
assets[name] = asset
return version, build, filename, assets


def verify_download(url, expected_size, expected_hash):
digest = hashlib.sha256()
size = 0
request = Request(url, headers={"User-Agent": "Sayo-Homebrew"})
with urlopen(request, timeout=60) as response:
while chunk := response.read(1024 * 1024):
size += len(chunk)
if size > expected_size:
raise ValueError("Published DMG size mismatch")
digest.update(chunk)
if size != expected_size or digest.hexdigest() != expected_hash:
raise ValueError("Published DMG checksum or size mismatch")


def update(root=ROOT):
release = json.loads(read_url(f"https://api.github.com/repos/{REPOSITORY}/releases/latest"))
version, build, filename, assets = published_metadata(release)
dmg = assets[filename]
checksum_text = read_url(assets["SHA256SUMS"]["browser_download_url"]).decode()
checksums = re.findall(r"^([a-f0-9]{64}) " + re.escape(filename) + r"$", checksum_text, re.MULTILINE)
if len(checksums) != 1:
raise ValueError("Checksum manifest must contain exactly one matching DMG")
checksum = checksums[0]
if dmg.get("digest") and dmg["digest"] != "sha256:" + checksum:
raise ValueError("GitHub asset digest and checksum manifest disagree")
size = dmg["size"]
if not isinstance(size, int) or size <= 0:
raise ValueError("Invalid published DMG size")

feed = ET.fromstring(read_url(assets["appcast.xml"]["browser_download_url"]))
items = [item for item in feed.findall("./channel/item")
if item.findtext(f"{{{SPARKLE}}}version") == str(build)]
if len(items) != 1:
raise ValueError("Appcast must contain exactly one item for this build")
item = items[0]
enclosure = item.find("enclosure")
if (item.findtext(f"{{{SPARKLE}}}shortVersionString") != version or
item.findtext(f"{{{SPARKLE}}}minimumSystemVersion") != "14.0" or
enclosure is None or enclosure.get("url") != dmg["browser_download_url"] or
enclosure.get("length") != str(size) or not enclosure.get(f"{{{SPARKLE}}}edSignature")):
raise ValueError("Appcast metadata does not match the supported release")

path = root / "Casks/sayo.rb"
previous = path.read_text() if path.exists() else ""
if previous:
old_version = re.search(r'^ version "([0-9.]+),([0-9]+)"$', previous, re.MULTILINE)
old_hash = re.search(r'^ sha256 "([a-f0-9]{64})"$', previous, re.MULTILINE)
if not old_version or not old_hash or version_build(old_version[1]) != int(old_version[2]):
raise ValueError("Existing Cask metadata is invalid")
if int(old_version[2]) > build:
raise ValueError("Refusing to downgrade the Cask")
if int(old_version[2]) == build and old_hash[1] != checksum:
raise ValueError("Refusing to change the checksum of a published version")

rendered = (root / "Casks/sayo.rb.in").read_text()
for token, value in {"VERSION": version, "BUILD": str(build), "SHA256": checksum, "REPOSITORY": REPOSITORY}.items():
rendered = rendered.replace(f"@{token}@", value)
if re.search(r"@[A-Z_]+@", rendered):
raise ValueError("Unresolved Cask template token")
if previous == rendered:
print(f"Sayo {version} is already current")
return False

# Verify the actual bytes before writing any new version or checksum.
verify_download(dmg["browser_download_url"], size, checksum)
temporary = path.with_suffix(".rb.tmp")
temporary.write_text(rendered)
temporary.replace(path)
print(f"Updated Sayo to {version} ({build})")
return True


if __name__ == "__main__":
try:
update()
except (ValueError, KeyError, OSError, ET.ParseError) as error:
sys.exit(str(error))
Loading
Loading