Skip to content
Draft
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
8 changes: 7 additions & 1 deletion .github/workflows/startup.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ on:
- 'app/python_runtime.py'
- 'app/provision/runtimes.py'
- 'app/provision/python_downloads.json'
- 'app/provision/node_downloads.json'
- 'app/node_runtime.py'
- 'app/provision/verify.py'
- 'tests/test_native_runtime.py'
- 'tests/test_python_downloads.py'
- 'tests/test_node_downloads.py'
- 'tests/test_autostart.py'
- 'tests/test_craftbot_service.py'
- '.github/workflows/startup.yml'
Expand All @@ -25,9 +28,12 @@ on:
- 'app/python_runtime.py'
- 'app/provision/runtimes.py'
- 'app/provision/python_downloads.json'
- 'app/provision/node_downloads.json'
- 'app/node_runtime.py'
- 'app/provision/verify.py'
- 'tests/test_native_runtime.py'
- 'tests/test_python_downloads.py'
- 'tests/test_node_downloads.py'
- 'tests/test_autostart.py'
- 'tests/test_craftbot_service.py'
- '.github/workflows/startup.yml'
Expand All @@ -46,4 +52,4 @@ jobs:
python-version: '3.10'
- run: python -m pip install pytest==9.0.2
- name: Check login startup and browser-only shortcuts
run: python -m pytest tests/test_autostart.py tests/test_craftbot_service.py tests/test_python_downloads.py tests/test_native_runtime.py -q
run: python -m pytest tests/test_autostart.py tests/test_craftbot_service.py tests/test_python_downloads.py tests/test_node_downloads.py tests/test_native_runtime.py -q
2 changes: 1 addition & 1 deletion README.cn.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ python craftbot.py install
export CRAFTBOT_MIRRORS="https://github.com/=https://<your-github-proxy>/https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/"
```

Python 依赖包和记忆嵌入模型仍会按固定的 SHA-256 校验值进行校验,因此镜像无法改变它们。Python 和 Node.js 运行时没有固定校验值,请只为它们使用你信任的镜像。在 Windows PowerShell 中,请用 `$env:NAME = "value"` 代替 `export` 设置变量。
Python 依赖包、Python 和 Node.js 运行时以及记忆嵌入模型都会按固定的 SHA-256 校验值进行校验,因此镜像无法改变它们。在 Windows PowerShell 中,请用 `$env:NAME = "value"` 代替 `export` 设置变量。

### 没有桌面环境的服务器

Expand Down
2 changes: 1 addition & 1 deletion README.de.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ Leite die Downloads vor der Installation auf Mirrors um:
export CRAFTBOT_MIRRORS="https://github.com/=https://<your-github-proxy>/https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/"
```

Python-Pakete und das Embedding-Modell für den Speicher werden weiterhin gegen fest hinterlegte SHA-256-Prüfsummen geprüft, ein Mirror kann sie also nicht verändern. Die Python- und Node.js-Laufzeiten sind nicht fest hinterlegt, verwende dafür nur einen Mirror, dem du vertraust. In Windows PowerShell setzt du Variablen mit `$env:NAME = "value"` statt `export`.
Python-Pakete, die Python- und Node.js-Laufzeiten und das Embedding-Modell für den Speicher werden gegen fest hinterlegte SHA-256-Prüfsummen geprüft, ein Mirror kann sie also nicht verändern. In Windows PowerShell setzt du Variablen mit `$env:NAME = "value"` statt `export`.

### Server ohne Desktop

