Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(install): pin standalone stack bootstrap and publish install scripts in releases
Dongdong Chen79af345433a1
diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex daf7c1b4..b1f2bd1b 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -213,6 +213,7 @@ jobs:export DESKTOP_UPDATE_KEY="$key"fiscripts/ci/desktop-release.sh manifest release "${{ needs.prepare.outputs.version }}"+ - run: scripts/ci/desktop-release.sh install-scripts release "${{ needs.prepare.outputs.version }}"- run: scripts/ci/desktop-release.sh checksums release "${{ needs.prepare.outputs.version }}"# GITHUB_TOKEN can write only this repository; a release in another one# takes LINGER_RELEASE_TOKEN, which prepare checked.diff --git a/docs/desktop-release.md b/docs/desktop-release.mdindex 42e75c21..c312bf1a 100644--- a/docs/desktop-release.md+++ b/docs/desktop-release.md@@ -122,6 +122,7 @@ gh release upload native-deps <archive> --repo simplexai-labs/linger| `Linger-<version>-windows-x64-setup.exe` | Windows x64 per-user installer || `Linger-<version>-windows-x64-portable.zip` | Windows x64 folder to run without installing || `Linger-<version>-macos-arm64.app.tar.gz` | macOS app the updater swaps in |+| `install.sh`, `install.ps1` | guided local-model & Computer installer scripts || `manifest.json`, `manifest.json.sig` | only with the update key: the [auto-update](#auto-update) feed || `SHA256SUMS.txt` | SHA-256 of every file above |diff --git a/scripts/ci/desktop-release.sh b/scripts/ci/desktop-release.shindex 790f31b2..385a4a49 100755--- a/scripts/ci/desktop-release.sh+++ b/scripts/ci/desktop-release.sh@@ -16,6 +16,9 @@ set -euo pipefail# desktop-release.sh build <target> fetch-native, compile and package# desktop-release.sh manifest <dir> <version> write the signed update manifest# (manifest.json and .sig) into <dir>+# desktop-release.sh install-scripts <dir> <version>+# verify stack pins and copy install.sh+# and install.ps1 into <dir># desktop-release.sh checksums <dir> <version> write <dir>/SHA256SUMS.txt# desktop-release.sh gitlab-upload <dir> <version># upload <dir>'s files to a GitLab generic@@ -67,7 +70,7 @@ die() {usage() {echo "Usage: $0 version <tag> | fetch-native|compile|package|build <target>" \- "| manifest|checksums <dir> <version> | github-release <dir> <tag> <version>" \+ "| manifest|install-scripts|checksums <dir> <version> | github-release <dir> <tag> <version>" \"| gitlab-upload <dir> <version>" >&2exit 2}@@ -332,9 +335,22 @@ NODEdie "could not write the update manifest"}+cmd_install_scripts() {+ local dir="${1:-}" version="${2:-}"+ [[ -d "$dir" && "$version" =~ $version_pattern ]] ||+ die "install-scripts needs the folder holding the release files and the release version"+ command -v node >/dev/null || die "install-scripts needs Node.js (node)"+ node "$repo_root/scripts/sync-install-stack-pin.mjs" --root "$repo_root" --check+ cp "$repo_root/scripts/install/install.sh" "$dir/install.sh"+ cp "$repo_root/scripts/install/install.ps1" "$dir/install.ps1"+ chmod 0755 "$dir/install.sh"+ chmod 0644 "$dir/install.ps1"+ echo "desktop-release: copied install.sh and install.ps1 for $version"+}+# Every release ships the three installers; SHA256SUMS.txt covers each file-# of the version, extra ones such as the portable zip and the app archive-# included, and the update manifest and its signature when there are.+# of the version, guided installer scripts, extra ones such as the portable+# zip and the app archive, and the update manifest and its signature when there are.cmd_checksums() {local dir="${1:-}" version="${2:-}" required file files=()[[ -d "$dir" ]] || die "checksums needs the folder holding the release files"@@ -344,7 +360,7 @@ cmd_checksums() {donewhile IFS= read -r file; dofiles+=("$(basename "$file")")- done < <(find "$dir" -maxdepth 1 -type f \( -name "Linger-$version-*" -o -name manifest.json -o -name manifest.json.sig \) | LC_ALL=C sort)+ done < <(find "$dir" -maxdepth 1 -type f \( -name "Linger-$version-*" -o -name install.sh -o -name install.ps1 -o -name manifest.json -o -name manifest.json.sig \) | LC_ALL=C sort): >"$dir/SHA256SUMS.txt.part"for file in "${files[@]}"; doprintf '%s %s\n' "$(sha256_of "$dir/$file")" "$file" >>"$dir/SHA256SUMS.txt.part"@@ -430,6 +446,7 @@ case "$command" inpackage) cmd_package "$@" ;;build) cmd_build "$@" ;;manifest) cmd_manifest "$@" ;;+ install-scripts) cmd_install_scripts "$@" ;;checksums) cmd_checksums "$@" ;;gitlab-upload) cmd_gitlab_upload "$@" ;;github-release) cmd_github_release "$@" ;;diff --git a/scripts/ci/desktop-release.test.ts b/scripts/ci/desktop-release.test.tsindex 7861a4b9..09ee0a67 100644--- a/scripts/ci/desktop-release.test.ts+++ b/scripts/ci/desktop-release.test.ts@@ -8,6 +8,7 @@ import {mkdtempSync,readFileSync,rmSync,+ statSync,writeFileSync,} from "node:fs";import { tmpdir } from "node:os";@@ -382,3 +383,74 @@ describe("desktop-release.sh github-release", () => {expect(result.stderr).toContain("owner/name");});});++describe("desktop-release.sh install-scripts", () => {+ const version = "0.16.33";++ it("exports verified install.sh and install.ps1 and covers them in SHA256SUMS.txt", () => {+ const dir = folder();+ for (const suffix of [+ "macos-arm64.dmg",+ "linux-x64.tar.gz",+ "windows-x64-setup.exe",+ ]) {+ writeFileSync(join(dir, `Linger-${version}-${suffix}`), suffix);+ }++ const exported = run(["install-scripts", dir, version]);+ expect(exported.status).toBe(0);+ expect(exported.stdout).toContain(+ `copied install.sh and install.ps1 for ${version}`,+ );+ expect(statSync(join(dir, "install.sh")).mode & 0o111).toBe(0o111);+ expect(existsSync(join(dir, "install.ps1"))).toBe(true);++ const sums = run(["checksums", dir, version]);+ expect(sums.status).toBe(0);+ const checksumText = readFileSync(join(dir, "SHA256SUMS.txt"), "utf8");+ const shHash = createHash("sha256")+ .update(readFileSync(join(process.cwd(), "scripts/install/install.sh")))+ .digest("hex");+ const ps1Hash = createHash("sha256")+ .update(readFileSync(join(process.cwd(), "scripts/install/install.ps1")))+ .digest("hex");+ expect(checksumText).toContain(`${shHash} install.sh\n`);+ expect(checksumText).toContain(`${ps1Hash} install.ps1\n`);+ });++ it("refuses install-scripts when standalone pins drift from scripts/installs", () => {+ const checkout = folder();+ for (const rel of ["scripts/ci", "scripts/install", "scripts/installs"]) {+ mkdirSync(join(checkout, rel), { recursive: true });+ }+ for (const file of [+ "scripts/ci/desktop-release.sh",+ "scripts/sync-install-stack-pin.mjs",+ "scripts/installs/stack.sh",+ "scripts/installs/stack.ps1",+ "scripts/install/install.sh",+ "scripts/install/install.ps1",+ ]) {+ copyFileSync(join(process.cwd(), file), join(checkout, file));+ }+ const driftedSh = readFileSync(+ join(checkout, "scripts/install/install.sh"),+ "utf8",+ ).replace(+ /STACK_PIN_SHA256='[a-f0-9]+'/,+ `STACK_PIN_SHA256='${"0".repeat(64)}'`,+ );+ writeFileSync(join(checkout, "scripts/install/install.sh"), driftedSh);++ const dir = folder();+ const result = run(+ ["install-scripts", dir, version],+ {},+ join(checkout, "scripts/ci/desktop-release.sh"),+ );++ expect(result.status).toBe(1);+ expect(result.stderr).toContain("Stack release pin drift");+ expect(existsSync(join(dir, "install.sh"))).toBe(false);+ });+});diff --git a/scripts/install.test.ts b/scripts/install.test.tsindex 77ecd440..8c51b4f7 100644--- a/scripts/install.test.ts+++ b/scripts/install.test.ts@@ -1,4 +1,5 @@import { execFile, spawn } from "node:child_process";+import { createHash } from "node:crypto";import {chmod,copyFile,@@ -16,6 +17,7 @@ import os from "node:os";import path from "node:path";import { fileURLToPath } from "node:url";import { promisify } from "node:util";+import { gzipSync } from "node:zlib";import { afterEach, describe, expect, it } from "vitest";@@ -1448,4 +1450,172 @@ describe("scripts/install/install.ps1 and release pin parity", () => {expect(stackPs1).toContain(`$StackSourceCommit = '${shCommit}'`);expect(stackPs1).toContain(`$StackNpmVersion = '${shNpm}'`);});++ it("keeps standalone install script stack pins synchronized and free of floating domain URLs", async () => {+ const syncScript = path.join(+ repositoryRoot,+ "scripts",+ "sync-install-stack-pin.mjs",+ );+ const { stdout } = await execFileAsync(+ process.execPath,+ [syncScript, "--check"],+ { cwd: repositoryRoot, encoding: "utf8" },+ );+ expect(stdout).toContain("Verified install stack pins");++ const [shBody, ps1Body] = await Promise.all([+ readFile(installScriptPath, "utf8"),+ readFile(+ path.join(repositoryRoot, "scripts", "install", "install.ps1"),+ "utf8",+ ),+ ]);+ expect(shBody).not.toContain("simplexai.com/stack");+ expect(ps1Body).not.toContain("simplexai.com/stack");+ });++ it("downloads, SHA-256 verifies, and rejects tampered @simplexai/localmodels tarballs when run standalone", async () => {+ const buildSingleFileTgz = (entryName: string, content: Buffer): Buffer => {+ const header = Buffer.alloc(512);+ header.write(entryName, 0, "ascii");+ header.write("0000755\0", 100, "ascii");+ header.write("0000000\0", 108, "ascii");+ header.write("0000000\0", 116, "ascii");+ header.write(+ `${content.length.toString(8).padStart(11, "0")}\0`,+ 124,+ "ascii",+ );+ header.write("00000000000\0", 136, "ascii");+ header.write(" ", 148, "ascii");+ header.write("0", 156, "ascii");+ header.write("ustar\0", 257, "ascii");+ header.write("00", 263, "ascii");+ let sum = 0;+ for (const byte of header) {+ sum += byte;+ }+ header.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148, "ascii");+ const pad = (512 - (content.length % 512)) % 512;+ const tar = Buffer.concat([+ header,+ content,+ Buffer.alloc(pad),+ Buffer.alloc(1024),+ ]);+ return gzipSync(tar);+ };++ const startMockNpm = async (expectedUrlPath: string, tgzBytes: Buffer) => {+ const srv = createServer((req, res) => {+ if (req.url === expectedUrlPath) {+ res.writeHead(200, { "content-type": "application/gzip" });+ res.end(tgzBytes);+ return;+ }+ res.writeHead(404);+ res.end("not found");+ });+ await new Promise<void>((resolve) => srv.listen(0, "127.0.0.1", resolve));+ cleanups.push(+ () =>+ new Promise<void>((resolve, reject) =>+ srv.close((err) => (err ? reject(err) : resolve())),+ ),+ );+ const addr = srv.address() as AddressInfo;+ return `http://127.0.0.1:${addr.port}`;+ };++ const root = await createTempRoot();+ await mkdir(path.join(root, "home"), { recursive: true });+ await chmod(path.join(root, "home"), 0o700);+ const standaloneDir = path.join(root, "standalone");+ await mkdir(standaloneDir, { recursive: true });+ const standaloneSh = path.join(standaloneDir, "install.sh");+ await copyFile(installScriptPath, standaloneSh);+ await chmod(standaloneSh, 0o755);++ const shRaw = await readFile(standaloneSh, "utf8");+ const npmVer = shRaw.match(/^STACK_PIN_NPM_VERSION='([^']+)'/m)?.[1];+ expect(npmVer).toBeTruthy();+ const tarUrlPath = `/@simplexai/localmodels/-/localmodels-${npmVer}.tgz`;++ // 1. Unmodified install.sh rejects a tampered package/stack.sh immediately.+ const tamperedUrl = await startMockNpm(+ tarUrlPath,+ buildSingleFileTgz(+ "package/stack.sh",+ Buffer.from("#!/bin/sh\necho bad\n"),+ ),+ );+ const envBase = buildTestEnv(root, "");+ delete envBase.LINGER_STACK_SCRIPT;+ delete envBase.LINGER_STACK_URL;+ const tamperedRes = await runInstallScript(["--status"], {+ scriptPath: standaloneSh,+ cwd: standaloneDir,+ env: { ...envBase, SIMPLEX_NPM_REGISTRY: tamperedUrl },+ });+ expect(tamperedRes.code).toBe(1);+ expect(tamperedRes.stderr).toContain(+ "Local model runtime bootstrap checksum mismatch.",+ );++ // 1b. Bounded streaming caps uncompressed package/stack.sh at 16 MiB.+ const oversizedUrl = await startMockNpm(+ tarUrlPath,+ buildSingleFileTgz(+ "package/stack.sh",+ Buffer.alloc(16 * 1024 * 1024 + 64),+ ),+ );+ const oversizedRes = await runInstallScript(["--status"], {+ scriptPath: standaloneSh,+ cwd: standaloneDir,+ env: { ...envBase, SIMPLEX_NPM_REGISTRY: oversizedUrl },+ });+ expect(oversizedRes.code).toBe(1);+ expect(oversizedRes.stderr).toContain(+ "Local model runtime bootstrap exceeds maximum size.",+ );++ // 2. Standalone install.sh extracts and runs verified package/stack.sh when SHA-256 matches.+ const fakeBody = Buffer.from(+ `#!/bin/sh+if [ "\${1:-}" = "--bootstrap-json" ]; then+ printf '{"schema":"localmodels.kit-location/v1","python":"/bin/sh"}\\n'+ exit 0+fi+if [ "\${1:-}" = "status" ]; then+ printf 'qwen3.8-27b active\\n'+ exit 0+fi+exit 0+`,+ "utf8",+ );+ const fakeSha = createHash("sha256").update(fakeBody).digest("hex");+ const pinnedSh = path.join(standaloneDir, "install-pinned.sh");+ await writeFile(+ pinnedSh,+ shRaw.replace(+ /STACK_PIN_SHA256='[a-f0-9]+'/,+ `STACK_PIN_SHA256='${fakeSha}'`,+ ),+ { mode: 0o755 },+ );+ const goodUrl = await startMockNpm(+ tarUrlPath,+ buildSingleFileTgz("package/stack.sh", fakeBody),+ );+ const goodRes = await runInstallScript(["--status"], {+ scriptPath: pinnedSh,+ cwd: standaloneDir,+ env: { ...envBase, SIMPLEX_NPM_REGISTRY: goodUrl },+ });+ expect(goodRes.code).toBe(0);+ expect(goodRes.stdout).toContain("qwen3.8-27b active");+ });});diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1index 8a551b8d..6a4b1a45 100644--- a/scripts/install/install.ps1+++ b/scripts/install/install.ps1@@ -166,7 +166,10 @@ $script:ScriptDir = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Pare$script:PowerShellExe = (Get-Process -Id $PID).Path$script:Utf8NoBom = New-Object System.Text.UTF8Encoding($false)$script:TempDirsToClean = New-Object System.Collections.Generic.List[string]-$script:DefaultStackUrl = 'https://simplexai.com/stack.ps1'+# >>> stack release pin+$script:StackPinNpmVersion = '0.1.0-dev.38'+$script:StackPinSha256 = 'adf4c67d0cf59a26e54484edf3ea7ad2c54001fbbaeaec6bd8f938096e6a4bdf'+# <<< stack release pin$script:StackScriptPath = ''$script:KitHome = ''$script:KitHomeResolved = $false@@ -558,6 +561,167 @@ function Test-PrivateWindowsDirectory([string]$Path) {}}+function Read-TarAsciiField([byte[]]$Buffer, [int]$Start, [int]$MaxLen) {+ $end = $Start+ $limit = [Math]::Min($Buffer.Length, ($Start + $MaxLen))+ while ($end -lt $limit -and $Buffer[$end] -ne 0) {+ $end+++ }+ if ($end -eq $Start) { return '' }+ return [Text.Encoding]::ASCII.GetString($Buffer, $Start, ($end - $Start))+}++function Extract-TarGzEntryBytes([string]$TgzPath, [string]$EntryPath) {+ $maxBytes = 16777216+ if ((Get-Item -LiteralPath $TgzPath).Length -gt $maxBytes) {+ return @{ ArchiveValid = $false; Found = $false; Bytes = $null }+ }+ $tarBytes = $null+ try {+ $fs = [IO.File]::OpenRead($TgzPath)+ try {+ $gz = New-Object IO.Compression.GZipStream($fs, [IO.Compression.CompressionMode]::Decompress)+ try {+ $ms = New-Object IO.MemoryStream+ try {+ $buf = New-Object byte[] 65536+ $total = 0+ while ($true) {+ $read = $gz.Read($buf, 0, $buf.Length)+ if ($read -le 0) { break }+ $total += $read+ if ($total -gt $maxBytes) {+ return @{ ArchiveValid = $false; Found = $false; Bytes = $null }+ }+ $ms.Write($buf, 0, $read)+ }+ $tarBytes = $ms.ToArray()+ } finally {+ $ms.Dispose()+ }+ } finally {+ $gz.Dispose()+ }+ } finally {+ $fs.Dispose()+ }+ } catch {+ return @{ ArchiveValid = $false; Found = $false; Bytes = $null }+ }++ $offset = 0+ while (($offset + 512) -le $tarBytes.Length) {+ $allZero = $true+ for ($i = 0; $i -lt 512; $i++) {+ if ($tarBytes[$offset + $i] -ne 0) {+ $allZero = $false+ break+ }+ }+ if ($allZero) { break }++ $rawName = Read-TarAsciiField $tarBytes $offset 100+ $magic = Read-TarAsciiField $tarBytes ($offset + 257) 5+ $prefix = if ($magic -eq 'ustar') { Read-TarAsciiField $tarBytes ($offset + 345) 155 } else { '' }+ $fullName = if ($prefix) { "$prefix/$rawName" } else { $rawName }+ $normalized = ($fullName -replace '^\./', '').Replace('\', '/')+ $sizeRaw = (Read-TarAsciiField $tarBytes ($offset + 124) 12).Trim()+ $entrySize = 0+ if ($sizeRaw) {+ try {+ $entrySize = [Convert]::ToInt32($sizeRaw, 8)+ } catch {+ return @{ ArchiveValid = $false; Found = $false; Bytes = $null }+ }+ }+ $typeByte = $tarBytes[$offset + 156]+ $dataStart = $offset + 512+ if ($entrySize -lt 0 -or ($dataStart + $entrySize) -gt $tarBytes.Length) {+ return @{ ArchiveValid = $false; Found = $false; Bytes = $null }+ }+ if (($typeByte -eq 0 -or $typeByte -eq 48) -and $normalized -eq $EntryPath) {+ $entryBytes = New-Object byte[] $entrySize+ if ($entrySize -gt 0) {+ [Buffer]::BlockCopy($tarBytes, $dataStart, $entryBytes, 0, $entrySize)+ }+ return @{ ArchiveValid = $true; Found = $true; Bytes = $entryBytes }+ }+ $padded = [int]([Math]::Ceiling($entrySize / 512.0) * 512)+ $offset = $dataStart + $padded+ }+ return @{ ArchiveValid = $true; Found = $false; Bytes = $null }+}++function Get-BytesSha256Hex([byte[]]$Bytes) {+ $sha = [Security.Cryptography.SHA256]::Create()+ try {+ $digest = $sha.ComputeHash($Bytes)+ return ([BitConverter]::ToString($digest) -replace '-', '').ToLowerInvariant()+ } finally {+ $sha.Dispose()+ }+}++function Download-PinnedStackScript([string]$DestinationPath, [string]$TempDir) {+ if (-not $script:StackPinNpmVersion -or -not $script:StackPinSha256) {+ Exit-Fail 'Local model runtime release pin is missing.'+ }++ $registries = @()+ $override = $env:SIMPLEX_NPM_REGISTRY+ if ($override) {+ $trimmed = $override.TrimEnd('/')+ if ($trimmed -notmatch '^https://[^/\s]+' -and $trimmed -notmatch '^http://(127\.0\.0\.1|localhost)(:\d+)?(/.*)?$') {+ Exit-Fail 'SIMPLEX_NPM_REGISTRY must use https or loopback http.'+ }+ $registries = @($trimmed)+ } else {+ $region = if ($env:SIMPLEX_REGION) { $env:SIMPLEX_REGION } else { 'auto' }+ if ($region -notin @('auto', 'global', 'cn')) {+ Exit-Fail 'SIMPLEX_REGION must be auto, global, or cn.'+ }+ if ($region -eq 'cn') {+ $registries = @('https://registry.npmmirror.com', 'https://registry.npmjs.org')+ } else {+ $registries = @('https://registry.npmjs.org', 'https://registry.npmmirror.com')+ }+ }++ $tgzPath = Join-Path $TempDir 'localmodels-launcher.tgz'+ $lastError = 'download failed'+ foreach ($base in $registries) {+ $tarUrl = "$base/@simplexai/localmodels/-/localmodels-$($script:StackPinNpmVersion).tgz"+ if (Test-Path -LiteralPath $tgzPath) {+ Remove-Item -LiteralPath $tgzPath -Force -ErrorAction SilentlyContinue+ }+ try {+ Invoke-WebRequest -UseBasicParsing -MaximumRedirection 5 -Uri $tarUrl -OutFile $tgzPath -TimeoutSec 60+ } catch {+ $lastError = $_.Exception.Message+ continue+ }++ $extracted = Extract-TarGzEntryBytes $tgzPath 'package/stack.ps1'+ if (-not $extracted.ArchiveValid) {+ $lastError = 'downloaded archive is invalid'+ continue+ }+ if (-not $extracted.Found) {+ Exit-Fail 'Downloaded runtime bootstrap archive is missing stack.ps1.'+ }+ $actualSha = Get-BytesSha256Hex ([byte[]]$extracted.Bytes)+ if ($actualSha -ne $script:StackPinSha256) {+ if (Test-Path -LiteralPath $DestinationPath) {+ Remove-Item -LiteralPath $DestinationPath -Force -ErrorAction SilentlyContinue+ }+ Exit-Fail 'Local model runtime bootstrap checksum mismatch.'+ }+ [IO.File]::WriteAllBytes($DestinationPath, [byte[]]$extracted.Bytes)+ return+ }+ Exit-Fail "Could not download the local model runtime helper: $lastError"+}+function Resolve-StackScript {if ($env:LINGER_STACK_SCRIPT) {if (-not (Test-Path -LiteralPath $env:LINGER_STACK_SCRIPT -PathType Leaf)) {@@ -577,11 +741,14 @@ function Resolve-StackScript {Set-PrivateWindowsDirectoryAcl $tempRoot$script:TempDirsToClean.Add($tempRoot)$dest = Join-Path $tempRoot 'stack.ps1'- $srcUrl = if ($env:LINGER_STACK_URL) { $env:LINGER_STACK_URL } else { $script:DefaultStackUrl }- try {- Invoke-WebRequest -UseBasicParsing -Uri $srcUrl -OutFile $dest -TimeoutSec 30- } catch {- Exit-Fail "Could not download the local model runtime helper: $($_.Exception.Message)"+ if ($env:LINGER_STACK_URL) {+ try {+ Invoke-WebRequest -UseBasicParsing -Uri $env:LINGER_STACK_URL -OutFile $dest -TimeoutSec 30+ } catch {+ Exit-Fail "Could not download the local model runtime helper: $($_.Exception.Message)"+ }+ } else {+ Download-PinnedStackScript $dest $tempRoot}$script:StackScriptPath = $dest}diff --git a/scripts/install/install.sh b/scripts/install/install.shindex 18f9ccbb..a1e2bb4c 100755--- a/scripts/install/install.sh+++ b/scripts/install/install.sh@@ -41,6 +41,11 @@ STACK_SCRIPT=""KIT_PYTHON=""PROMPT_VALUE=""+# >>> stack release pin+STACK_PIN_NPM_VERSION='0.1.0-dev.38'+STACK_PIN_SHA256='cc5a7397ca5703d47de72e5b7c012227d802f52429b5efe38844b625e452878d'+# <<< stack release pin+usage() {cat <<EOFUsage: $SELF_CMD [options]@@ -359,6 +364,95 @@ ensure_kit_home() {fi}+sha256_file() {+ local target="$1"+ if command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$target" | awk '{print $1}'+ elif command -v shasum >/dev/null 2>&1; then+ shasum -a 256 "$target" | awk '{print $1}'+ else+ die "sha256sum or shasum is required."+ fi+}++download_pinned_stack_script() {+ local dest="$1"+ command -v tar >/dev/null 2>&1 || die "tar is required."+ [[ -n "$STACK_PIN_NPM_VERSION" && -n "$STACK_PIN_SHA256" ]] ||+ die "Local model runtime release pin is missing."++ local registries=()+ local override="${SIMPLEX_NPM_REGISTRY:-}"+ if [[ -n "$override" ]]; then+ override="${override%/}"+ case "$override" in+ https://?* | http://127.0.0.1 | http://127.0.0.1:* | http://127.0.0.1/* | http://localhost | http://localhost:* | http://localhost/*) ;;+ *) die "SIMPLEX_NPM_REGISTRY must use https or loopback http." ;;+ esac+ registries=("$override")+ else+ local region="${SIMPLEX_REGION:-auto}"+ case "$region" in+ auto | global) registries=("https://registry.npmjs.org" "https://registry.npmmirror.com") ;;+ cn) registries=("https://registry.npmmirror.com" "https://registry.npmjs.org") ;;+ *) die "SIMPLEX_REGION must be auto, global, or cn." ;;+ esac+ fi++ local tgz_file="$WORK_DIR/localmodels-launcher.tgz"+ local extracted="$WORK_DIR/stack.sh.download"+ local base="" proto="" tar_url="" pipe_rc="" extracted_bytes="" actual_sha=""+ for base in "${registries[@]}"; do+ case "$base" in+ https://*) proto='=https' ;;+ *) proto='=http,https' ;;+ esac+ tar_url="$base/@simplexai/localmodels/-/localmodels-${STACK_PIN_NPM_VERSION}.tgz"+ rm -f "$tgz_file" "$extracted"+ if ! curl -fsSL --proto "$proto" --proto-redir '=https' --max-redirs 5 --max-filesize 16777216 --retry 2 --connect-timeout 15 --max-time 60 -o "$tgz_file" "$tar_url" 2>/dev/null; then+ continue+ fi+ if (( $(wc -c < "$tgz_file" | tr -d ' ') > 16777216 )); then+ rm -f "$tgz_file"+ continue+ fi+ set +e+ tar -xzOf "$tgz_file" package/stack.sh 2>/dev/null | head -c 16777217 > "$extracted"+ pipe_rc="${PIPESTATUS[0]}:${PIPESTATUS[1]}"+ set -e+ extracted_bytes="$(wc -c < "$extracted" 2>/dev/null | tr -d ' ' || printf '0')"+ if (( extracted_bytes > 16777216 )); then+ rm -f "$extracted" "$tgz_file" "$dest"+ die "Local model runtime bootstrap exceeds maximum size."+ fi+ if [[ "$pipe_rc" != "0:0" ]]; then+ rm -f "$extracted"+ if ! tar -tzf "$tgz_file" >/dev/null 2>&1; then+ rm -f "$tgz_file"+ continue+ fi+ rm -f "$tgz_file"+ die "Downloaded runtime bootstrap archive is missing stack.sh."+ fi+ if [[ ! -s "$extracted" ]]; then+ rm -f "$extracted" "$tgz_file"+ die "Downloaded runtime bootstrap archive is missing stack.sh."+ fi+ actual_sha="$(sha256_file "$extracted")"+ if [[ "$actual_sha" != "$STACK_PIN_SHA256" ]]; then+ rm -f "$extracted" "$tgz_file" "$dest"+ die "Local model runtime bootstrap checksum mismatch."+ fi+ mv -f "$extracted" "$dest"+ chmod 0700 "$dest"+ rm -f "$tgz_file"+ return 0+ done++ rm -f "$tgz_file" "$extracted"+ die "Could not download the local model runtime bootstrap."+}+ensure_engine() {check_supported_platformensure_kit_home@@ -367,11 +461,13 @@ ensure_engine() {STACK_SCRIPT="$LINGER_STACK_SCRIPT"elif [[ -n "$REPO_ROOT" && -r "$REPO_ROOT/scripts/installs/stack.sh" ]]; thenSTACK_SCRIPT="$REPO_ROOT/scripts/installs/stack.sh"- else+ elif [[ -n "${LINGER_STACK_URL:-}" ]]; thenSTACK_SCRIPT="$WORK_DIR/engine.sh"- local engine_url="${LINGER_STACK_URL:-https://simplexai.com/stack.sh}"- curl -fsSL "$engine_url" -o "$STACK_SCRIPT" || die "Could not download the local model runtime bootstrap."+ curl -fsSL "$LINGER_STACK_URL" -o "$STACK_SCRIPT" || die "Could not download the local model runtime bootstrap."chmod 0700 "$STACK_SCRIPT"+ else+ STACK_SCRIPT="$WORK_DIR/engine.sh"+ download_pinned_stack_script "$STACK_SCRIPT"filocal bootstrap_out=""diff --git a/scripts/install/install.tests.ps1 b/scripts/install/install.tests.ps1index b6c58f95..519537b7 100644--- a/scripts/install/install.tests.ps1+++ b/scripts/install/install.tests.ps1@@ -82,9 +82,112 @@ public sealed class TestHttpMockServer : IDisposable {try { _thread.Join(1000); } catch {}}}++public sealed class TestNpmTgzServer : IDisposable {+ private readonly TcpListener _listener;+ private readonly Thread _thread;+ private volatile bool _running;+ private readonly string _expectedPath;+ private readonly byte[] _tgzBytes;+ public int Port { get; private set; }+ public string BaseUrl { get { return "http://127.0.0.1:" + Port; } }++ public TestNpmTgzServer(string expectedPath, byte[] tgzBytes) {+ _expectedPath = expectedPath;+ _tgzBytes = tgzBytes;+ _listener = new TcpListener(IPAddress.Loopback, 0);+ _listener.Start();+ Port = ((IPEndPoint)_listener.LocalEndpoint).Port;+ _running = true;+ _thread = new Thread(Loop);+ _thread.IsBackground = true;+ _thread.Start();+ }++ private void Loop() {+ while (_running) {+ try {+ using (var client = _listener.AcceptTcpClient())+ using (var stream = client.GetStream()) {+ var reader = new StreamReader(stream, Encoding.ASCII, false, 1024, true);+ var requestLine = reader.ReadLine() ?? "";+ while (true) {+ var line = reader.ReadLine();+ if (string.IsNullOrEmpty(line)) break;+ }+ if (requestLine.StartsWith("GET " + _expectedPath + " ", StringComparison.Ordinal)) {+ var header = Encoding.ASCII.GetBytes(+ "HTTP/1.1 200 OK\r\nContent-Type: application/gzip\r\nContent-Length: " ++ _tgzBytes.Length + "\r\nConnection: close\r\n\r\n");+ stream.Write(header, 0, header.Length);+ stream.Write(_tgzBytes, 0, _tgzBytes.Length);+ } else {+ var header = Encoding.ASCII.GetBytes(+ "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");+ stream.Write(header, 0, header.Length);+ }+ }+ } catch {+ if (!_running) break;+ }+ }+ }++ public void Dispose() {+ _running = false;+ try { _listener.Stop(); } catch {}+ try { _thread.Join(1000); } catch {}+ }+}'@}+function New-SingleFileTgzBytes([string]$EntryName, [byte[]]$ContentBytes) {+ $header = New-Object byte[] 512+ $nameBytes = [Text.Encoding]::ASCII.GetBytes($EntryName)+ [Buffer]::BlockCopy($nameBytes, 0, $header, 0, [Math]::Min($nameBytes.Length, 100))+ foreach ($pair in @(+ @{ Off = 100; Val = "0000755`0" },+ @{ Off = 108; Val = "0000000`0" },+ @{ Off = 116; Val = "0000000`0" },+ @{ Off = 124; Val = ([Convert]::ToString($ContentBytes.Length, 8).PadLeft(11, '0') + "`0") },+ @{ Off = 136; Val = "00000000000`0" },+ @{ Off = 148; Val = ' ' },+ @{ Off = 156; Val = '0' },+ @{ Off = 257; Val = "ustar`0" },+ @{ Off = 263; Val = '00' }+ )) {+ $b = [Text.Encoding]::ASCII.GetBytes($pair.Val)+ [Buffer]::BlockCopy($b, 0, $header, $pair.Off, $b.Length)+ }+ $sum = 0+ for ($i = 0; $i -lt 512; $i++) { $sum += [int]$header[$i] }+ $chk = [Convert]::ToString($sum, 8).PadLeft(6, '0') + "`0 "+ $chkBytes = [Text.Encoding]::ASCII.GetBytes($chk)+ [Buffer]::BlockCopy($chkBytes, 0, $header, 148, $chkBytes.Length)++ $padLen = (512 - ($ContentBytes.Length % 512)) % 512+ $ms = New-Object IO.MemoryStream+ try {+ $gz = New-Object IO.Compression.GZipStream($ms, [IO.Compression.CompressionMode]::Compress, $true)+ try {+ $gz.Write($header, 0, $header.Length)+ if ($ContentBytes.Length -gt 0) { $gz.Write($ContentBytes, 0, $ContentBytes.Length) }+ if ($padLen -gt 0) {+ $padBytes = New-Object byte[] $padLen+ $gz.Write($padBytes, 0, $padBytes.Length)+ }+ $trailer = New-Object byte[] 1024+ $gz.Write($trailer, 0, $trailer.Length)+ } finally {+ $gz.Dispose()+ }+ return ,$ms.ToArray()+ } finally {+ $ms.Dispose()+ }+}+function Assert-True([bool]$Condition, [string]$Message) {$script:Assertions++if (-not $Condition) {@@ -754,6 +857,84 @@ exit 0$mDay2.Server.Dispose()}+ # 7. Standalone @simplexai/localmodels tarball download, SHA-256 verification & tamper rejection+ $dPkg = Join-Path $workRoot 't-pkg'+ $hPkg = Join-Path $dPkg 'home'+ $laPkg = Join-Path $dPkg 'la'+ $saPkgDir = Join-Path $dPkg 'standalone'+ foreach ($dirToMake in @($hPkg, $laPkg, $saPkgDir)) {+ $null = New-Item -ItemType Directory -Path $dirToMake -Force+ }+ $saPs1 = Join-Path $saPkgDir 'install.ps1'+ Copy-Item -LiteralPath $InstallScriptPath -Destination $saPs1 -Force+ $ps1Raw = [IO.File]::ReadAllText($saPs1, $script:Utf8NoBom)+ $npmMatch = [regex]::Match($ps1Raw, '\$script:StackPinNpmVersion = ''([^'']+)''')+ Assert-True $npmMatch.Success 'install.ps1 declares StackPinNpmVersion'+ $npmPinVer = $npmMatch.Groups[1].Value+ $tarUrlPath = "/@simplexai/localmodels/-/localmodels-$npmPinVer.tgz"++ $badStackBytes = $script:Utf8NoBom.GetBytes("Write-Output 'tampered'`n")+ [byte[]]$badTgz = New-SingleFileTgzBytes 'package/stack.ps1' $badStackBytes+ $srvBad = New-Object TestNpmTgzServer($tarUrlPath, $badTgz)+ try {+ $envBad = @{+ USERPROFILE = $hPkg+ HOME = $hPkg+ LOCALAPPDATA = $laPkg+ LINGER_STACK_SCRIPT = $null+ LINGER_STACK_URL = $null+ SIMPLEX_NPM_REGISTRY = $srvBad.BaseUrl+ LINGER_INSTALL_TEST_ELEVATED = '0'+ }+ $rTampered = Invoke-Script @('--status') $envBad '' $saPs1 $saPkgDir+ Assert-Exit $rTampered 1 'tampered npm tgz rejected'+ Assert-Contains $rTampered.StdErr 'Local model runtime bootstrap checksum mismatch.' 'tampered checksum message'+ } finally {+ $srvBad.Dispose()+ }++ $fakeStackBody = @'+if ($args.Count -ge 1 -and $args[0] -eq '--bootstrap-json') {+ Write-Output '{"schema":"localmodels.kit-location/v1","python":"ok"}'+ exit 0+}+if ($args.Count -ge 1 -and $args[0] -eq 'status') {+ Write-Output 'qwen3.8-27b active'+ exit 0+}+exit 0+'@+ $goodStackBytes = $script:Utf8NoBom.GetBytes($fakeStackBody)+ $shaAlg = [Security.Cryptography.SHA256]::Create()+ try {+ $goodSha = ([BitConverter]::ToString($shaAlg.ComputeHash($goodStackBytes)) -replace '-', '').ToLowerInvariant()+ } finally {+ $shaAlg.Dispose()+ }+ $pinnedSaPs1 = Join-Path $saPkgDir 'install-pinned.ps1'+ $pinShaMatch = [regex]::Match($ps1Raw, '\$script:StackPinSha256 = ''[a-f0-9]+''')+ Assert-True $pinShaMatch.Success 'install.ps1 declares StackPinSha256'+ $patchedPs1 = $ps1Raw.Replace($pinShaMatch.Value, ('$script:StackPinSha256 = ''' + $goodSha + ''''))+ [IO.File]::WriteAllText($pinnedSaPs1, $patchedPs1, $script:Utf8NoBom)+ [byte[]]$goodTgz = New-SingleFileTgzBytes 'package/stack.ps1' $goodStackBytes+ $srvGood = New-Object TestNpmTgzServer($tarUrlPath, $goodTgz)+ try {+ $envGood = @{+ USERPROFILE = $hPkg+ HOME = $hPkg+ LOCALAPPDATA = $laPkg+ LINGER_STACK_SCRIPT = $null+ LINGER_STACK_URL = $null+ SIMPLEX_NPM_REGISTRY = $srvGood.BaseUrl+ LINGER_INSTALL_TEST_ELEVATED = '0'+ }+ $rGood = Invoke-Script @('--status') $envGood '' $pinnedSaPs1 $saPkgDir+ Assert-Exit $rGood 0 'verified npm tgz executes status'+ Assert-Contains $rGood.StdOut 'qwen3.8-27b active' 'verified npm tgz status output'+ } finally {+ $srvGood.Dispose()+ }+Write-Host "ALL $($script:Assertions) ASSERTIONS PASSED under $($script:CurrentExe)!"} finally {Remove-TreeClean $workRootdiff --git a/scripts/installs/README.md b/scripts/installs/README.mdindex d812c25d..1d04d96a 100644--- a/scripts/installs/README.md+++ b/scripts/installs/README.md@@ -3,7 +3,10 @@This directory holds only the entry scripts of the local model stack, plus thisREADME. Its release pipeline generates the scripts with pinned versions; source,tests and release tools stay in their own repository, and the pipeline rewrites-only its scripts and its marked section below.+only its scripts and its marked section below. After updating `stack.sh` and+`stack.ps1`, run `node scripts/sync-install-stack-pin.mjs --write` so+`scripts/install/install.sh` and `scripts/install/install.ps1` keep matching+release pins.## Your own API keys: `user.env`diff --git a/scripts/sync-install-stack-pin.mjs b/scripts/sync-install-stack-pin.mjsnew file mode 100755index 00000000..bde60cad--- /dev/null+++ b/scripts/sync-install-stack-pin.mjs@@ -0,0 +1,183 @@+#!/usr/bin/env node++import { createHash } from "node:crypto";+import { readFileSync, writeFileSync } from "node:fs";+import path from "node:path";+import process from "node:process";+import { fileURLToPath } from "node:url";++const MARKER_BEGIN = "# >>> stack release pin";+const MARKER_END = "# <<< stack release pin";+const BLOCK_PATTERN =+ /# >>> stack release pin\r?\n[\s\S]*?\r?\n# <<< stack release pin/g;++function parseArgs(argv) {+ let mode = "check";+ let root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+ for (let i = 0; i < argv.length; i += 1) {+ const arg = argv[i];+ if (arg === "--write") {+ mode = "write";+ } else if (arg === "--check") {+ mode = "check";+ } else if (arg === "--root") {+ const value = argv[i + 1];+ if (!value) {+ throw new Error("--root requires a directory path");+ }+ root = path.resolve(value);+ i += 1;+ } else {+ throw new Error(`Unknown option: ${arg}`);+ }+ }+ return { mode, root };+}++function sha256Hex(buffer) {+ return createHash("sha256").update(buffer).digest("hex");+}++function readPinField(text, pattern, label, file) {+ const match = pattern.exec(text);+ if (!match?.[1]) {+ throw new Error(`Missing ${label} in ${file}`);+ }+ return match[1];+}++function readSourcePins(root) {+ const stackShRel = "scripts/installs/stack.sh";+ const stackPs1Rel = "scripts/installs/stack.ps1";+ const shBytes = readFileSync(path.join(root, stackShRel));+ const psBytes = readFileSync(path.join(root, stackPs1Rel));+ const shText = shBytes.toString("utf8");+ const psText = psBytes.toString("utf8");++ const shVersion = readPinField(+ shText,+ /^STACK_VERSION='([^']+)'/m,+ "STACK_VERSION",+ stackShRel,+ );+ const shNpm = readPinField(+ shText,+ /^STACK_NPM_VERSION='([^']+)'/m,+ "STACK_NPM_VERSION",+ stackShRel,+ );+ const psVersion = readPinField(+ psText,+ /^\$StackVersion = '([^']+)'/m,+ "$StackVersion",+ stackPs1Rel,+ );+ const psNpm = readPinField(+ psText,+ /^\$StackNpmVersion = '([^']+)'/m,+ "$StackNpmVersion",+ stackPs1Rel,+ );++ if (shVersion !== psVersion) {+ throw new Error(+ `Version mismatch between ${stackShRel} (${shVersion}) and ${stackPs1Rel} (${psVersion})`,+ );+ }+ if (shNpm !== psNpm) {+ throw new Error(+ `npm version mismatch between ${stackShRel} (${shNpm}) and ${stackPs1Rel} (${psNpm})`,+ );+ }++ return {+ version: shVersion,+ npmVersion: shNpm,+ shSha256: sha256Hex(shBytes),+ psSha256: sha256Hex(psBytes),+ };+}++function renderShellBlock(pins, eol) {+ return [+ MARKER_BEGIN,+ `STACK_PIN_NPM_VERSION='${pins.npmVersion}'`,+ `STACK_PIN_SHA256='${pins.shSha256}'`,+ MARKER_END,+ ].join(eol);+}++function renderPowershellBlock(pins, eol) {+ return [+ MARKER_BEGIN,+ `$script:StackPinNpmVersion = '${pins.npmVersion}'`,+ `$script:StackPinSha256 = '${pins.psSha256}'`,+ MARKER_END,+ ].join(eol);+}++function syncTarget(root, relativePath, renderBlock) {+ const fullPath = path.join(root, relativePath);+ const current = readFileSync(fullPath, "utf8");+ const eol = current.includes("\r\n") ? "\r\n" : "\n";+ const matches = [...current.matchAll(BLOCK_PATTERN)];+ if (matches.length !== 1) {+ throw new Error(+ `Expected exactly one '${MARKER_BEGIN}'..'${MARKER_END}' block in ${relativePath}, found ${matches.length}`,+ );+ }+ const expectedBlock = renderBlock(eol);+ const existingBlock = matches[0][0];+ const updated =+ existingBlock === expectedBlock+ ? current+ : current.slice(0, matches[0].index) ++ expectedBlock ++ current.slice(matches[0].index + existingBlock.length);+ return {+ relativePath,+ fullPath,+ changed: updated !== current,+ updated,+ };+}++function main() {+ const { mode, root } = parseArgs(process.argv.slice(2));+ const pins = readSourcePins(root);+ const results = [+ syncTarget(root, "scripts/install/install.sh", (eol) =>+ renderShellBlock(pins, eol),+ ),+ syncTarget(root, "scripts/install/install.ps1", (eol) =>+ renderPowershellBlock(pins, eol),+ ),+ ];++ const drifted = results.filter((entry) => entry.changed);+ if (mode === "write") {+ for (const entry of drifted) {+ writeFileSync(entry.fullPath, entry.updated, "utf8");+ process.stdout.write(`Updated ${entry.relativePath}\n`);+ }+ if (drifted.length === 0) {+ process.stdout.write("Install stack release pins are up to date.\n");+ }+ return;+ }++ if (drifted.length > 0) {+ const names = drifted.map((entry) => entry.relativePath).join(", ");+ process.stderr.write(+ `Stack release pin drift in: ${names}\nRun: node scripts/sync-install-stack-pin.mjs --write\n`,+ );+ process.exitCode = 1;+ return;+ }++ process.stdout.write(+ `Verified install stack pins (${pins.version} / ${pins.npmVersion}).\n`,+ );+}++main();