#!/bin/sh # SPDX-License-Identifier: MIT # Copyright (c) 2026 Q1Z3 contributors # Q1Z3 local client installer. License: https://q1z3.com/local-client.LICENSE.txt # Source: https://q1z3.com/local-client.SOURCE.md # Everything is installed for the current user. No sudo, shell edits, services, # model downloads or changes to another running gateway. set -eu umask 077 say() { printf '%s\n' "$*"; } die() { printf 'Q1Z3: %s\n' "$*" >&2; exit 1; } handle='' while [ "$#" -gt 0 ]; do case "$1" in --handle) [ "$#" -ge 2 ] || die 'Use --handle followed by your public handle.'; handle=$2; shift 2 ;; *) die 'Usage: sh install.sh [--handle your-handle]' ;; esac done case "$handle" in '') ;; *[!a-z0-9-]*|[!a-z]*|*-|*--*) die 'Use your handle without @: 3–24 lowercase letters, numbers or single hyphens.' ;; esac if [ -n "$handle" ]; then [ "${#handle}" -ge 3 ] && [ "${#handle}" -le 24 ] || die 'A handle has 3–24 characters.'; fi [ "$(id -u)" != 0 ] || die 'Run this as your normal user, without sudo.' case "${HOME:-}" in /*) ;; *) die 'Your HOME must be an absolute directory.' ;; esac origin='https://q1z3.com' node_origin='https://nodejs.org/dist' install_root="$HOME/.local/share/q1z3" test_mode=0 check_loopback() { candidate=$1 case "$candidate" in http://127.0.0.1:*) fixture_port=${candidate#http://127.0.0.1:} ;; *) die 'Installer tests only use numeric loopback URLs.' ;; esac case "$fixture_port" in ''|*[!0-9]*) die 'Installer tests need a plain numeric loopback port.' ;; esac [ "${#fixture_port}" -le 5 ] && [ "$fixture_port" -ge 1 ] && [ "$fixture_port" -le 65535 ] || die 'Invalid fixture port.' } if [ "${Q1Z3_INSTALL_TEST:-}" = 1 ]; then case "${Q1Z3_INSTALL_TEST_ROOT:-}" in /private/tmp/q1z3-installer-test-*/install|/tmp/q1z3-installer-test-*/install) install_root=$Q1Z3_INSTALL_TEST_ROOT ;; *) die 'Installer tests need an isolated temporary install directory.' ;; esac case "${Q1Z3_INSTALL_TEST_ORIGIN:-}" in http://127.0.0.1:*) origin=$Q1Z3_INSTALL_TEST_ORIGIN ;; *) die 'Installer tests only use a numeric loopback fixture.' ;; esac case "${Q1Z3_INSTALL_TEST_NODE_ORIGIN:-}" in http://127.0.0.1:*/dist) node_origin=$Q1Z3_INSTALL_TEST_NODE_ORIGIN ;; *) die 'Installer tests only use a numeric loopback Node fixture.' ;; esac check_loopback "$origin" check_loopback "${node_origin%/dist}" test_mode=1 fi for tool in curl tar awk mktemp id uname wc; do command -v "$tool" >/dev/null 2>&1 || die "Install $tool first, then run this command again."; done case "$(uname -s)" in Darwin) platform=darwin ;; Linux) platform=linux ;; *) die 'This installer supports macOS and Linux. Use browser mode on other systems.' ;; esac case "$(uname -m)" in arm64|aarch64) architecture=arm64 ;; x86_64|amd64) architecture=x64 ;; *) die 'This installer supports Intel/AMD 64-bit and ARM64 machines.' ;; esac # Refuse symbolic links in every installation ancestor, including test roots. check_path() { path=$1 case "$path" in /*) ;; *) die 'Installation paths must be absolute.' ;; esac case "$path" in *'/../'*|*'/./'*|*'//'*) die 'Unsafe installation path.' ;; esac while [ "$path" != / ]; do [ ! -L "$path" ] || die "Refusing a symbolic link in $path"; path=${path%/*}; [ -n "$path" ] || path=/; done } check_path "$install_root" mkdir -p "$install_root" [ -d "$install_root" ] || die 'The installation directory is not a directory.' if [ "$platform" = darwin ]; then root_owner=$(stat -f '%u' "$install_root"); else root_owner=$(stat -c '%u' "$install_root"); fi [ "$root_owner" = "$(id -u)" ] || die 'The installation directory belongs to another user.' [ ! -e "$install_root/.install-lock" ] && [ ! -L "$install_root/.install-lock" ] || die 'Another installation is in progress. If interrupted, inspect and remove the .install-lock directory, then retry.' mkdir "$install_root/.install-lock" || die 'Another installation is in progress.' stage=$(mktemp -d "$install_root/.stage.XXXXXXXX") cleanup() { [ -z "${stage:-}" ] || rm -rf "$stage"; rmdir "$install_root/.install-lock" 2>/dev/null || :; } trap cleanup EXIT trap 'exit 130' INT trap 'exit 143' TERM fetch_file() { url=$1 destination=$2 maximum=$3 if [ "$test_mode" = 1 ]; then curl --fail --silent --show-error --location --max-redirs 0 --proto '=http' --proto-redir '=http' --connect-timeout 15 --max-time 300 --max-filesize "$maximum" --output "$destination" "$url" else curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --connect-timeout 15 --max-time 300 --max-filesize "$maximum" --output "$destination" "$url" fi || die 'Download failed. Your existing client and context were not changed. Run the command again when connected.' [ "$(wc -c < "$destination" | tr -d ' ')" -le "$maximum" ] || die 'The download exceeds its size limit.' } checksum() { if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | awk '{print $1}' elif command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}' else die 'Install shasum or sha256sum to verify the Node.js download.'; fi } node_bin='' if command -v node >/dev/null 2>&1 && node -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 24 ? 0 : 1)' >/dev/null 2>&1; then node_bin=$(node -p 'process.execPath') fi runtime_name='' # Reuse a previously verified private runtime. Check metadata, every containing # directory and the binary hash before executing anything from the install root. if [ -z "$node_bin" ] && [ -e "$install_root/node-path" ]; then private_entry() { entry=$1 expected_mode=$2 check_path "$entry" [ -e "$entry" ] || die 'The private runtime is incomplete. Inspect the installation, then rerun.' if [ "$platform" = darwin ]; then entry_owner=$(stat -f '%u' "$entry"); entry_mode=$(stat -f '%Lp' "$entry"); else entry_owner=$(stat -c '%u' "$entry"); entry_mode=$(stat -c '%a' "$entry"); fi [ "$entry_owner" = "$(id -u)" ] && [ "$entry_mode" = "$expected_mode" ] || die 'The private runtime must belong to you and remain private.' } private_entry "$install_root" 700 private_entry "$install_root/node-path" 600 [ -f "$install_root/node-path" ] || die 'Invalid private runtime metadata.' cached_node=$(cat "$install_root/node-path") case "$cached_node" in "$install_root"/runtimes/*) relative_node=${cached_node#"$install_root/runtimes/"} printf '%s\n' "$relative_node" | awk -v suffix="-$platform-$architecture/bin/node" 'length($0)>0 && $0 ~ /^node-v24\.[0-9]+\.[0-9]+-/ && substr($0,length($0)-length(suffix)+1)==suffix && $0 !~ /[^a-zA-Z0-9.\/-]/ {valid=1} END {exit !valid}' || die 'Invalid private runtime path.' private_entry "$install_root/node-sha256" 600 [ -f "$install_root/node-sha256" ] || die 'Invalid private runtime checksum.' cached_sha=$(cat "$install_root/node-sha256") case "$cached_sha" in *[!a-f0-9]*) die 'Invalid private runtime checksum.' ;; esac [ "${#cached_sha}" = 64 ] || die 'Invalid private runtime checksum.' entry=$cached_node while [ "$entry" != "$install_root" ]; do private_entry "$entry" 700; entry=${entry%/*}; done [ -f "$cached_node" ] || die 'The private runtime binary is not a regular file.' [ "$(checksum "$cached_node")" = "$cached_sha" ] || die 'The private Node.js runtime checksum changed. No client or context was changed.' "$cached_node" -e 'process.exit(Number(process.versions.node.split(".")[0]) === 24 ? 0 : 1)' || die 'The private runtime cannot run on this machine.' node_bin=$cached_node ;; esac fi if [ -z "$node_bin" ]; then say 'Installing a private Node.js 24 runtime (no system changes)…' fetch_file "$node_origin/latest-v24.x/SHASUMS256.txt" "$stage/node-checksums" 1048576 matches=$(awk -v suffix="-$platform-$architecture.tar.gz" '$1 ~ /^[0-9a-f]+$/ && length($1)==64 && $2 ~ /^node-v24\.[0-9]+\.[0-9]+-/ && substr($2,length($2)-length(suffix)+1)==suffix {print $1 " " $2}' "$stage/node-checksums") [ "$(printf '%s\n' "$matches" | wc -l | tr -d ' ')" = 1 ] && [ -n "$matches" ] || die 'The official Node.js checksum catalog is invalid. Retry later.' expected_node_sha=${matches%% *}; node_file=${matches#* } case "$node_file" in *[!a-zA-Z0-9.-]*) die 'Invalid Node.js archive name.' ;; esac runtime_name=${node_file%.tar.gz}; node_version=${runtime_name#node-}; node_version=${node_version%%-*} fetch_file "$node_origin/$node_version/$node_file" "$stage/node.tgz" 104857600 [ "$(checksum "$stage/node.tgz")" = "$expected_node_sha" ] || die 'Node.js checksum mismatch. Nothing was installed.' # Extract only the verified runtime binary and its license, never archive links. tar -tzf "$stage/node.tgz" > "$stage/node-list" || die 'The Node.js archive is invalid.' awk -v prefix="$runtime_name/" 'index($0,prefix)!=1 || $0 ~ /(^|\/)\.\.?(\/|$)/ {bad=1} END {exit bad}' "$stage/node-list" || die 'Unsafe paths in the Node.js archive.' for member in "$runtime_name/bin/node" "$runtime_name/LICENSE"; do [ "$(awk -v member="$member" '$0==member {count++} END {print count+0}' "$stage/node-list")" = 1 ] || die 'The Node.js runtime archive is incomplete.' listing=$(tar -tvzf "$stage/node.tgz" "$member") || die 'Cannot inspect the Node.js runtime.' case "$listing" in -*) ;; *) die 'The Node.js binary or license is not a regular file.' ;; esac done mkdir "$stage/runtime" tar -xzf "$stage/node.tgz" -C "$stage/runtime" "$runtime_name/bin/node" "$runtime_name/LICENSE" || die 'Cannot unpack the Node.js runtime.' chmod 700 "$stage/runtime/$runtime_name" "$stage/runtime/$runtime_name/bin" "$stage/runtime/$runtime_name/bin/node" chmod 600 "$stage/runtime/$runtime_name/LICENSE" node_bin="$stage/runtime/$runtime_name/bin/node" "$node_bin" -e 'process.exit(Number(process.versions.node.split(".")[0]) === 24 ? 0 : 1)' || die 'This Node.js runtime cannot run on your machine. Use browser mode or install a compatible Node.js 24 runtime.' fi say 'Installing Q1Z3 — open source, local context…' fetch_file "$origin/local-gateway.manifest.json" "$stage/manifest.json" 1048576 "$node_bin" --input-type=module - "$stage/manifest.json" > "$stage/archive-info" <<'JS' import {readFileSync} from 'node:fs'; const manifest=JSON.parse(readFileSync(process.argv[2],'utf8')); if(manifest.schema!=='q1z3.local-gateway-manifest'||manifest.version!==1||manifest.directory!=='q1z3-local-gateway'||manifest.entrypoint!=='gateway/server.mjs'||manifest.archive!=='/local-gateway.tgz'||!/^\w{64}$/.test(manifest.archiveSha256)||!/^[a-f0-9]{64}$/.test(manifest.archiveSha256)||!Number.isSafeInteger(manifest.archiveBytes)||manifest.archiveBytes<1024||manifest.archiveBytes>12582912)throw Error('Invalid Q1Z3 release manifest.'); console.log(manifest.archive);console.log(manifest.archiveSha256);console.log(manifest.archiveBytes); JS archive_path=$(sed -n '1p' "$stage/archive-info") fetch_file "$origin$archive_path" "$stage/client.tgz" 12582912 # This verifier never delegates extraction to tar. Only regular, hashed public # source files are accepted; no links, hidden paths, traversal or extra payloads. "$node_bin" --input-type=module - "$stage" "$install_root" "$runtime_name" "$node_bin" "$test_mode" <<'JS' import fs from 'node:fs'; import path from 'node:path'; import {createHash,randomUUID} from 'node:crypto'; import {gunzipSync} from 'node:zlib'; const [stage,root,runtimeName,nodeBinary,testMode]=process.argv.slice(2); const sha=bytes=>createHash('sha256').update(bytes).digest('hex'); function safe(file,{directory=false,optional=false}={}){ const parent=path.dirname(file);if(parent!==file)safe(parent,{directory:true}); let info;try{info=fs.lstatSync(file);}catch(error){if(optional&&error.code==='ENOENT')return;throw error;} if(info.isSymbolicLink()||directory&&!info.isDirectory()||!directory&&(!info.isFile()||info.nlink!==1))throw Error('Unsafe installation path: '+file); if(file===root||file.startsWith(root+path.sep)){if(info.uid!==process.getuid()||(info.mode&0o077)!==0)throw Error('Installation files must belong to you and be private: '+file);} } safe(root,{directory:true}); const manifest=JSON.parse(fs.readFileSync(path.join(stage,'manifest.json'),'utf8')); const archive=fs.readFileSync(path.join(stage,'client.tgz')); if(archive.length!==manifest.archiveBytes||sha(archive)!==manifest.archiveSha256)throw Error('Q1Z3 archive checksum mismatch. Your existing release and profile were not changed.'); if(!Array.isArray(manifest.files)||manifest.files.length<10||manifest.files.length>256)throw Error('Invalid Q1Z3 source manifest.'); const expected=new Map(); const validName=name=>typeof name==='string'&&name.length<=100&&/^[a-zA-Z0-9_-][a-zA-Z0-9_./-]*$/.test(name)&&!name.split('/').some(part=>part==='.'||part==='..'||part===''); for(const entry of manifest.files){if(!validName(entry.path)||entry.path==='gateway-manifest.json'||expected.has(entry.path)||!Number.isSafeInteger(entry.bytes)||entry.bytes<0||entry.bytes>12582912||!/^[a-f0-9]{64}$/.test(entry.sha256))throw Error('Invalid Q1Z3 source entry.');expected.set(entry.path,entry);} for(const required of ['LICENSE','package.json','gateway/server.mjs','worker/index.mjs','public/index.html'])if(!expected.has(required))throw Error('The Q1Z3 source archive is incomplete.'); const bytes=gunzipSync(archive,{maxOutputLength:67108864}),files=new Map();let at=0,ended=false; while(at+512<=bytes.length){ const header=bytes.subarray(at,at+512); if(header.every(value=>value===0)){if(bytes.subarray(at).some(value=>value!==0)||bytes.length-at<1024)throw Error('Invalid archive terminator.');ended=true;break;} const number=(start,length)=>{const text=header.subarray(start,start+length).toString('ascii').replace(/\0.*$/s,'').trim();if(!/^[0-7]+$/.test(text))throw Error('Invalid archive number.');return parseInt(text,8);}; const sum=number(148,8),actual=[...header].reduce((total,value,index)=>total+(index>=148&&index<156?32:value),0); const fullName=header.subarray(0,100).toString('ascii').replace(/\0.*$/s,''),prefix='q1z3-local-gateway/'; if(sum!==actual||header[156]!==48||header.subarray(345,500).some(value=>value!==0)||!fullName.startsWith(prefix))throw Error('Unsafe Q1Z3 archive entry.'); const name=fullName.slice(prefix.length),length=number(124,12),end=at+512+length,next=at+512+Math.ceil(length/512)*512; if(!validName(name)||files.has(name)||length>12582912||end>bytes.length||next>bytes.length)throw Error('Unsafe Q1Z3 archive path or size.'); const content=bytes.subarray(at+512,end),entry=expected.get(name); if(name==='gateway-manifest.json'){const embedded=JSON.parse(content.toString('utf8'));if(embedded.schema!==manifest.schema||embedded.version!==1)throw Error('Invalid embedded release manifest.');} else if(!entry||entry.bytes!==content.length||entry.sha256!==sha(content))throw Error('Q1Z3 source checksum mismatch: '+name); files.set(name,content);at=next; } if(!ended||files.size!==expected.size+1||!files.has('gateway-manifest.json'))throw Error('The Q1Z3 archive is incomplete.'); const packageJSON=JSON.parse(files.get('package.json').toString('utf8')); if(packageJSON.type!=='module'||Object.keys(packageJSON.dependencies||{}).length||packageJSON.license!=='MIT')throw Error('Unexpected Q1Z3 runtime dependencies or license.'); for(const directory of ['releases','profile','runtimes']){const full=path.join(root,directory);safe(full,{directory:true,optional:true});if(!fs.existsSync(full))fs.mkdirSync(full,{mode:0o700});} const release=path.join(root,'releases',manifest.archiveSha256);safe(release,{directory:true,optional:true}); if(fs.existsSync(release)){ for(const [name,content]of files){const full=path.join(release,name);safe(full);if(sha(fs.readFileSync(full))!==sha(content))throw Error('The installed release changed: '+name);} }else{ const unpacked=path.join(stage,'verified-source');fs.mkdirSync(unpacked,{mode:0o700}); for(const [name,content]of files){const target=path.join(unpacked,name);fs.mkdirSync(path.dirname(target),{recursive:true,mode:0o700});fs.writeFileSync(target,content,{mode:0o600,flag:'wx'});} fs.renameSync(unpacked,release); } let installedNode=nodeBinary; if(runtimeName){ const destination=path.join(root,'runtimes',runtimeName);safe(destination,{directory:true,optional:true}); const incoming=path.join(stage,'runtime',runtimeName),incomingBinary=fs.readFileSync(path.join(incoming,'bin/node')); if(!fs.existsSync(destination))fs.renameSync(incoming,destination); else {safe(path.join(destination,'bin/node'));if(sha(fs.readFileSync(path.join(destination,'bin/node')))!==sha(incomingBinary))throw Error('The private Node.js runtime changed.');} installedNode=path.join(destination,'bin/node'); } const launcher=`import fs from 'node:fs';\nimport path from 'node:path';\nimport net from 'node:net';\nimport {spawn} from 'node:child_process';\nimport {fileURLToPath} from 'node:url';\nconst root=path.dirname(fileURLToPath(import.meta.url));\nconst test=process.env.Q1Z3_INSTALL_TEST==='1'&&/^\\/(?:private\\/)?tmp\\/q1z3-installer-test-[^/]+\\/install$/.test(root);\nconst port=test&&process.env.Q1Z3_INSTALL_TEST_PORT?Number(process.env.Q1Z3_INSTALL_TEST_PORT):4175;\nif(!Number.isInteger(port)||port<1024||port>65535)throw Error('Invalid loopback port.');\nconst handle=process.argv[2]||'';if(handle&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(handle)||handle&& (handle.length<3||handle.length>24))throw Error('Invalid handle.');\nconst origin='http://127.0.0.1:'+port,url=origin+'/'+(handle?'#@'+handle:'');\nconst privatePath=(file,directory=false)=>{const info=fs.lstatSync(file);if(info.isSymbolicLink()||info.uid!==process.getuid()||(info.mode&0o077)!==0||directory&&!info.isDirectory()||!directory&&(!info.isFile()||info.nlink!==1))throw Error('Unsafe local client path: '+file);};\nprivatePath(root,true);privatePath(path.join(root,'profile'),true);privatePath(path.join(root,'current'));\nconst releaseId=fs.readFileSync(path.join(root,'current'),'utf8').trim();if(!/^[a-f0-9]{64}$/.test(releaseId))throw Error('Invalid installed release.');\nconst cwd=path.join(root,'releases',releaseId);privatePath(cwd,true);\nconst status=async()=>{const response=await fetch(origin+'/api/gateway/status',{signal:AbortSignal.timeout(1500),redirect:'error'});const reader=response.body.getReader();let text='',length=0;for(;;){const chunk=await reader.read();if(chunk.done)break;length+=chunk.value.byteLength;if(length>4096){await reader.cancel();throw Error('unexpected service response');}text+=new TextDecoder().decode(chunk.value);}const body=JSON.parse(text);if(response.status!==200||body.schema!=='q1z3.gateway-status'||body.version!==1||body.local!==true||!(body.handle===null||typeof body.handle==='string'&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(body.handle)))throw Error('unrecognized service');return body;};\nconst occupied=await new Promise(resolve=>{const socket=net.connect({host:'127.0.0.1',port});socket.setTimeout(1500);socket.once('connect',()=>{socket.destroy();resolve(true);});socket.once('error',error=>resolve(error.code!=='ECONNREFUSED'));socket.once('timeout',()=>{socket.destroy();resolve(true);});});\nconst open=()=>{console.log('Open '+url);if(test)return;const command=process.platform==='darwin'?'open':'xdg-open';const opened=spawn(command,[url],{stdio:'ignore'});opened.on('error',()=>{});opened.unref();};\nif(occupied){let current;try{current=await status();}catch{console.error('Port '+port+' is already used by another service. Stop it yourself or use q1z3.com in your browser. No process or private profile was changed.');process.exit(1);}\nconsole.log('Q1Z3 is already running'+(current.handle?' for @'+current.handle:'')+'. Its process and profile were left unchanged.');if(current.handle&&handle&¤t.handle!==handle){console.log('To use @'+handle+', stop the existing client yourself, then run your installed start command.');console.log('Existing client: '+origin+'/');}else open();process.exit(0);}\nconst child=spawn(process.execPath,['gateway/server.mjs','--profile',path.join(root,'profile'),'--port',String(port)],{cwd,stdio:'inherit'});\nlet exited=false;child.once('error',error=>{console.error('Could not start Q1Z3: '+error.message);process.exit(1);});child.once('exit',code=>{exited=true;process.exit(code??1);});\nfor(const signal of ['SIGINT','SIGTERM'])process.on(signal,()=>{if(!exited)child.kill(signal);});\nlet ready=false;for(let attempt=0;attempt<100&&!exited;attempt++){try{await status();ready=true;break;}catch{}await new Promise(resolve=>setTimeout(resolve,100));}\nif(!ready){console.error('The client could not start. Your context was kept at '+path.join(root,'profile')+'.');child.kill('SIGTERM');process.exitCode=1;}else{console.log('Your context stays on this computer. Keep this Terminal open; Control-C stops the client.');console.log('Start again: '+JSON.stringify(path.join(root,'start')));console.log('AI drafting is optional; no model was downloaded.');open();}\n`; function atomic(name,content,mode=0o600){const full=path.join(root,name);safe(full,{optional:true});const temporary=path.join(root,'.write-'+randomUUID());fs.writeFileSync(temporary,content,{mode,flag:'wx'});fs.renameSync(temporary,full);} atomic('start.mjs',launcher);atomic('node-path',installedNode+'\n');atomic('node-sha256',sha(fs.readFileSync(installedNode))+'\n'); atomic('start',`#!/bin/sh\nset -eu\nq1z3_root=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)\nq1z3_node=$(cat "$q1z3_root/node-path")\nexec "$q1z3_node" "$q1z3_root/start.mjs" "$@"\n`,0o700); atomic('current',manifest.archiveSha256+'\n'); console.log('Installed at '+root+'; private context stays at '+path.join(root,'profile')+'.'); JS cleanup stage='' trap - EXIT INT TERM exec "$install_root/start" "$handle"