Expand Down
2 changes: 1 addition & 1 deletion README.es.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ Antes de instalar, dirige las descargas a mirrors:
export CRAFTBOT_MIRRORS="https://github.com/=https://<your-github-proxy>/https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/"
```

Los paquetes de Python y el modelo de embeddings de la memoria se siguen verificando con checksums SHA-256 fijados, así que un mirror no puede cambiarlos. Los runtimes de Python y Node.js no están fijados, así que para ellos usa solo un mirror de confianza. En Windows PowerShell, define las variables con `$env:NAME = "value"` en lugar de `export`.
Los paquetes de Python, los runtimes de Python y Node.js y el modelo de embeddings de la memoria se verifican con checksums SHA-256 fijados, así que un mirror no puede cambiarlos. En Windows PowerShell, define las variables con `$env:NAME = "value"` en lugar de `export`.

### Servidor sin escritorio

Expand Down
2 changes: 1 addition & 1 deletion README.fr.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ Avant l'installation, redirigez les téléchargements vers des miroirs :
export CRAFTBOT_MIRRORS="https://github.com/=https://<your-github-proxy>/https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/"
```

Les paquets Python et le modèle d'embeddings de la mémoire restent vérifiés avec des sommes de contrôle SHA-256 épinglées : un miroir ne peut donc pas les modifier. Les environnements d'exécution Python et Node.js ne sont pas épinglés, n'utilisez donc pour eux qu'un miroir de confiance. Dans Windows PowerShell, définissez les variables avec `$env:NAME = "value"` au lieu de `export`.
Les paquets Python, les environnements d'exécution Python et Node.js et le modèle d'embeddings de la mémoire sont vérifiés avec des sommes de contrôle SHA-256 épinglées : un miroir ne peut donc pas les modifier. Dans Windows PowerShell, définissez les variables avec `$env:NAME = "value"` au lieu de `export`.

### Serveur sans bureau

Expand Down
2 changes: 1 addition & 1 deletion README.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ TLS 通信を検査するネットワークでも追加の設定は不要です
export CRAFTBOT_MIRRORS="https://github.com/=https://<your-github-proxy>/https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/"
```

Python パッケージとメモリ用の埋め込みモデルは、ミラーを使っても固定された SHA-256 チェックサムで検証されるため、ミラーがそれらを変えることはできません。Python と Node.js のランタイムはチェックサムが固定されていないため、信頼できるミラーだけを使ってください。Windows PowerShell では `export` の代わりに `$env:NAME = "value"` で変数を設定します。
Python パッケージ、Python と Node.js のランタイム、メモリ用の埋め込みモデルは、ミラーを使っても固定された SHA-256 チェックサムで検証されるため、ミラーがそれらを変えることはできません。Windows PowerShell では `export` の代わりに `$env:NAME = "value"` で変数を設定します。

### デスクトップのないサーバー

Expand Down
2 changes: 1 addition & 1 deletion README.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ TLS 트래픽을 검사하는 네트워크에서도 추가 설정이 필요 없
export CRAFTBOT_MIRRORS="https://github.com/=https://<your-github-proxy>/https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/"
```

Python 패키지와 메모리 임베딩 모델은 미러를 거쳐도 고정된 SHA-256 체크섬으로 검증되므로, 미러가 이를 바꿀 수 없습니다. Python과 Node.js 런타임은 체크섬이 고정되어 있지 않으므로, 신뢰할 수 있는 미러만 사용하세요. Windows PowerShell에서는 `export` 대신 `$env:NAME = "value"`로 변수를 설정합니다.
Python 패키지, Python과 Node.js 런타임, 메모리 임베딩 모델은 미러를 거쳐도 고정된 SHA-256 체크섬으로 검증되므로, 미러가 이를 바꿀 수 없습니다. Windows PowerShell에서는 `export` 대신 `$env:NAME = "value"`로 변수를 설정합니다.

### 데스크톱이 없는 서버

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ Point the downloads at mirrors before you install:
export CRAFTBOT_MIRRORS="https://github.com/=https://<your-github-proxy>/https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/"
```

Python packages and the memory embedding model are still checked against pinned SHA-256 checksums, so a mirror cannot change them. The Python and Node.js runtimes are not pinned, so only use a mirror you trust for those. In Windows PowerShell, set variables with `$env:NAME = "value"` instead of `export`.
Python packages, the Python and Node.js runtimes, and the memory embedding model are checked against pinned SHA-256 checksums, so a mirror cannot change them. In Windows PowerShell, set variables with `$env:NAME = "value"` instead of `export`.

### Server without a desktop

Expand Down
2 changes: 1 addition & 1 deletion README.pt-BR.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ Antes de instalar, aponte os downloads para mirrors:
export CRAFTBOT_MIRRORS="https://github.com/=https://<your-github-proxy>/https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/"
```

