Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(sdk): the JavaScript client installs the pinned runtime from the published manifest
thinhlpgf34242fbcf5b
diff --git a/packages/agent-sdk/README.md b/packages/agent-sdk/README.mdindex 429bc3db9..638cf2882 100644--- a/packages/agent-sdk/README.md+++ b/packages/agent-sdk/README.md@@ -17,10 +17,45 @@ process serving many addressable sessions.npm install @janhq/agent-sdk```-The runtime binary is separate: `jan` must be on `PATH`, or named by-`process.env.JAN_BIN` (the `bin` option overrides both). A package that ships-the runtime is the distribution half of the same protocol; until then, build it-with `make agent` in the Jan repository.+The runtime binary is separate, and there are three ways to have one: on `PATH`,+named by `process.env.JAN_BIN` (the `bin` option overrides both), or installed by+this package from the channel Jan publishes. That channel is a manifest naming,+per platform, the artifact and its SHA-256, so an install is reproducible rather+than whatever the URL serves today:++```js+import { JanRuntime, installRuntime } from '@janhq/agent-sdk'++const runtime = await installRuntime() // downloaded once, then cached+const jan = await JanRuntime.start({ bin: runtime.bin })+```++`installRuntime()` maps this platform to its artifact (`darwin-universal`,+`linux-x86_64`, `linux-aarch64`, `windows-x86_64`, `windows-aarch64`), verifies+the published digest before extracting anything, and only then renames the+install into `JAN_AGENT_HOME` or the per-user cache directory. An install that+failed its digest, or that was interrupted mid-extract, is never visible as one:+`findRuntime()` answers `null` for it.++`version` and `sha256` pin. Both are checked against the manifest, and a+mismatch is an error rather than a substitution, so a run that has to reproduce+is never quietly moved to a newer runtime. `manifestUrl` names another channel;+the default is the nightly one. The macOS artifact is notarized, and getting a+runtime this way needs no Rust toolchain and no Jan Desktop.++```js+const pinned = await installRuntime({ version: '0.8.4-50' }) // must be what the manifest publishes+const found = await findRuntime({ version: '0.8.4-50' }) // reads the cache, no network+```++The nightly channel also publishes a shell installer, which is what the+[jan.ai SDK pages](https://jan.ai/docs/agent/sdk) use:++```bash+curl -fsSL https://delta.jan.ai/jan-cli/install-jan-agent.sh | bash+```++To build your own instead, `make agent` in the Jan repository.## Quickstartdiff --git a/packages/agent-sdk/package.json b/packages/agent-sdk/package.jsonindex c11ae6b4a..3b75d50b9 100644--- a/packages/agent-sdk/package.json+++ b/packages/agent-sdk/package.json@@ -31,7 +31,7 @@"scripts": {"generate": "node scripts/generate.mjs","check-types": "node scripts/generate.mjs --check && tsc -p tsconfig.json",- "test": "node --test tests/sdk.test.mjs"+ "test": "node --test tests/sdk.test.mjs tests/install.test.mjs"},"devDependencies": {"@types/node": "^22.10.0",diff --git a/packages/agent-sdk/src/index.d.ts b/packages/agent-sdk/src/index.d.tsindex aba687cfe..9ba4a5a0e 100644--- a/packages/agent-sdk/src/index.d.ts+++ b/packages/agent-sdk/src/index.d.ts@@ -242,3 +242,64 @@ export declare class JanRuntime {request<M extends RpcMethod>(method: M, params?: RpcParams<M>, options?: { timeoutMs?: number }): Promise<RpcResponses[M]>close(options?: { force?: boolean }): Promise<{ code: number | null; signal: string | null }>}++/** Where a runtime could not be installed: no artifact for this platform, a+ * manifest that does not name what was asked for, a digest that does not match,+ * or an archive that holds no binary. */+export declare class JanInstallError extends Error {+ constructor(+ message: string,+ options?: { url?: string; expected?: string; actual?: string; platform?: string },+ )+ readonly url?: string+ readonly expected?: string+ readonly actual?: string+ readonly platform?: string+}++/** An installed runtime and what it was installed from. */+export interface InstalledRuntime {+ version: string+ pubDate: string | null+ platform: string+ url: string+ sha256: string+ installedAt: string+ /** Absolute path to the runtime binary, for `JanRuntime.start({ bin })`. */+ bin: string+ dir: string+ root: string+ /** True when the install was already on disk and nothing was downloaded. */+ cached: boolean+}++export interface InstallRuntimeOptions {+ /** Pin: the manifest must publish exactly this version. */+ version?: string+ /** Pin: the manifest's digest for this platform must be exactly this. */+ sha256?: string+ /** The channel's manifest. Defaults to `JAN_AGENT_MANIFEST` or the published one. */+ manifestUrl?: string+ /** Where runtimes live. Defaults to `JAN_AGENT_HOME` or the per-user cache. */+ root?: string+ /** The `fetch` to use, for a caller with its own proxy or instrumentation. */+ fetch?: typeof globalThis.fetch+ signal?: AbortSignal+ /** `total` is 0 when the server sends no `content-length`. */+ onProgress?: (received: number, total: number) => void+}++/** The channel the runtime is published on today. */+export declare const MANIFEST_URL: string+/** Every platform key the current manifest publishes. */+export declare const PLATFORM_KEYS: readonly string[]+/** The manifest key for a Node platform/arch pair; throws for an unsupported one. */+export declare function platformKey(platform?: string, arch?: string): string+/** The binary's name inside an installed runtime. */+export declare function binName(platform?: string): string+/** Where installed runtimes live: `JAN_AGENT_HOME`, or the per-user cache. */+export declare function runtimeRoot(env?: Record<string, string | undefined>): string+/** An already-installed runtime for `version`, or `null`. No network. */+export declare function findRuntime(options?: { version?: string; root?: string }): Promise<InstalledRuntime | null>+/** Install the runtime for this platform and return its binary path. */+export declare function installRuntime(options?: InstallRuntimeOptions): Promise<InstalledRuntime>diff --git a/packages/agent-sdk/src/index.js b/packages/agent-sdk/src/index.jsindex b94fff1fc..9754c682a 100644--- a/packages/agent-sdk/src/index.js+++ b/packages/agent-sdk/src/index.js@@ -20,6 +20,20 @@ import { createInterface } from 'node:readline'import { EVENT_TAGS, PROTOCOL_VERSION } from './generated/rpc-types.js'+// Fetching the runtime this client spawns is its own concern - the manifest, the+// digest, the platform table - so it lives in its own module and is re-exported+// here as the package's one entry point.+export {+ JanInstallError,+ MANIFEST_URL,+ PLATFORM_KEYS,+ binName,+ findRuntime,+ installRuntime,+ platformKey,+ runtimeRoot,+} from './install.js'+const require = createRequire(import.meta.url)const { version: SDK_VERSION } = require('../package.json')diff --git a/packages/agent-sdk/src/install.js b/packages/agent-sdk/src/install.jsnew file mode 100644index 000000000..b0bd49e62--- /dev/null+++ b/packages/agent-sdk/src/install.js@@ -0,0 +1,343 @@+// Installing a pinned Jan runtime, without a Rust toolchain and without Jan+// Desktop.+//+// The SDK spawns and owns a `jan` process, and where that process comes from is+// the caller's business: a PATH install, a build of their own, or this - the+// runtime Jan publishes, downloaded for this platform and checked against the+// digest the manifest carries.+//+// The manifest is the only source of truth, deliberately. It names, per+// platform, the artifact and its SHA-256; an install therefore reproduces the+// bytes that were advertised rather than whatever the URL serves today. A+// caller who names a `version` or a `sha256` is pinning: the install fails+// closed when the published manifest has moved on, which is the same rule the+// protocol applies to a session's model.+//+// An install is atomic: everything happens in a staging directory that is+// renamed into place only after the digest matches and the binary is there, so+// an interrupted or corrupt install never leaves something that looks usable.++import { spawn } from 'node:child_process'+import { createHash } from 'node:crypto'+import { createWriteStream } from 'node:fs'+import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'+import { homedir } from 'node:os'+import { basename, dirname, join, resolve, sep } from 'node:path'+import { Readable } from 'node:stream'+import { pipeline } from 'node:stream/promises'++// The channel the runtime is published on today. A release channel is the same+// shape at another URL, which is why the URL is an argument and this is only a+// default.+export const MANIFEST_URL = 'https://delta.jan.ai/agent-nightly/manifest.json'++// Every platform key the current manifest publishes. macOS is one universal+// artifact, so both of its architectures map to `darwin-universal`.+export const PLATFORM_KEYS = Object.freeze([+ 'darwin-universal',+ 'linux-x86_64',+ 'linux-aarch64',+ 'windows-x86_64',+ 'windows-aarch64',+])++// Where a runtime could not be installed: no artifact for this platform, a+// manifest that does not name what was asked for, a digest that does not match,+// or an archive that does not hold a binary. Distinct from+// [`JanRuntimeError`](./index.js), which is a runtime that will not run - this+// is a runtime that could not be fetched.+export class JanInstallError extends Error {+ constructor(message, { url, expected, actual, platform } = {}) {+ super(message)+ this.name = 'JanInstallError'+ this.url = url+ this.expected = expected+ this.actual = actual+ this.platform = platform+ }+}++// The manifest key for a Node platform/arch pair. Throws rather than guessing:+// an artifact for another architecture extracts fine and then fails at exec.+export function platformKey(platform = process.platform, arch = process.arch) {+ if (platform === 'darwin') return 'darwin-universal'+ if (platform === 'linux' && arch === 'x64') return 'linux-x86_64'+ if (platform === 'linux' && arch === 'arm64') return 'linux-aarch64'+ if (platform === 'win32' && arch === 'x64') return 'windows-x86_64'+ if (platform === 'win32' && arch === 'arm64') return 'windows-aarch64'+ throw new JanInstallError(+ `the Jan runtime publishes no artifact for ${platform}/${arch}; it publishes ${PLATFORM_KEYS.join(', ')}`,+ { platform: `${platform}/${arch}` },+ )+}++// Where installed runtimes live: `JAN_AGENT_HOME` when set, otherwise the+// per-user cache directory each OS already has a convention for.+export function runtimeRoot(env = process.env) {+ if (env.JAN_AGENT_HOME) return env.JAN_AGENT_HOME+ const home = homedir()+ if (process.platform === 'win32') {+ return join(env.LOCALAPPDATA ?? join(home, 'AppData', 'Local'), 'jan-agent', 'runtimes')+ }+ if (process.platform === 'darwin') return join(home, 'Library', 'Caches', 'jan-agent', 'runtimes')+ return join(env.XDG_CACHE_HOME ?? join(home, '.cache'), 'jan-agent', 'runtimes')+}++// The binary's name inside an installed runtime.+export function binName(platform = platformKey()) {+ return platform.startsWith('windows-') ? 'jan.exe' : 'jan'+}++function installDir(root, version, platform) {+ return join(root, version, platform)+}++// An installed runtime for `version`, read from the marker an install writes.+// No network: a caller who already has one pays nothing to find it, and a+// missing one answers `null` rather than throwing.+export async function findRuntime({ version, root = runtimeRoot() } = {}) {+ if (!version) return null+ const platform = platformKey()+ const dir = installDir(root, version, platform)+ let marker+ try {+ marker = JSON.parse(await readFile(join(dir, 'install.json'), 'utf8'))+ } catch {+ return null+ }+ const bin = join(dir, binName(platform))+ try {+ await stat(bin)+ } catch {+ // A marker whose binary is gone is not an install: it is the remains of one.+ return null+ }+ return { ...marker, bin, dir, root, cached: true }+}++// Install the runtime for this platform and return the path to its binary.+//+// `manifestUrl` names the channel (default: the one above). `version` and+// `sha256` pin: either is checked against the manifest and a mismatch is an+// error, never a silent fallback. `onProgress(received, total)` reports the+// download; `total` is 0 when the server sends no length.+export async function installRuntime(options = {}) {+ const {+ version,+ sha256,+ manifestUrl = process.env.JAN_AGENT_MANIFEST ?? MANIFEST_URL,+ root = runtimeRoot(),+ fetch: fetchImpl = globalThis.fetch,+ signal,+ onProgress,+ } = options++ const platform = platformKey()+ if (version) {+ const hit = await findRuntime({ version, root })+ if (hit && (!sha256 || hit.sha256 === sha256)) return hit+ }++ const manifest = await readManifest(manifestUrl, fetchImpl, signal)+ if (version && manifest.version !== version) {+ throw new JanInstallError(+ `the manifest at ${manifestUrl} publishes ${manifest.version}, not ${version}: ` ++ 'point `manifestUrl` at the manifest that names the version you are pinning, or drop it',+ { url: manifestUrl },+ )+ }+ const entry = manifest.platforms?.[platform]+ if (!entry?.url || !entry?.sha256) {+ throw new JanInstallError(+ `the manifest at ${manifestUrl} (version ${manifest.version}) has no entry for ${platform}`,+ { url: manifestUrl, platform },+ )+ }+ if (sha256 && sha256 !== entry.sha256) {+ throw new JanInstallError(+ `the manifest publishes ${entry.sha256} for ${platform}, not the ${sha256} this install pins`,+ { url: entry.url, expected: sha256, actual: entry.sha256, platform },+ )+ }++ const dir = installDir(root, manifest.version, platform)+ // An install of the version the manifest names, whose digest is still the one+ // the manifest publishes, is the artifact this call would fetch. A channel+ // that republished the same version with different bytes fails this check and+ // is downloaded again, which is the point of recording the digest.+ const existing = await findRuntime({ version: manifest.version, root })+ if (existing && existing.sha256 === entry.sha256) return existing++ const stage = join(root, manifest.version, `.${platform}.part-${process.pid}-${Date.now().toString(36)}`)+ await mkdir(stage, { recursive: true })+ try {+ const archive = join(stage, basename(new URL(entry.url).pathname) || 'jan-runtime')+ const actual = await download(entry.url, archive, { fetchImpl, onProgress, signal })+ if (actual !== entry.sha256) {+ throw new JanInstallError(+ `the artifact downloaded from ${entry.url} hashes to ${actual}, not the ${entry.sha256} the manifest publishes`,+ { url: entry.url, expected: entry.sha256, actual, platform },+ )+ }+ await extract(archive, stage)+ await rm(archive, { force: true })++ const name = binName(platform)+ const bin = join(stage, name)+ try {+ await stat(bin)+ } catch {+ throw new JanInstallError(+ `the ${platform} archive from ${entry.url} holds no ${name} at its root`,+ { url: entry.url, platform },+ )+ }+ if (process.platform !== 'win32') await chmod(bin, 0o755)++ const installedAt = new Date().toISOString()+ await writeFile(+ join(stage, 'install.json'),+ `${JSON.stringify(+ {+ version: manifest.version,+ pubDate: manifest.pub_date ?? null,+ platform,+ url: entry.url,+ sha256: actual,+ bin: name,+ installedAt,+ },+ null,+ 2,+ )}\n`,+ )++ // Renamed into place last, and only now: until this line the install is+ // invisible to every other process, and a crash anywhere above leaves no+ // directory that `findRuntime` would trust. A rename that finds a directory+ // already there is either a concurrent install of the same artifact or what+ // an older one left behind; both are replaced, but only after asking.+ await mkdir(dirname(dir), { recursive: true })+ try {+ await rename(stage, dir)+ } catch (error) {+ if (error.code !== 'ENOTEMPTY' && error.code !== 'EEXIST' && error.code !== 'ENOTDIR') throw error+ await rm(dir, { recursive: true, force: true })+ await rename(stage, dir)+ }+ return {+ version: manifest.version,+ pubDate: manifest.pub_date ?? null,+ platform,+ url: entry.url,+ sha256: actual,+ installedAt,+ bin: join(dir, name),+ dir,+ root,+ cached: false,+ }+ } catch (error) {+ await rm(stage, { recursive: true, force: true })+ throw error+ }+}++async function readManifest(url, fetchImpl, signal) {+ let response+ try {+ response = await fetchImpl(url, { signal, headers: { accept: 'application/json' } })+ } catch (error) {+ throw new JanInstallError(`could not read the runtime manifest at ${url}: ${error.message}`, { url })+ }+ if (!response.ok) {+ throw new JanInstallError(`the runtime manifest at ${url} answered ${response.status}`, { url })+ }+ let manifest+ try {+ manifest = await response.json()+ } catch (error) {+ throw new JanInstallError(`the runtime manifest at ${url} is not JSON: ${error.message}`, { url })+ }+ if (!manifest?.version || typeof manifest.platforms !== 'object' || manifest.platforms === null) {+ throw new JanInstallError(`the runtime manifest at ${url} names no version and no platforms`, { url })+ }+ return manifest+}++// Stream the artifact to `target`, hashing as it arrives, and answer the digest.+// Nothing is kept if the transfer fails: the caller stages inside a directory it+// removes on any error.+async function download(url, target, { fetchImpl, onProgress, signal }) {+ const response = await fetchImpl(url, { signal })+ if (!response.ok) {+ throw new JanInstallError(`the artifact at ${url} answered ${response.status}`, { url })+ }+ if (!response.body) {+ throw new JanInstallError(`the artifact at ${url} arrived with no body`, { url })+ }+ const total = Number(response.headers?.get?.('content-length') ?? 0)+ const hash = createHash('sha256')+ let received = 0+ async function* counted(source) {+ for await (const chunk of source) {+ hash.update(chunk)+ received += chunk.length+ onProgress?.(received, total)+ yield chunk+ }+ }+ await pipeline(Readable.fromWeb(response.body), counted, createWriteStream(target))+ return hash.digest('hex')+}++// The archives are a tarball on macOS and Linux and a zip on Windows. The+// system `tar` reads both (GNU tar on Linux, bsdtar on macOS and on the Windows+// that ships with it), which is one code path and no dependency.+//+// Members are listed and checked before anything is extracted: an archive whose+// entries would land outside the staging directory is refused, not followed.+// Current `tar` implementations refuse those members themselves (GNU tar strips+// a leading `/` and warns, bsdtar errors on `..`), so this is the policy stated+// in one place rather than left to whichever `tar` is on PATH - a digest proves+// the artifact is the one published, which is a promise about the channel and+// not about the archive's layout.+async function extract(archive, into) {+ const listing = await run('tar', ['-tf', archive], archive, 'read')+ for (const name of listing.split('\n').filter((line) => line.length > 0)) {+ const resolved = resolve(into, name)+ if (resolved !== into && !resolved.startsWith(into + sep)) {+ throw new JanInstallError(+ `${basename(archive)} holds a member outside the install directory (${name}); refusing to extract it`,+ { url: archive },+ )+ }+ }+ await run('tar', ['-xf', archive, '-C', into], archive, 'extract')+}++async function run(command, args, archive, action) {+ return await new Promise((resolve_, reject) => {+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] })+ let stdout = ''+ let stderr = ''+ child.stdout.on('data', (chunk) => {+ stdout = (stdout + chunk).slice(-1 << 20)+ })+ child.stderr.on('data', (chunk) => {+ stderr = (stderr + chunk).slice(-2048)+ })+ child.once('error', (error) => {+ reject(+ new JanInstallError(+ `could not ${action} ${basename(archive)}: ${error.message} (a \`tar\` on PATH is required to install a runtime)`,+ { url: archive },+ ),+ )+ })+ child.once('exit', (code) => {+ if (code === 0) resolve_(stdout)+ else reject(new JanInstallError(`could not ${action} ${basename(archive)}: tar exited ${code}${stderr ? `: ${stderr.trim()}` : ''}`, { url: archive }))+ })+ })+}diff --git a/packages/agent-sdk/tests/install.test.mjs b/packages/agent-sdk/tests/install.test.mjsnew file mode 100644index 000000000..917f158fe--- /dev/null+++ b/packages/agent-sdk/tests/install.test.mjs@@ -0,0 +1,291 @@+// Installing a runtime, against a manifest this test serves itself.+//+// Nothing here touches the network: an HTTP server on loopback publishes a+// manifest and a tarball this test builds with the same `tar` the installer+// uses, so the whole path - manifest, platform key, download, digest, extract,+// rename - runs for real. What is faked is only the channel.++import assert from 'node:assert/strict'+import { createServer } from 'node:http'+import { createHash } from 'node:crypto'+import { execFileSync } from 'node:child_process'+import { readdirSync } from 'node:fs'+import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import test from 'node:test'++import {+ JanInstallError,+ PLATFORM_KEYS,+ binName,+ findRuntime,+ installRuntime,+ platformKey,+ runtimeRoot,+} from '../src/index.js'++const VERSION = '0.0.0-test'++// A tarball holding a `jan` that is executable and does nothing. The installer+// only has to put a binary there; whether it runs is the runtime's business.+async function makeArchive(dir) {+ const staged = join(dir, 'staged')+ await mkdir(staged, { recursive: true })+ const name = binName()+ await writeFile(join(staged, name), `#!/bin/sh\necho ${VERSION}\n`)+ const archive = join(dir, 'jan-runtime.tar.gz')+ execFileSync('tar', ['-czf', archive, '-C', staged, name])+ return archive+}++function sha256(bytes) {+ return createHash('sha256').update(bytes).digest('hex')+}++// A channel: `/manifest.json` and the artifact, counted so a cached install can+// be proved to have downloaded nothing.+async function channel({ archive, version = VERSION, digest, omitPlatform = false }) {+ const bytes = await readFile(archive)+ const entry = { url: '', sha256: digest ?? sha256(bytes) }+ const requests = []+ const server = createServer((req, res) => {+ requests.push(req.url)+ if (req.url === '/manifest.json') {+ entry.url = `http://127.0.0.1:${server.address().port}/jan-runtime.tar.gz`+ const platforms = { [platformKey()]: entry }+ if (omitPlatform) delete platforms[platformKey()]+ res.writeHead(200, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ version, pub_date: '2026-01-01T00:00:00.000Z', platforms }))+ return+ }+ res.writeHead(200, { 'content-type': 'application/gzip', 'content-length': bytes.length })+ res.end(bytes)+ })+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))+ return {+ url: `http://127.0.0.1:${server.address().port}/manifest.json`,+ requests,+ close: () => new Promise((resolve) => server.close(resolve)),+ artifacts: () => requests.filter((path) => path !== '/manifest.json').length,+ }+}++test('a platform maps to the artifact the manifest publishes for it', () => {+ assert.equal(platformKey('darwin', 'arm64'), 'darwin-universal')+ assert.equal(platformKey('darwin', 'x64'), 'darwin-universal')+ assert.equal(platformKey('linux', 'x64'), 'linux-x86_64')+ assert.equal(platformKey('linux', 'arm64'), 'linux-aarch64')+ assert.equal(platformKey('win32', 'x64'), 'windows-x86_64')+ assert.equal(platformKey('win32', 'arm64'), 'windows-aarch64')+ assert.throws(() => platformKey('sunos', 'sparc'), (error) => {+ assert.ok(error instanceof JanInstallError)+ assert.match(error.message, /sunos\/sparc/)+ assert.match(error.message, /darwin-universal/)+ return true+ })+ for (const key of PLATFORM_KEYS) assert.match(binName(key), /^jan(\.exe)?$/)+})++test('an install lands a verified, executable binary and is cached after that', async () => {+ const root = await mkdtemp(join(tmpdir(), 'jan-install-'))+ const source = await mkdtemp(join(tmpdir(), 'jan-install-src-'))+ const archive = await makeArchive(source)+ const published = await channel({ archive })+ try {+ const progress = []+ const installed = await installRuntime({+ manifestUrl: published.url,+ root,+ onProgress: (received, total) => progress.push([received, total]),+ })++ assert.equal(installed.version, VERSION)+ assert.equal(installed.platform, platformKey())+ assert.equal(installed.cached, false)+ // The digest is the archive's, which is what the manifest pins and what a+ // caller recomputes from the published artifact.+ assert.equal(installed.sha256, sha256(await readFile(archive)))+ assert.equal((await stat(installed.bin)).mode & 0o111, 0o111, 'the binary is executable')+ assert.ok(progress.length > 0, 'progress was reported')+ assert.equal(progress.at(-1)[0], progress.at(-1)[1])++ // The marker is what makes it findable without the network, and what the+ // next install reads instead of downloading again.+ const found = await findRuntime({ version: VERSION, root })+ assert.equal(found.bin, installed.bin)+ assert.equal(found.cached, true)+ assert.equal(found.sha256, installed.sha256)++ const before = published.requests.length+ const again = await installRuntime({ version: VERSION, manifestUrl: published.url, root })+ assert.equal(again.cached, true)+ assert.equal(published.requests.length, before, `a cached install fetches nothing: ${published.requests}`)+ assert.equal(published.artifacts(), 1, 'the artifact was downloaded once')++ // Pinned to what the manifest publishes, an install is a cache read.+ const pinned = await installRuntime({ version: VERSION, sha256: found.sha256, manifestUrl: published.url, root })+ assert.equal(pinned.cached, true)++ // And so is one that pins nothing: the manifest names the version already+ // installed, with the digest it was installed under.+ const unpinned = await installRuntime({ manifestUrl: published.url, root })+ assert.equal(unpinned.cached, true)+ assert.equal(unpinned.version, VERSION)+ assert.equal(published.artifacts(), 1, 'still one download for the whole test')+ } finally {+ await published.close()+ await rm(root, { recursive: true, force: true })+ await rm(source, { recursive: true, force: true })+ }+})++test('a digest that does not match is an error, and leaves nothing behind', async () => {+ const root = await mkdtemp(join(tmpdir(), 'jan-install-bad-'))+ const source = await mkdtemp(join(tmpdir(), 'jan-install-bad-src-'))+ const published = await channel({ archive: await makeArchive(source), digest: 'f'.repeat(64) })+ try {+ await assert.rejects(+ installRuntime({ manifestUrl: published.url, root }),+ (error) => {+ assert.ok(error instanceof JanInstallError)+ assert.equal(error.expected, 'f'.repeat(64))+ assert.notEqual(error.actual, error.expected)+ assert.match(error.message, /hashes to/)+ return true+ },+ )+ assert.equal(await findRuntime({ version: VERSION, root }), null)+ // No staging directory survives: a listing of the version directory, if it+ // exists at all, holds no platform directory.+ const versions = await readFile(join(root, VERSION, platformKey()), 'utf8').then(+ () => 'present',+ () => 'absent',+ )+ assert.equal(versions, 'absent')+ } finally {+ await published.close()+ await rm(root, { recursive: true, force: true })+ await rm(source, { recursive: true, force: true })+ }+})++test('a version or digest that the manifest does not publish is refused, not substituted', async () => {+ const root = await mkdtemp(join(tmpdir(), 'jan-install-pin-'))+ const source = await mkdtemp(join(tmpdir(), 'jan-install-pin-src-'))+ const published = await channel({ archive: await makeArchive(source) })+ try {+ await assert.rejects(+ installRuntime({ version: '0.0.0-other', manifestUrl: published.url, root }),+ (error) => {+ assert.ok(error instanceof JanInstallError)+ assert.match(error.message, /publishes 0\.0\.0-test, not 0\.0\.0-other/)+ return true+ },+ )+ await assert.rejects(+ installRuntime({ sha256: 'a'.repeat(64), manifestUrl: published.url, root }),+ (error) => {+ assert.ok(error instanceof JanInstallError)+ assert.match(error.message, /not the a{64} this install pins/)+ return true+ },+ )+ assert.equal(published.artifacts(), 0, 'nothing was downloaded for a refused pin')+ } finally {+ await published.close()+ await rm(root, { recursive: true, force: true })+ await rm(source, { recursive: true, force: true })+ }+})++test('a manifest without this platform is an error naming what it has', async () => {+ const root = await mkdtemp(join(tmpdir(), 'jan-install-missing-'))+ const source = await mkdtemp(join(tmpdir(), 'jan-install-missing-src-'))+ const published = await channel({ archive: await makeArchive(source), omitPlatform: true })+ try {+ await assert.rejects(installRuntime({ manifestUrl: published.url, root }), (error) => {+ assert.ok(error instanceof JanInstallError)+ assert.match(error.message, new RegExp(`no entry for ${platformKey()}`))+ assert.equal(error.platform, platformKey())+ return true+ })+ } finally {+ await published.close()+ await rm(root, { recursive: true, force: true })+ await rm(source, { recursive: true, force: true })+ }+})++test('a channel that republishes a version under a new digest installs again', async () => {+ const root = await mkdtemp(join(tmpdir(), 'jan-install-repub-'))+ const source = await mkdtemp(join(tmpdir(), 'jan-install-repub-src-'))+ const first = await channel({ archive: await makeArchive(source) })+ try {+ const installed = await installRuntime({ manifestUrl: first.url, root })+ assert.equal(installed.cached, false)++ // Same version, different bytes: the recorded digest is what tells the two+ // apart, so this is a re-install rather than a cache hit.+ const rebuilt = join(source, 'second')+ await mkdir(rebuilt, { recursive: true })+ const second = await channel({ archive: await makeArchive(rebuilt) })+ try {+ const again = await installRuntime({ manifestUrl: second.url, root })+ assert.equal(again.version, VERSION)+ assert.equal(again.cached, false, 'a republished digest is not the install on disk')+ assert.notEqual(again.sha256, installed.sha256)+ assert.equal(again.sha256, sha256(await readFile(join(rebuilt, 'jan-runtime.tar.gz'))))+ } finally {+ await second.close()+ }+ } finally {+ await first.close()+ await rm(root, { recursive: true, force: true })+ await rm(source, { recursive: true, force: true })+ }+})++test('an archive that names a member outside the staging directory is refused', async () => {+ const root = await mkdtemp(join(tmpdir(), 'jan-install-escape-'))+ const source = await mkdtemp(join(tmpdir(), 'jan-install-escape-src-'))+ // An absolute member: `tar -P` stores the path as given, which is the shape a+ // hostile channel would use. The listing is checked before anything is+ // extracted, so the install is refused rather than written outside the root.+ const outside = join(source, 'outside')+ await writeFile(outside, 'x')+ const archive = join(source, 'jan-runtime.tar.gz')+ execFileSync('tar', ['-czPf', archive, outside])+ const published = await channel({ archive })+ try {+ await assert.rejects(installRuntime({ manifestUrl: published.url, root }), (error) => {+ assert.ok(error instanceof JanInstallError)+ assert.match(error.message, /member outside the install directory/)+ return true+ })+ assert.equal(await findRuntime({ version: VERSION, root }), null)+ assert.equal(readdirSync(join(root, VERSION)).length, 0, 'nothing is left staged')+ } finally {+ await published.close()+ await rm(root, { recursive: true, force: true })+ await rm(source, { recursive: true, force: true })+ }+})++test('the runtime root follows JAN_AGENT_HOME, and a marker without a binary is not an install', async () => {+ const root = await mkdtemp(join(tmpdir(), 'jan-install-root-'))+ try {+ assert.equal(runtimeRoot({ JAN_AGENT_HOME: root }), root)+ assert.notEqual(runtimeRoot({}), root)+ assert.match(runtimeRoot({}), /jan-agent[\\/]runtimes$/)++ // A directory that looks installed but holds no binary answers `null`: a+ // half-removed install must not be reported as usable.+ const dir = join(root, VERSION, platformKey())+ await mkdir(dir, { recursive: true })+ await writeFile(join(dir, 'install.json'), JSON.stringify({ version: VERSION, bin: binName() }))+ assert.equal(await findRuntime({ version: VERSION, root }), null)+ } finally {+ await rm(root, { recursive: true, force: true })+ }+})