Os pacotes Python e o modelo de embeddings da memória continuam sendo verificados por checksums SHA-256 fixados, então um mirror não consegue alterá-los. Os runtimes de Python e Node.js não são fixados, então use para eles apenas um mirror de confiança. No Windows PowerShell, defina as variáveis com `$env:NAME = "value"` em vez de `export`.
Os pacotes Python, os runtimes de Python e Node.js e o modelo de embeddings da memória são verificados por checksums SHA-256 fixados, então um mirror não consegue alterá-los. No Windows PowerShell, defina as variáveis com `$env:NAME = "value"` em vez de `export`.

### Servidor sem desktop

Expand Down
2 changes: 1 addition & 1 deletion README.zh-TW.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ python craftbot.py install
export CRAFTBOT_MIRRORS="https://github.com/=https://<your-github-proxy>/https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/"
```

Python 套件和記憶嵌入模型仍會以固定的 SHA-256 檢查碼驗證,因此鏡像站無法改變它們。Python 和 Node.js 執行環境沒有固定檢查碼,請只為它們使用你信任的鏡像站。在 Windows PowerShell 中,請用 `$env:NAME = "value"` 取代 `export` 來設定變數。
Python 套件、Python 和 Node.js 執行環境以及記憶嵌入模型都會以固定的 SHA-256 檢查碼驗證,因此鏡像站無法改變它們。在 Windows PowerShell 中,請用 `$env:NAME = "value"` 取代 `export` 來設定變數。

### 沒有桌面環境的伺服器

Expand Down
24 changes: 0 additions & 24 deletions app/downloads.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,30 +205,6 @@ def cache_name(url: str) -> str:
return unquote(name) or "download.bin"


def find_cached(pattern: str) -> Optional[str]:
"""A cached archive matching a glob, or None.

Lets a caller use the cache WITHOUT first resolving a download URL.
That matters more than it sounds: resolving the Python runtime's URL
means fetching a large JSON release index, and on a slow or flaky link
that request is itself a failure point — observed as
`IncompleteRead(1277952 bytes read)` in Windows Sandbox. Having the file
already and still failing because the index could not be read is an
absurd way to lose an install.

The archive names carry version and platform, so a glob like
`cpython-3.10.*-x86_64-pc-windows-msvc-install_only.tar.gz` identifies
the right file without asking anyone.
"""
import glob as _glob

cache = cache_dir()
if not cache:
return None
matches = sorted(_glob.glob(os.path.join(cache, pattern)))
return matches[-1] if matches else None


def _download_once(
url: str,
dest: str,
Expand Down
152 changes: 52 additions & 100 deletions app/node_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,20 @@
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
from typing import Optional, Tuple

logger = logging.getLogger(__name__)

MIN_NODE_MAJOR = 24 # keep the nodejs>=24 pin in environment.yml in sync

REPO_ROOT = Path(__file__).resolve().parents[1]

# The Node release a private copy is downloaded from, with the SHA-256 of each
# platform's archive as its signed SHASUMS256.txt lists it.
NODE_CONFIG_PATH = Path(__file__).resolve().parent / "provision" / "node_downloads.json"

_SHA256_RE = re.compile(r"[0-9a-f]{64}")

# app.paths is the single answer to "where does state live" — in a dev
# checkout that is the repo (so this is unchanged), and in an install it is
# the per-user data dir. Before this, SIDECAR_DIR was derived from __file__
Expand Down Expand Up @@ -200,14 +206,22 @@ def resolve(refresh: bool = False) -> Optional[NodeRuntime]:
and path_major is not None
and path_major >= MIN_NODE_MAJOR
):
_cached = NodeRuntime(
candidate = NodeRuntime(
node=path_node,
npm=path_npm,
bin_dir=os.path.dirname(path_node),
version=path_version,
source="path",
)
return _cached
# Only an npm this node can run counts. Arch's nodejs ships node
# without npm, so the npm on PATH can be another install's (a version
# manager's), which npm_command cannot pair with it. Taking that pair
# left `install` downloading the sidecar and then resolving the same
# unusable pair again, so setup never finished; the sidecar is used
# instead.
if npm_command(candidate):
_cached = candidate
return _cached

discovered = discover_node()
if discovered:
Expand Down Expand Up @@ -371,55 +385,45 @@ def _platform_suffix():
return f"linux-{arch}", "tar.xz"


def latest_download_url(log=None) -> Optional[str]:
"""URL of the newest Node on the MIN_NODE_MAJOR line for this machine.
def pinned_download(log=None) -> Optional[Tuple[str, str, str]]:
"""(version, url, sha256) of the pinned Node build for this machine, or None.

Only the release node_downloads.json names, checked against the SHA-256
it pins for this platform's archive, as published in that release's
signed SHASUMS256.txt. Nothing is asked of nodejs.org's index, so the
version every install runs is the one the repository was reviewed with.
Split out of download_sidecar so the archive can be pre-fetched into a
cache without installing it (scripts/prefetch_runtimes.py).
"""
import json
import ssl
import urllib.request

say = log or (lambda _m: None)

try:
import certifi

ctx = ssl.create_default_context(cafile=certifi.where())
except ImportError:
ctx = ssl.create_default_context()

suffix, ext = _platform_suffix()

try:
req = urllib.request.Request(
"https://nodejs.org/dist/index.json", headers={"User-Agent": "CraftBot"}
)
index = json.loads(urllib.request.urlopen(req, timeout=60, context=ctx).read())
except Exception as e:
say(f" Could not reach the Node index: {str(e)[:160]}")
config = json.loads(NODE_CONFIG_PATH.read_text(encoding="utf-8"))
ver = str(config["version"])
digest = config["sha256"].get(f"{suffix}.{ext}", "")
base = str(config["download_base"]).rstrip("/")
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
say(f" Invalid Node download configuration: {error}")
return None

ver = next(
(
e["version"]
for e in index
if e.get("version", "").startswith(f"v{MIN_NODE_MAJOR}.")
),
None,
)
if not ver:
say(f" No v{MIN_NODE_MAJOR}.x release found in the Node index")
# nodejs.org names every release directory v<major>.<minor>.<patch>.
if not re.fullmatch(r"v\d+\.\d+\.\d+", ver) or major_of(ver) != MIN_NODE_MAJOR:
say(f" The pinned Node {ver} is not a v{MIN_NODE_MAJOR}.x release")
return None
if not _SHA256_RE.fullmatch(str(digest)):
say(f" No pinned Node {ver} build for {suffix}")
return None
return f"https://nodejs.org/dist/{ver}/node-{ver}-{suffix}.{ext}"
return ver, f"{base}/{ver}/node-{ver}-{suffix}.{ext}", digest


def _extract_node(archive_src, ver, suffix, ext, say, url=None):
"""Put a Node archive into SIDECAR_DIR and return its binary path.
def _extract_node(ver, suffix, ext, say, url, sha256):
"""Download a Node archive into SIDECAR_DIR and return its binary path.

Shared by the cached and downloaded paths so extraction, layout and the
binary probe cannot drift between them.
downloads.download uses a cached copy (CRAFTBOT_DOWNLOAD_CACHE) only when
it matches the pin, and refuses a download that doesn't, so nothing
unverified is ever extracted.
"""
import tarfile
import zipfile
Expand All @@ -430,13 +434,11 @@ def _extract_node(archive_src, ver, suffix, ext, say, url=None):
os.makedirs(dest_root, exist_ok=True)
archive = os.path.join(dest_root, f"_download.{ext}")
try:
if archive_src:
say(f" Using cached {os.path.basename(archive_src)}")
shutil.copyfile(archive_src, archive)
else:
# Streamed with progress: the archive is 30-55MB, and a single
# silent blocking copy is indistinguishable from a hung install.
downloads.download(url, archive, log=say, label=f"Node {ver}")
# Streamed with progress: the archive is 30-55MB, and a single
# silent blocking copy is indistinguishable from a hung install.
downloads.download(
url, archive, log=say, label=f"Node {ver}", expected_sha256=sha256
)
say(" Extracting...")
if ext == "zip":
zipfile.ZipFile(archive).extractall(dest_root)
Expand Down Expand Up @@ -470,67 +472,17 @@ def download_sidecar(log=None) -> Optional[str]:
the installer needs it too: installer users never run install.py, so that
was the only route by which they could obtain Node, and they had none.

Stdlib-only (certifi when importable, else the system trust store).
Stdlib-only.
"""
import json
import ssl
import urllib.request

say = log or (lambda _m: None)

try:
import certifi

ctx = ssl.create_default_context(cafile=certifi.where())
except ImportError:
ctx = ssl.create_default_context()

pinned = pinned_download(log=say)
if not pinned:
return None
ver, url, sha256 = pinned
suffix, ext = _platform_suffix()

# Consult the cache BEFORE the network. Resolving the version means
# fetching nodejs.org's release index, which on a slow or flaky link is
# its own failure point — and failing there while the archive is already
# on disk would be a pointless way to lose an install.
cached_archive = None
ver_from_cache = None
try:
from app import downloads

cached_archive = downloads.find_cached(
f"node-v{MIN_NODE_MAJOR}.*-{suffix}.{ext}"
)
if cached_archive:
m = _NODE_VER_RE.search(os.path.basename(cached_archive))
if m:
ver_from_cache = "v" + ".".join(m.groups())
except Exception:
cached_archive = None

if cached_archive and ver_from_cache:
ver = ver_from_cache
url = f"https://nodejs.org/dist/{ver}/node-{ver}-{suffix}.{ext}"
return _extract_node(cached_archive, ver, suffix, ext, say, url)

try:
# Newest release on the MIN_NODE_MAJOR line (the index is newest-first).
req = urllib.request.Request(
"https://nodejs.org/dist/index.json", headers={"User-Agent": "CraftBot"}
)
index = json.loads(urllib.request.urlopen(req, timeout=60, context=ctx).read())
ver = next(
(
e["version"]
for e in index
if e.get("version", "").startswith(f"v{MIN_NODE_MAJOR}.")
),
None,
)
if not ver:
say(f" ⚠ No v{MIN_NODE_MAJOR}.x release found in the Node index")
return None

url = f"https://nodejs.org/dist/{ver}/node-{ver}-{suffix}.{ext}"
return _extract_node(None, ver, suffix, ext, say, url)
return _extract_node(ver, suffix, ext, say, url, sha256)
except Exception as e:
say(f" ⚠ Sidecar Node download failed: {str(e)[:200]}")
return None
Expand Down
12 changes: 12 additions & 0 deletions app/provision/node_downloads.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"download_base": "https://nodejs.org/dist",
"version": "v24.22.3",
"sha256": {
"darwin-arm64.tar.gz": "ff6e17d4874b76d272212b908cc020d6e815fba5a6c7eaaa06add725840307fd",
"darwin-x64.tar.gz": "977614af0504c81045e7fd85596dbca0e5f951b96681516dadafedcca8c447f7",
"linux-arm64.tar.xz": "6e51a2ada00f0011cc266f65d98922b403d7ad88f809ca2aa615a5fe1ce6e86c",
"linux-x64.tar.xz": "4f2b175a6d53a5c617a80dba2676238a0688cef28c6da4eba35c7d844e66fcfb",
"win-arm64.zip": "b3cc74a295b39d4f273271e96f58c06dd2b35757ca12abec64c7d0598b434f14",
"win-x64.zip": "e612af99f626ab415ea225af6bce5c971feb448cb5cae250bb1c3fa50c5f7d9f"
}
}
Loading
Loading