aptly 0.1.13 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/aptly.js +5 -2
- package/dist/src/cli-help.js +2 -2
- package/dist/src/doctor.d.ts +3 -0
- package/dist/src/doctor.js +26 -7
- package/dist/src/files.js +2 -2
- package/dist/src/setup.d.ts +1 -0
- package/dist/src/setup.js +93 -21
- package/dist/src/stable-runtime.d.ts +61 -0
- package/dist/src/stable-runtime.js +694 -0
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/docs/guide/en/configuration.md +24 -0
- package/docs/guide/ja/configuration.md +24 -0
- package/docs/guide/ko/configuration.md +24 -0
- package/docs/guide/zh-CN/configuration.md +24 -0
- package/package.json +1 -1
|
@@ -0,0 +1,694 @@
|
|
|
1
|
+
// POSIX, opt-in, immutable MCP/observer runtime snapshots. No host configuration,
|
|
2
|
+
// credential access, Node installation, lifecycle scripts, or mutable current pointer.
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readlinkSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { createRequire } from 'node:module';
|
|
7
|
+
import { basename, dirname, isAbsolute, join, parse as parsePath, relative, resolve, sep } from 'node:path';
|
|
8
|
+
import { assertNoRedirectedAncestors, readRegularFile, systemAliasAllowed } from './files.js';
|
|
9
|
+
export const stableRuntimeLimits = Object.freeze({ files: 12000, totalBytes: 128 * 1024 * 1024, fileBytes: 8 * 1024 * 1024, manifestBytes: 2 * 1024 * 1024 });
|
|
10
|
+
const plans = new WeakMap();
|
|
11
|
+
function fail(code) { throw new Error(code); }
|
|
12
|
+
const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
13
|
+
const uid = () => process.getuid?.();
|
|
14
|
+
const within = (path, root) => path === root || path.startsWith(root + sep);
|
|
15
|
+
const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
16
|
+
const exact = (v, keys) => object(v) && Object.keys(v).length === keys.length && keys.every(k => Object.hasOwn(v, k));
|
|
17
|
+
const cleanAbsolute = (v) => typeof v === 'string' && isAbsolute(v) && resolve(v) === v && !/[\x00-\x1f\x7f]/.test(v);
|
|
18
|
+
const safeRelative = (v) => typeof v === 'string' && v.length > 0 && v.length <= 1024 && !v.includes('\\') && !/[\x00-\x1f\x7f]/.test(v) && v.split('/').every(p => p && p !== '.' && p !== '..');
|
|
19
|
+
const baseFor = (home) => join(home, '.local', 'share', 'aptly', 'runtimes');
|
|
20
|
+
const identity = (path) => { const s = lstatSync(path); return [s.dev, s.ino, s.uid, s.nlink, s.mode, s.size, s.mtimeMs, s.ctimeMs].join(':'); };
|
|
21
|
+
const quote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
22
|
+
function canonicalAllowed(path) {
|
|
23
|
+
const absolute = resolve(path);
|
|
24
|
+
let current = parsePath(absolute).root;
|
|
25
|
+
for (const part of absolute.slice(current.length).split(sep).filter(Boolean)) {
|
|
26
|
+
const next = join(current, part);
|
|
27
|
+
try {
|
|
28
|
+
const stat = lstatSync(next);
|
|
29
|
+
if (stat.isSymbolicLink()) {
|
|
30
|
+
const target = readlinkSync(next);
|
|
31
|
+
if (!systemAliasAllowed(next, stat, target))
|
|
32
|
+
fail('stable_runtime_unverified');
|
|
33
|
+
current = resolve(dirname(next), target);
|
|
34
|
+
}
|
|
35
|
+
else
|
|
36
|
+
current = next;
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error.code === 'ENOENT')
|
|
40
|
+
current = next;
|
|
41
|
+
else
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return current;
|
|
46
|
+
}
|
|
47
|
+
/** Shape only. Reads OS alias metadata, never runtime bytes or credentials. */
|
|
48
|
+
export function stableReference(entry, { home = homedir() } = {}) {
|
|
49
|
+
const command = object(entry) ? entry.command : undefined;
|
|
50
|
+
if (typeof command !== 'string')
|
|
51
|
+
return null;
|
|
52
|
+
const lexicalHome = resolve(home), aliasHome = process.platform === 'darwin' ? lexicalHome.replace(/^\/(tmp|var|etc)(?=\/|$)/, '/private/$1') : lexicalHome, candidate = resolve(command);
|
|
53
|
+
if (![baseFor(lexicalHome), baseFor(aliasHome)].some(base => within(candidate, base)))
|
|
54
|
+
return null;
|
|
55
|
+
const canonicalHome = process.platform === 'win32' ? lexicalHome : canonicalAllowed(lexicalHome), bases = [baseFor(lexicalHome), baseFor(canonicalHome)], base = bases.find(base => within(candidate, base));
|
|
56
|
+
if (!base)
|
|
57
|
+
fail('stable_runtime_unverified');
|
|
58
|
+
if (!cleanAbsolute(command) || Object.hasOwn(entry, 'url') || (entry.type !== undefined && entry.type !== 'stdio') || !Array.isArray(entry.args) || entry.args.length !== 1 || entry.args[0] !== 'serve')
|
|
59
|
+
fail('stable_runtime_unverified');
|
|
60
|
+
const suffix = relative(base, candidate).split(sep);
|
|
61
|
+
if (suffix.length !== 2 || !/^[a-f0-9]{64}$/.test(suffix[0]) || suffix[1] !== 'launch')
|
|
62
|
+
fail('stable_runtime_unverified');
|
|
63
|
+
const runtimeRoot = join(baseFor(canonicalHome), suffix[0]);
|
|
64
|
+
return frozen({ command: join(runtimeRoot, 'launch'), args: ['serve'], generation: suffix[0], runtimeRoot });
|
|
65
|
+
}
|
|
66
|
+
function platform() { if (process.platform === 'win32')
|
|
67
|
+
fail('stable_launcher_platform_unsupported'); }
|
|
68
|
+
function safeAncestors(path) {
|
|
69
|
+
let current = resolve(path);
|
|
70
|
+
while (!existsSync(current)) {
|
|
71
|
+
const parent = dirname(current);
|
|
72
|
+
if (parent === current)
|
|
73
|
+
fail('stable_runtime_unverified');
|
|
74
|
+
current = parent;
|
|
75
|
+
}
|
|
76
|
+
assertNoRedirectedAncestors(current);
|
|
77
|
+
for (;;) {
|
|
78
|
+
const observed = lstatSync(current), stat = observed.isSymbolicLink() ? statSync(current) : observed;
|
|
79
|
+
const sticky = stat.isDirectory() && stat.uid === 0 && (stat.mode & 0o1000) !== 0;
|
|
80
|
+
if ((uid() !== undefined && stat.uid !== uid() && stat.uid !== 0) || ((stat.mode & 0o022) !== 0 && !sticky))
|
|
81
|
+
fail('stable_runtime_unverified');
|
|
82
|
+
const parent = dirname(current);
|
|
83
|
+
if (parent === current)
|
|
84
|
+
break;
|
|
85
|
+
current = parent;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function privatePath(path, directory) {
|
|
89
|
+
safeAncestors(path);
|
|
90
|
+
assertNoRedirectedAncestors(path);
|
|
91
|
+
const s = lstatSync(path);
|
|
92
|
+
if (s.isSymbolicLink() || (directory ? !s.isDirectory() : !s.isFile() || s.nlink !== 1) || (s.mode & 0o077) || (uid() !== undefined && s.uid !== uid()))
|
|
93
|
+
fail('stable_runtime_unverified');
|
|
94
|
+
}
|
|
95
|
+
function checkedRoot(runtimeRoot, home) {
|
|
96
|
+
const base = baseFor(home);
|
|
97
|
+
if (dirname(runtimeRoot) !== base || !/^\w{64}$/.test(basename(runtimeRoot)))
|
|
98
|
+
fail('stable_runtime_unverified');
|
|
99
|
+
safeAncestors(dirname(base));
|
|
100
|
+
for (const path of [base, runtimeRoot, join(runtimeRoot, 'payload')])
|
|
101
|
+
privatePath(path, true);
|
|
102
|
+
}
|
|
103
|
+
function readPrivate(path, maxBytes) { privatePath(path, false); return readRegularFile(path, { privateFile: true, maxBytes }); }
|
|
104
|
+
function frozen(value) { if (value && typeof value === 'object') {
|
|
105
|
+
Object.freeze(value);
|
|
106
|
+
for (const child of Object.values(value))
|
|
107
|
+
frozen(child);
|
|
108
|
+
} return value; }
|
|
109
|
+
// No interpolation from host events or secrets. The launcher checks these exact
|
|
110
|
+
// bootstrap bytes before Node execution; this is integrity, not publisher authentication.
|
|
111
|
+
const bootstrap = String.raw `'use strict';
|
|
112
|
+
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');
|
|
113
|
+
const root=__dirname,mode=process.argv[2],quiet=mode==='observe';
|
|
114
|
+
function bad(){throw Error('stable_runtime_unverified');}
|
|
115
|
+
function hash(v){return crypto.createHash('sha256').update(v).digest('hex');}
|
|
116
|
+
function privatePath(p,dir){const s=fs.lstatSync(p);if(s.isSymbolicLink()||(dir?!s.isDirectory():!s.isFile()||s.nlink!==1)||(s.mode&63)||(process.getuid&&s.uid!==process.getuid()))bad();}
|
|
117
|
+
function read(p,max){privatePath(p,false);const before=fs.lstatSync(p);const fd=fs.openSync(p,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW||0)|(fs.constants.O_NONBLOCK||0));try{const s=fs.fstatSync(fd);if(!s.isFile()||s.dev!==before.dev||s.ino!==before.ino||s.size>max||s.nlink!==1||(s.mode&63)||(process.getuid&&s.uid!==process.getuid()))bad();const buffer=Buffer.alloc(Math.min(max+1,s.size+1));let size=0;while(size<buffer.length){const count=fs.readSync(fd,buffer,size,buffer.length-size,null);if(!count)break;size+=count;}if(size>s.size||size>max)bad();privatePath(p,false);const after=fs.lstatSync(p);if(after.dev!==s.dev||after.ino!==s.ino)bad();return buffer.subarray(0,size);}finally{fs.closeSync(fd);}}
|
|
118
|
+
function safe(p){return typeof p==='string'&&p.length>0&&p.length<=1024&&!p.includes('\\')&&!/[\x00-\x1f\x7f]/.test(p)&&p.split('/').every(x=>x&&x!=='.'&&x!=='..');}
|
|
119
|
+
async function main(){
|
|
120
|
+
if(!/^v(?:2[4-9]|[3-9][0-9]|[1-9][0-9]{2,})\.\d+\.\d+$/.test(process.version))bad();
|
|
121
|
+
if(mode!=='serve'&&mode!=='observe')bad();if(mode==='serve'&&process.argv.length!==3)bad();
|
|
122
|
+
const m=JSON.parse(read(path.join(root,'manifest.json'),2097152).toString('utf8'));
|
|
123
|
+
const body={schema_version:m.schema_version,kind:m.kind,version:m.version,home:m.home,node_path:m.node_path,launcher_revision:m.launcher_revision,bootstrap_sha256:m.bootstrap_sha256,launcher_sha256:m.launcher_sha256,files:m.files};
|
|
124
|
+
if(Object.keys(m).sort().join(',')!=='bootstrap_sha256,files,generation,home,kind,launcher_revision,launcher_sha256,node_path,schema_version,version')bad();
|
|
125
|
+
if(m.schema_version!==1||m.kind!=='aptly-stable-runtime'||m.launcher_revision!==1||!Array.isArray(m.files)||m.files.length>12000||!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(m.version))bad();
|
|
126
|
+
if(root!==path.join(m.home,'.local','share','aptly','runtimes',m.generation)||hash(JSON.stringify(body))!==m.generation)bad();
|
|
127
|
+
for(const p of [path.dirname(root),root,path.join(root,'payload')])privatePath(p,true);
|
|
128
|
+
let at=root;while(true){let s=fs.lstatSync(at);if(s.isSymbolicLink()&&!((at==='/var'&&fs.readlinkSync(at)==='private/var'||at==='/tmp'&&fs.readlinkSync(at)==='private/tmp'||at==='/etc'&&fs.readlinkSync(at)==='private/etc')&&process.platform==='darwin'&&s.uid===0))bad();if(s.isSymbolicLink())s=fs.statSync(at);if((process.getuid&&s.uid!==process.getuid()&&s.uid!==0)||((s.mode&18)&&!(s.isDirectory()&&s.uid===0&&(s.mode&512))))bad();const next=path.dirname(at);if(next===at)break;at=next;}
|
|
129
|
+
if(hash(read(path.join(root,'bootstrap.cjs'),65536))!==m.bootstrap_sha256||hash(read(path.join(root,'launch'),65536))!==m.launcher_sha256)bad();
|
|
130
|
+
const expected=new Map();let total=0,previous='';for(const f of m.files){if(!f||typeof f!=='object'||Array.isArray(f)||Object.keys(f).sort().join(',')!=='path,sha256,size'||!safe(f.path)||f.path<=previous||expected.has(f.path)||!Number.isSafeInteger(f.size)||f.size<0||f.size>8388608||!/^[a-f0-9]{64}$/.test(f.sha256))bad();total+=f.size;if(total>134217728)bad();expected.set(f.path,f);previous=f.path;}
|
|
131
|
+
const directories=new Set(['']);for(const key of expected.keys()){const parts=key.split('/');parts.pop();while(parts.length){directories.add(parts.join('/'));parts.pop();}}
|
|
132
|
+
const seen=new Set();function walk(dir,rel){privatePath(dir,true);for(const name of fs.readdirSync(dir)){const file=path.join(dir,name),key=rel?rel+'/'+name:name,s=fs.lstatSync(file);if(s.isDirectory()){if(!directories.has(key))bad();walk(file,key);}else{const f=expected.get(key);if(!f||seen.has(key))bad();const bytes=read(file,8388608);if(bytes.length!==f.size||hash(bytes)!==f.sha256)bad();seen.add(key);}}}
|
|
133
|
+
walk(path.join(root,'payload'),'');if(seen.size!==expected.size)bad();
|
|
134
|
+
const pkg=JSON.parse(read(path.join(root,'payload','package.json'),65536).toString('utf8'));if(pkg.name!=='aptly'||pkg.version!==m.version||pkg.type!=='module')bad();
|
|
135
|
+
// Synchronous hooks also cover require/createRequire in this thread. This is
|
|
136
|
+
// a module-resolution boundary, not a sandbox for trusted payload programs.
|
|
137
|
+
const modules=require('node:module'),urls=require('node:url'),payload=fs.realpathSync(path.join(root,'payload'));
|
|
138
|
+
if(typeof modules.registerHooks!=='function')bad();
|
|
139
|
+
modules.registerHooks({resolve(specifier,context,nextResolve){
|
|
140
|
+
if(modules.isBuiltin(specifier))return nextResolve(specifier,context);
|
|
141
|
+
const result=nextResolve(specifier,context);if(modules.isBuiltin(result.url))return result;
|
|
142
|
+
let target;try{target=fs.realpathSync(urls.fileURLToPath(result.url));}catch{bad();}
|
|
143
|
+
const relative=path.relative(payload,target).split(path.sep).join('/');
|
|
144
|
+
if(!relative||relative.startsWith('../')||path.isAbsolute(relative)||!expected.has(relative))bad();
|
|
145
|
+
privatePath(target,false);return result;
|
|
146
|
+
}});
|
|
147
|
+
if(mode==='serve'){const server=await import(require('node:url').pathToFileURL(path.join(root,'payload','dist','src','server.js')).href);await server.serve();}
|
|
148
|
+
else{const target=path.join(root,'payload','dist','bin','aptly-observe.js');process.argv=[process.execPath,target,...process.argv.slice(3)];await import(require('node:url').pathToFileURL(target).href);}
|
|
149
|
+
}
|
|
150
|
+
main().catch(()=>{if(!quiet){process.stderr.write('aptly: stable_runtime_unavailable\n');process.exitCode=1;}});
|
|
151
|
+
`;
|
|
152
|
+
const bootstrapHash = digest(bootstrap);
|
|
153
|
+
function sourceFiles(packageRoot) {
|
|
154
|
+
const root = canonicalAllowed(packageRoot), files = [];
|
|
155
|
+
let bytes = 0;
|
|
156
|
+
try {
|
|
157
|
+
safeAncestors(root);
|
|
158
|
+
assertNoRedirectedAncestors(root);
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
fail('stable_source_unverified');
|
|
162
|
+
}
|
|
163
|
+
if (!lstatSync(root).isDirectory())
|
|
164
|
+
fail('stable_source_unverified');
|
|
165
|
+
if (readdirSync(root).some(name => name.toLowerCase() === 'binding.gyp' || name.toLowerCase().endsWith('.node') || name.toLowerCase() === 'prebuilds' && lstatSync(join(root, name)).isDirectory()))
|
|
166
|
+
fail('stable_source_unverified');
|
|
167
|
+
function add(path) {
|
|
168
|
+
if (path.toLowerCase().endsWith('.node') || basename(path).toLowerCase() === 'binding.gyp')
|
|
169
|
+
fail('stable_source_unverified');
|
|
170
|
+
const source = join(root, path);
|
|
171
|
+
assertNoRedirectedAncestors(source);
|
|
172
|
+
const s = lstatSync(source);
|
|
173
|
+
if (!s.isFile() || s.isSymbolicLink() || s.nlink !== 1 || s.size > stableRuntimeLimits.fileBytes || (s.mode & 0o022) || (uid() !== undefined && s.uid !== uid() && s.uid !== 0))
|
|
174
|
+
fail('stable_source_unverified');
|
|
175
|
+
const before = identity(source), data = readRegularFile(source, { maxBytes: stableRuntimeLimits.fileBytes });
|
|
176
|
+
if (before !== identity(source))
|
|
177
|
+
fail('stable_source_changed');
|
|
178
|
+
bytes += data.length;
|
|
179
|
+
if (bytes > stableRuntimeLimits.totalBytes || files.length >= stableRuntimeLimits.files)
|
|
180
|
+
fail('stable_runtime_limit');
|
|
181
|
+
files.push({ path, source, size: data.length, sha256: digest(data), identity: before });
|
|
182
|
+
}
|
|
183
|
+
function walk(directory, skipModules = false) {
|
|
184
|
+
const absolute = join(root, directory);
|
|
185
|
+
try {
|
|
186
|
+
safeAncestors(absolute);
|
|
187
|
+
assertNoRedirectedAncestors(absolute);
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
fail('stable_source_unverified');
|
|
191
|
+
}
|
|
192
|
+
if (!lstatSync(absolute).isDirectory())
|
|
193
|
+
fail('stable_source_unverified');
|
|
194
|
+
for (const name of readdirSync(absolute).sort()) {
|
|
195
|
+
if (name === '.bin' || name === 'node_modules' && skipModules)
|
|
196
|
+
continue;
|
|
197
|
+
if (['.git', '.npmrc', '.env', 'credentials.json', 'auth.json'].includes(name) || name.startsWith('.env.'))
|
|
198
|
+
fail('stable_source_unverified');
|
|
199
|
+
const path = directory + '/' + name;
|
|
200
|
+
if (!safeRelative(path))
|
|
201
|
+
fail('stable_source_unverified');
|
|
202
|
+
const s = lstatSync(join(root, path));
|
|
203
|
+
if (s.isSymbolicLink() || s.isDirectory() && name.toLowerCase() === 'prebuilds')
|
|
204
|
+
fail('stable_source_unverified');
|
|
205
|
+
if (s.isDirectory())
|
|
206
|
+
walk(path, skipModules);
|
|
207
|
+
else
|
|
208
|
+
add(path);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
add('package.json');
|
|
212
|
+
add('LICENSE');
|
|
213
|
+
walk('dist/src');
|
|
214
|
+
walk('dist/bin');
|
|
215
|
+
const metadata = JSON.parse(readRegularFile(join(root, 'package.json'), { maxBytes: 65536 }).toString('utf8'));
|
|
216
|
+
if (metadata.name !== 'aptly' || metadata.type !== 'module' || typeof metadata.version !== 'string' || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(metadata.version) || !existsSync(join(root, 'dist/src/server.js')) || !existsSync(join(root, 'dist/bin/aptly-observe.js')))
|
|
217
|
+
fail('stable_source_unverified');
|
|
218
|
+
const modules = join(root, 'node_modules'), seen = new Set();
|
|
219
|
+
function dependencies(current, pkg) {
|
|
220
|
+
const required = { ...(pkg.dependencies ?? {}), ...(pkg.peerDependencies ?? {}) };
|
|
221
|
+
const optional = { ...(pkg.optionalDependencies ?? {}) };
|
|
222
|
+
for (const [name, meta] of Object.entries(pkg.peerDependenciesMeta ?? {}))
|
|
223
|
+
if (object(meta) && meta.optional === true && Object.hasOwn(required, name)) {
|
|
224
|
+
optional[name] = required[name];
|
|
225
|
+
delete required[name];
|
|
226
|
+
}
|
|
227
|
+
for (const name of Object.keys(optional))
|
|
228
|
+
delete required[name];
|
|
229
|
+
const require = createRequire(join(current, 'package.json'));
|
|
230
|
+
for (const name of [...new Set([...Object.keys(required), ...Object.keys(optional)])].sort()) {
|
|
231
|
+
if (!/^(?:@[a-z0-9_.-]+\/)?[a-z0-9_.-]+$/i.test(name))
|
|
232
|
+
fail('stable_source_unverified');
|
|
233
|
+
let dependency;
|
|
234
|
+
for (const search of require.resolve.paths(name) ?? []) {
|
|
235
|
+
const possible = join(search, name);
|
|
236
|
+
if (existsSync(join(possible, 'package.json'))) {
|
|
237
|
+
dependency = resolve(possible);
|
|
238
|
+
break;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (!dependency) {
|
|
242
|
+
if (Object.hasOwn(optional, name))
|
|
243
|
+
continue;
|
|
244
|
+
fail('stable_source_unverified');
|
|
245
|
+
}
|
|
246
|
+
if (!within(dependency, modules))
|
|
247
|
+
fail('stable_source_unverified');
|
|
248
|
+
assertNoRedirectedAncestors(dependency);
|
|
249
|
+
if (seen.has(dependency))
|
|
250
|
+
continue;
|
|
251
|
+
seen.add(dependency);
|
|
252
|
+
const data = JSON.parse(readRegularFile(join(dependency, 'package.json'), { maxBytes: 65536 }).toString('utf8'));
|
|
253
|
+
if (data.name !== name)
|
|
254
|
+
fail('stable_source_unverified');
|
|
255
|
+
walk(relative(root, dependency).split(sep).join('/'), true);
|
|
256
|
+
dependencies(dependency, data);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
dependencies(root, metadata);
|
|
260
|
+
files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
261
|
+
if (new Set(files.map(f => f.path)).size !== files.length)
|
|
262
|
+
fail('stable_source_unverified');
|
|
263
|
+
return { files, version: metadata.version };
|
|
264
|
+
}
|
|
265
|
+
function manifestBody(manifest) { return { schema_version: manifest.schema_version, kind: manifest.kind, version: manifest.version, home: manifest.home, node_path: manifest.node_path, launcher_revision: manifest.launcher_revision, bootstrap_sha256: manifest.bootstrap_sha256, launcher_sha256: manifest.launcher_sha256, files: manifest.files }; }
|
|
266
|
+
function readManifest(root, home) {
|
|
267
|
+
const value = JSON.parse(readPrivate(join(root, 'manifest.json'), stableRuntimeLimits.manifestBytes).toString('utf8'));
|
|
268
|
+
if (!exact(value, ['schema_version', 'kind', 'version', 'home', 'node_path', 'launcher_revision', 'bootstrap_sha256', 'launcher_sha256', 'files', 'generation']) || value.schema_version !== 1 || value.kind !== 'aptly-stable-runtime' || value.launcher_revision !== 1 || value.home !== home || !cleanAbsolute(value.node_path) || typeof value.version !== 'string' || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(value.version) || value.bootstrap_sha256 !== bootstrapHash || !Array.isArray(value.files) || value.files.length > stableRuntimeLimits.files)
|
|
269
|
+
fail('stable_runtime_unverified');
|
|
270
|
+
const expectedLauncher = launcher(value.node_path, home);
|
|
271
|
+
if (value.launcher_sha256 !== digest(expectedLauncher) || readPrivate(join(root, 'launch'), 65536).toString('utf8') !== expectedLauncher || readPrivate(join(root, 'bootstrap.cjs'), 65536).toString('utf8') !== bootstrap || (lstatSync(join(root, 'launch')).mode & 0o100) === 0)
|
|
272
|
+
fail('stable_runtime_unverified');
|
|
273
|
+
let bytes = 0, previous = '';
|
|
274
|
+
for (const f of value.files) {
|
|
275
|
+
if (!exact(f, ['path', 'size', 'sha256']) || !safeRelative(f.path) || f.path <= previous || !Number.isSafeInteger(f.size) || f.size < 0 || f.size > stableRuntimeLimits.fileBytes || typeof f.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(f.sha256))
|
|
276
|
+
fail('stable_runtime_unverified');
|
|
277
|
+
previous = f.path;
|
|
278
|
+
bytes += f.size;
|
|
279
|
+
}
|
|
280
|
+
if (bytes > stableRuntimeLimits.totalBytes || digest(JSON.stringify(manifestBody(value))) !== value.generation || basename(root) !== value.generation)
|
|
281
|
+
fail('stable_runtime_unverified');
|
|
282
|
+
return value;
|
|
283
|
+
}
|
|
284
|
+
function validatePayload(root, manifest, metadataOnly) {
|
|
285
|
+
const expected = new Map(manifest.files.map(f => [f.path, f]));
|
|
286
|
+
const pkgBytes = readPrivate(join(root, 'payload/package.json'), 65536), entry = expected.get('package.json');
|
|
287
|
+
const pkg = JSON.parse(pkgBytes.toString('utf8'));
|
|
288
|
+
if (!entry || digest(pkgBytes) !== entry.sha256 || pkgBytes.length !== entry.size || pkg.name !== 'aptly' || pkg.version !== manifest.version || pkg.type !== 'module')
|
|
289
|
+
fail('stable_runtime_unverified');
|
|
290
|
+
if (metadataOnly)
|
|
291
|
+
return;
|
|
292
|
+
const directories = new Set(['']);
|
|
293
|
+
for (const key of expected.keys()) {
|
|
294
|
+
const parts = key.split('/');
|
|
295
|
+
parts.pop();
|
|
296
|
+
while (parts.length) {
|
|
297
|
+
directories.add(parts.join('/'));
|
|
298
|
+
parts.pop();
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
const seen = new Set();
|
|
302
|
+
function walk(directory, path) {
|
|
303
|
+
privatePath(directory, true);
|
|
304
|
+
for (const name of readdirSync(directory)) {
|
|
305
|
+
const target = join(directory, name), rel = path ? path + '/' + name : name, s = lstatSync(target);
|
|
306
|
+
if (s.isSymbolicLink())
|
|
307
|
+
fail('stable_runtime_unverified');
|
|
308
|
+
if (s.isDirectory()) {
|
|
309
|
+
if (!directories.has(rel))
|
|
310
|
+
fail('stable_runtime_unverified');
|
|
311
|
+
walk(target, rel);
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
const f = expected.get(rel);
|
|
315
|
+
if (!f || seen.has(rel))
|
|
316
|
+
fail('stable_runtime_unverified');
|
|
317
|
+
const b = readPrivate(target, stableRuntimeLimits.fileBytes);
|
|
318
|
+
if (b.length !== f.size || digest(b) !== f.sha256)
|
|
319
|
+
fail('stable_runtime_unverified');
|
|
320
|
+
seen.add(rel);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
walk(join(root, 'payload'), '');
|
|
325
|
+
if (seen.size !== expected.size)
|
|
326
|
+
fail('stable_runtime_unverified');
|
|
327
|
+
}
|
|
328
|
+
export function planStableRuntime(options) {
|
|
329
|
+
platform();
|
|
330
|
+
try {
|
|
331
|
+
const root = canonicalAllowed(options.packageRoot), home = canonicalAllowed(options.home ?? homedir()), nodePath = options.nodePath ?? process.execPath;
|
|
332
|
+
if (!cleanAbsolute(home) || !cleanAbsolute(nodePath) || !cleanAbsolute(options.packageRoot))
|
|
333
|
+
fail('stable_source_unverified');
|
|
334
|
+
// Existing parents may be absent in a dry run; never create them here.
|
|
335
|
+
safeAncestors(home);
|
|
336
|
+
let existing = baseFor(home);
|
|
337
|
+
while (!existsSync(existing)) {
|
|
338
|
+
const parent = dirname(existing);
|
|
339
|
+
if (parent === existing)
|
|
340
|
+
fail('stable_runtime_unverified');
|
|
341
|
+
existing = parent;
|
|
342
|
+
}
|
|
343
|
+
safeAncestors(existing);
|
|
344
|
+
assertNoRedirectedAncestors(existing);
|
|
345
|
+
if (existsSync(baseFor(home)))
|
|
346
|
+
privatePath(baseFor(home), true);
|
|
347
|
+
const captured = sourceFiles(root), body = { schema_version: 1, kind: 'aptly-stable-runtime', version: captured.version, home, node_path: nodePath, launcher_revision: 1, bootstrap_sha256: bootstrapHash, launcher_sha256: digest(launcher(nodePath, home)), files: captured.files.map(({ path, size, sha256 }) => ({ path, size, sha256 })) };
|
|
348
|
+
const generation = digest(JSON.stringify(body)), runtimeRoot = join(baseFor(home), generation), manifest = { ...body, generation };
|
|
349
|
+
if (Buffer.byteLength(JSON.stringify(manifest) + '\n') > stableRuntimeLimits.manifestBytes)
|
|
350
|
+
fail('stable_runtime_limit');
|
|
351
|
+
const plan = frozen({ command: join(runtimeRoot, 'launch'), args: ['serve'], packageRoot: join(runtimeRoot, 'payload'), payloadRoot: join(runtimeRoot, 'payload'), runtimeRoot, version: captured.version, generation, manifest, integrity: 'full', descriptor: { command: join(runtimeRoot, 'launch'), args: ['serve'] } });
|
|
352
|
+
if (existsSync(runtimeRoot) && !validateStableRegistration(plan.descriptor, { home }))
|
|
353
|
+
fail('stable_runtime_unverified');
|
|
354
|
+
plans.set(plan, { root, files: captured.files });
|
|
355
|
+
return plan;
|
|
356
|
+
}
|
|
357
|
+
catch (error) {
|
|
358
|
+
if (error instanceof Error && ['stable_source_changed', 'stable_runtime_limit', 'stable_runtime_unverified'].includes(error.message))
|
|
359
|
+
throw error;
|
|
360
|
+
fail('stable_source_unverified');
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
function ensureDirectory(path, privateDirectory = false) {
|
|
364
|
+
safeAncestors(path);
|
|
365
|
+
if (!existsSync(path)) {
|
|
366
|
+
const parent = dirname(path);
|
|
367
|
+
if (parent !== path)
|
|
368
|
+
ensureDirectory(parent);
|
|
369
|
+
mkdirSync(path, { mode: 0o700 });
|
|
370
|
+
}
|
|
371
|
+
assertNoRedirectedAncestors(path);
|
|
372
|
+
if (!lstatSync(path).isDirectory())
|
|
373
|
+
fail('stable_runtime_unverified');
|
|
374
|
+
if (privateDirectory)
|
|
375
|
+
privatePath(path, true);
|
|
376
|
+
}
|
|
377
|
+
function assertSource(plan, capture) {
|
|
378
|
+
const now = sourceFiles(capture.root);
|
|
379
|
+
if (now.version !== plan.version || JSON.stringify(now.files) !== JSON.stringify(capture.files))
|
|
380
|
+
fail('stable_source_changed');
|
|
381
|
+
}
|
|
382
|
+
function writeDurable(path, bytes, mode) { const fd = openSync(path, 'wx', mode); try {
|
|
383
|
+
writeFileSync(fd, bytes);
|
|
384
|
+
fsyncSync(fd);
|
|
385
|
+
}
|
|
386
|
+
finally {
|
|
387
|
+
closeSync(fd);
|
|
388
|
+
} }
|
|
389
|
+
function syncDirectory(path) { const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_DIRECTORY ?? 0)); try {
|
|
390
|
+
fsyncSync(fd);
|
|
391
|
+
}
|
|
392
|
+
finally {
|
|
393
|
+
closeSync(fd);
|
|
394
|
+
} }
|
|
395
|
+
function syncTree(path) { for (const name of readdirSync(path)) {
|
|
396
|
+
const child = join(path, name);
|
|
397
|
+
if (lstatSync(child).isDirectory())
|
|
398
|
+
syncTree(child);
|
|
399
|
+
} syncDirectory(path); }
|
|
400
|
+
export function materializeStableRuntime(plan) {
|
|
401
|
+
platform();
|
|
402
|
+
const captured = plans.get(plan);
|
|
403
|
+
if (!captured)
|
|
404
|
+
fail('stable_plan_unverified');
|
|
405
|
+
const base = dirname(plan.runtimeRoot), stage = join(base, '.aptly-runtime-stage-' + randomUUID()), lock = join(base, '.' + plan.generation + '.lock');
|
|
406
|
+
let lockFd, lockIdentity, madeStage = false;
|
|
407
|
+
try {
|
|
408
|
+
assertSource(plan, captured);
|
|
409
|
+
ensureDirectory(dirname(base));
|
|
410
|
+
ensureDirectory(base, true);
|
|
411
|
+
if (existsSync(plan.runtimeRoot)) {
|
|
412
|
+
const existing = validateStableRegistration(plan.descriptor, { home: plan.manifest.home });
|
|
413
|
+
if (!existing || existing.generation !== plan.generation)
|
|
414
|
+
fail('stable_runtime_unverified');
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
try {
|
|
418
|
+
lockFd = openSync(lock, 'wx', 0o600);
|
|
419
|
+
const held = fstatSync(lockFd);
|
|
420
|
+
lockIdentity = [held.dev, held.ino].join(':');
|
|
421
|
+
}
|
|
422
|
+
catch {
|
|
423
|
+
fail('stable_runtime_busy');
|
|
424
|
+
}
|
|
425
|
+
if (existsSync(plan.runtimeRoot)) {
|
|
426
|
+
const current = validateStableRegistration(plan.descriptor, { home: plan.manifest.home });
|
|
427
|
+
if (!current || current.generation !== plan.generation)
|
|
428
|
+
fail('stable_runtime_unverified');
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
mkdirSync(stage, { mode: 0o700 });
|
|
432
|
+
madeStage = true;
|
|
433
|
+
mkdirSync(join(stage, 'payload'), { mode: 0o700 });
|
|
434
|
+
for (const file of captured.files) {
|
|
435
|
+
const data = readRegularFile(file.source, { maxBytes: stableRuntimeLimits.fileBytes });
|
|
436
|
+
if (identity(file.source) !== file.identity || data.length !== file.size || digest(data) !== file.sha256)
|
|
437
|
+
fail('stable_source_changed');
|
|
438
|
+
const target = join(stage, 'payload', file.path);
|
|
439
|
+
ensureDirectory(dirname(target), true);
|
|
440
|
+
writeDurable(target, data, 0o600);
|
|
441
|
+
}
|
|
442
|
+
writeDurable(join(stage, 'bootstrap.cjs'), bootstrap, 0o600);
|
|
443
|
+
writeDurable(join(stage, 'launch'), launcher(plan.manifest.node_path, plan.manifest.home), 0o700);
|
|
444
|
+
writeDurable(join(stage, 'manifest.json'), JSON.stringify(plan.manifest) + '\n', 0o600);
|
|
445
|
+
validatePayload(stage, plan.manifest, false);
|
|
446
|
+
assertSource(plan, captured);
|
|
447
|
+
syncTree(stage);
|
|
448
|
+
syncDirectory(base);
|
|
449
|
+
// Private lock serializes product writers. Same-UID hostile writers remain
|
|
450
|
+
// outside the authentication boundary; no signature/OS sandbox is claimed.
|
|
451
|
+
if (existsSync(plan.runtimeRoot))
|
|
452
|
+
fail('stable_runtime_unverified');
|
|
453
|
+
renameSync(stage, plan.runtimeRoot);
|
|
454
|
+
madeStage = false;
|
|
455
|
+
syncDirectory(base);
|
|
456
|
+
if (!validateStableRegistration(plan.descriptor, { home: plan.manifest.home }))
|
|
457
|
+
fail('stable_runtime_unverified');
|
|
458
|
+
}
|
|
459
|
+
catch (error) {
|
|
460
|
+
if (error instanceof Error && ['stable_source_changed', 'stable_runtime_limit', 'stable_runtime_busy', 'stable_plan_unverified'].includes(error.message))
|
|
461
|
+
throw error;
|
|
462
|
+
fail('stable_runtime_unverified');
|
|
463
|
+
}
|
|
464
|
+
finally {
|
|
465
|
+
let cleanupFailed = false;
|
|
466
|
+
try {
|
|
467
|
+
if (madeStage)
|
|
468
|
+
rmSync(stage, { recursive: true, force: true });
|
|
469
|
+
}
|
|
470
|
+
catch {
|
|
471
|
+
cleanupFailed = true;
|
|
472
|
+
}
|
|
473
|
+
if (lockFd !== undefined) {
|
|
474
|
+
try {
|
|
475
|
+
const held = lstatSync(lock);
|
|
476
|
+
if ([held.dev, held.ino].join(':') !== lockIdentity)
|
|
477
|
+
cleanupFailed = true;
|
|
478
|
+
else
|
|
479
|
+
unlinkSync(lock);
|
|
480
|
+
}
|
|
481
|
+
catch {
|
|
482
|
+
cleanupFailed = true;
|
|
483
|
+
}
|
|
484
|
+
finally {
|
|
485
|
+
try {
|
|
486
|
+
closeSync(lockFd);
|
|
487
|
+
}
|
|
488
|
+
catch {
|
|
489
|
+
cleanupFailed = true;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
if (cleanupFailed)
|
|
494
|
+
fail('stable_runtime_unverified');
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
export function validateStableRegistration(entry, { home = homedir(), metadataOnly = false } = {}) {
|
|
498
|
+
const reference = stableReference(entry, { home });
|
|
499
|
+
if (!reference)
|
|
500
|
+
return null;
|
|
501
|
+
platform();
|
|
502
|
+
try {
|
|
503
|
+
const selectedHome = canonicalAllowed(home), { command, runtimeRoot } = reference;
|
|
504
|
+
checkedRoot(runtimeRoot, selectedHome);
|
|
505
|
+
const before = identity(join(runtimeRoot, 'manifest.json')), manifest = readManifest(runtimeRoot, selectedHome);
|
|
506
|
+
validatePayload(runtimeRoot, manifest, metadataOnly);
|
|
507
|
+
if (before !== identity(join(runtimeRoot, 'manifest.json')))
|
|
508
|
+
fail('stable_runtime_unverified');
|
|
509
|
+
return frozen({ command, args: ['serve'], packageRoot: join(runtimeRoot, 'payload'), runtimeRoot, version: manifest.version, generation: manifest.generation, manifest, integrity: metadataOnly ? 'metadata' : 'full' });
|
|
510
|
+
}
|
|
511
|
+
catch {
|
|
512
|
+
fail('stable_runtime_unverified');
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
export function stableObserverCommand(registration, client, policyPath) {
|
|
516
|
+
platform();
|
|
517
|
+
try {
|
|
518
|
+
if (!['codex', 'claude'].includes(client) || !cleanAbsolute(policyPath) || registration.integrity !== 'full')
|
|
519
|
+
fail('stable_runtime_unverified');
|
|
520
|
+
const captured = plans.get(registration);
|
|
521
|
+
if (captured)
|
|
522
|
+
assertSource(registration, captured);
|
|
523
|
+
else if (!validateStableRegistration({ command: registration.command, args: registration.args }, { home: registration.manifest.home }))
|
|
524
|
+
fail('stable_runtime_unverified');
|
|
525
|
+
return [registration.command, 'observe', '--client', client, '--policy-path', policyPath].map(quote).join(' ');
|
|
526
|
+
}
|
|
527
|
+
catch {
|
|
528
|
+
fail('stable_runtime_unverified');
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
function launcher(nodePath, home) {
|
|
532
|
+
return `#!/bin/sh
|
|
533
|
+
# Aptly immutable stable launcher v1. No login profiles or shell evaluation.
|
|
534
|
+
quiet=0
|
|
535
|
+
case "\${1-}" in observe) quiet=1;; serve) :;; *) printf '%s\\n' 'aptly: stable_runtime_unavailable' >&2; exit 1;; esac
|
|
536
|
+
stop() { if [ "$quiet" -eq 0 ]; then printf '%s\\n' 'aptly: stable_runtime_unavailable' >&2; exit 1; fi; exit 0; }
|
|
537
|
+
unset NODE_OPTIONS NODE_PATH NODE_REPL_EXTERNAL_MODULE
|
|
538
|
+
for utility in /usr/bin/env /usr/bin/uname /usr/bin/id /usr/bin/stat /usr/bin/sort /usr/bin/readlink /bin/date /bin/sleep; do
|
|
539
|
+
[ -x "$utility" ] || stop
|
|
540
|
+
done
|
|
541
|
+
case "$0" in /*/launch) root=\${0%/launch};; *) stop;; esac
|
|
542
|
+
kernel=$(/usr/bin/uname -s) || stop
|
|
543
|
+
case "$kernel" in Darwin|Linux) :;; *) stop;; esac
|
|
544
|
+
owner=$(/usr/bin/id -u) || stop
|
|
545
|
+
started=$(/bin/date +%s) || stop
|
|
546
|
+
limit=10; probe_seconds=2
|
|
547
|
+
if [ "$quiet" -eq 1 ]; then limit=3; probe_seconds=1; fi
|
|
548
|
+
budget() { now=$(/bin/date +%s) || return 1; elapsed=$((now-started)); [ "$elapsed" -ge 0 ] && [ "$elapsed" -lt "$limit" ]; }
|
|
549
|
+
stat_item() {
|
|
550
|
+
if [ "$kernel" = Darwin ]; then
|
|
551
|
+
if [ "$2" = link ]; then info=$(/usr/bin/stat -f '%u:%Mp%Lp:%l' "$1" 2>/dev/null) || return 1
|
|
552
|
+
else info=$(/usr/bin/stat -L -f '%u:%Mp%Lp:%l' "$1" 2>/dev/null) || return 1; fi
|
|
553
|
+
else
|
|
554
|
+
if [ "$2" = link ]; then info=$(/usr/bin/stat -c '%u:%a:%h' "$1" 2>/dev/null) || return 1
|
|
555
|
+
else info=$(/usr/bin/stat -L -c '%u:%a:%h' "$1" 2>/dev/null) || return 1; fi
|
|
556
|
+
fi
|
|
557
|
+
user=\${info%%:*}; rest=\${info#*:}; bits=\${rest%%:*}; links=\${rest#*:}
|
|
558
|
+
case "$bits" in ''|*[!0-7]*) return 1;; esac
|
|
559
|
+
}
|
|
560
|
+
qualify_chain() {
|
|
561
|
+
item=$1
|
|
562
|
+
while :; do
|
|
563
|
+
if [ -L "$item" ]; then
|
|
564
|
+
case "$item" in /tmp|/var|/etc)
|
|
565
|
+
[ "$kernel" = Darwin ] || return 1
|
|
566
|
+
[ "$(/usr/bin/readlink "$item")" = "private/\${item#/}" ] || return 1
|
|
567
|
+
stat_item "$item" link || return 1; [ "$user" = 0 ] || return 1;;
|
|
568
|
+
*) return 1;;
|
|
569
|
+
esac
|
|
570
|
+
fi
|
|
571
|
+
stat_item "$item" follow || return 1
|
|
572
|
+
[ "$user" = "$owner" ] || [ "$user" = 0 ] || return 1
|
|
573
|
+
if [ "$((0$bits & 022))" -ne 0 ]; then
|
|
574
|
+
[ -d "$item" ] && [ "$user" = 0 ] && [ "$((0$bits & 01000))" -ne 0 ] || return 1
|
|
575
|
+
fi
|
|
576
|
+
[ "$item" = / ] && break
|
|
577
|
+
item=\${item%/*}; [ -n "$item" ] || item=/
|
|
578
|
+
done
|
|
579
|
+
}
|
|
580
|
+
qualify_file() {
|
|
581
|
+
[ -f "$1" ] && [ -r "$1" ] || return 1
|
|
582
|
+
resolved=$1
|
|
583
|
+
if [ -L "$1" ]; then
|
|
584
|
+
[ "$2" = standard ] || return 1
|
|
585
|
+
case "$1" in /opt/homebrew/bin/node|/usr/local/bin/node|/usr/bin/node) :;; *) return 1;; esac
|
|
586
|
+
lexical=\${1%/*}; [ -n "$lexical" ] || lexical=/
|
|
587
|
+
qualify_chain "$lexical" || return 1
|
|
588
|
+
stat_item "$1" link || return 1
|
|
589
|
+
[ "$user" = "$owner" ] || [ "$user" = 0 ] || return 1
|
|
590
|
+
[ -x /usr/bin/realpath ] || return 1
|
|
591
|
+
resolved=$(/usr/bin/realpath "$1" 2>/dev/null) || return 1
|
|
592
|
+
case "$resolved" in /*) :;; *) return 1;; esac
|
|
593
|
+
[ -f "$resolved" ] && [ ! -L "$resolved" ] || return 1
|
|
594
|
+
fi
|
|
595
|
+
qualify_chain "$resolved"
|
|
596
|
+
}
|
|
597
|
+
private_file() {
|
|
598
|
+
[ -f "$1" ] && [ ! -L "$1" ] || return 1
|
|
599
|
+
qualify_file "$1" private || return 1
|
|
600
|
+
stat_item "$1" link || return 1
|
|
601
|
+
[ "$user" = "$owner" ] && [ "$((0$bits & 077))" -eq 0 ] && [ "$links" = 1 ]
|
|
602
|
+
}
|
|
603
|
+
# Reject directories/FIFOs/links and unsafe ancestry BEFORE opening hash input.
|
|
604
|
+
private_file "$root/launch" && [ -x "$root/launch" ] || stop
|
|
605
|
+
private_file "$root/bootstrap.cjs" || stop
|
|
606
|
+
if [ -x /usr/bin/sha256sum ]; then sum=$(/usr/bin/env -i PATH=/usr/bin:/bin LC_ALL=C /usr/bin/sha256sum "$root/bootstrap.cjs" 2>/dev/null) || stop
|
|
607
|
+
elif [ -x /usr/bin/shasum ]; then sum=$(/usr/bin/env -i PATH=/usr/bin:/bin LC_ALL=C /usr/bin/shasum -a 256 "$root/bootstrap.cjs" 2>/dev/null) || stop
|
|
608
|
+
else stop; fi
|
|
609
|
+
[ "\${sum%% *}" = ${quote(bootstrapHash)} ] || stop
|
|
610
|
+
count=0
|
|
611
|
+
seen=
|
|
612
|
+
try_node() {
|
|
613
|
+
candidate=$1; shift
|
|
614
|
+
budget || stop
|
|
615
|
+
case "$candidate" in /*) :;; *) return 1;; esac
|
|
616
|
+
case "$candidate" in */../*|*/./*|*//*|*/..|*/.) return 1;; esac
|
|
617
|
+
qualify_file "$candidate" standard || return 1
|
|
618
|
+
candidate=$resolved
|
|
619
|
+
[ -x "$candidate" ] || return 1
|
|
620
|
+
case "$seen" in *"|$candidate|"*) return 1;; esac
|
|
621
|
+
seen="$seen|$candidate|"
|
|
622
|
+
[ "$count" -lt 6 ] || return 1
|
|
623
|
+
budget || stop
|
|
624
|
+
count=$((count+1))
|
|
625
|
+
"$candidate" -e 'var v=process.version.match(/^v(\\d+)\\.\\d+\\.\\d+$/);process.exit(v&&Number(v[1])>=24?0:1)' </dev/null >/dev/null 2>&1 & probe=$!
|
|
626
|
+
(
|
|
627
|
+
sleeper=
|
|
628
|
+
cleanup() { trap - TERM INT HUP; child=$sleeper; if [ -z "$child" ]; then child=$(jobs -p); fi; case "$child" in ''|*[!0-9]*) exit 0;; esac; kill "$child" 2>/dev/null; wait "$child" 2>/dev/null; exit 0; }
|
|
629
|
+
trap cleanup TERM INT HUP
|
|
630
|
+
/bin/sleep "$probe_seconds" & sleeper=$!
|
|
631
|
+
wait "$sleeper" 2>/dev/null
|
|
632
|
+
trap - TERM INT HUP
|
|
633
|
+
kill -KILL "$probe" 2>/dev/null
|
|
634
|
+
) >/dev/null 2>&1 & watchdog=$!
|
|
635
|
+
wait "$probe" 2>/dev/null; status=$?
|
|
636
|
+
kill "$watchdog" 2>/dev/null; wait "$watchdog" 2>/dev/null
|
|
637
|
+
budget || stop
|
|
638
|
+
[ "$status" -eq 0 ] || return 1
|
|
639
|
+
# APTLY_OBSERVER_BEGIN
|
|
640
|
+
if [ "$quiet" -eq 1 ]; then
|
|
641
|
+
exec 3<&0 || stop
|
|
642
|
+
observer_child=
|
|
643
|
+
observer_cleanup() {
|
|
644
|
+
trap - HUP INT TERM
|
|
645
|
+
if [ -z "$observer_child" ]; then observer_child=$(jobs -p); fi
|
|
646
|
+
case "$observer_child" in ''|*[!0-9]*) exit 0;; esac
|
|
647
|
+
kill "$observer_child" 2>/dev/null
|
|
648
|
+
wait "$observer_child" 2>/dev/null
|
|
649
|
+
exit 0
|
|
650
|
+
}
|
|
651
|
+
trap observer_cleanup HUP INT TERM
|
|
652
|
+
"$candidate" --no-warnings "$root/bootstrap.cjs" "$@" <&3 3<&- >/dev/null 2>&1 & observer_child=$!
|
|
653
|
+
wait "$observer_child" 2>/dev/null
|
|
654
|
+
trap - HUP INT TERM
|
|
655
|
+
exec 3<&-
|
|
656
|
+
exit 0
|
|
657
|
+
fi
|
|
658
|
+
# APTLY_OBSERVER_END
|
|
659
|
+
exec "$candidate" --no-warnings "$root/bootstrap.cjs" "$@"
|
|
660
|
+
}
|
|
661
|
+
# APTLY_CANDIDATES_BEGIN
|
|
662
|
+
# Installer -> fixed standard -> descending stable numeric nvm -> safe PATH.
|
|
663
|
+
try_node ${quote(nodePath)} "$@"
|
|
664
|
+
try_node /opt/homebrew/bin/node "$@"
|
|
665
|
+
try_node /usr/local/bin/node "$@"
|
|
666
|
+
try_node /usr/bin/node "$@"
|
|
667
|
+
savedIFS=$IFS
|
|
668
|
+
set +f
|
|
669
|
+
nvm_nodes=$(
|
|
670
|
+
for node in ${quote(join(home, '.nvm', 'versions', 'node'))}/v*/bin/node; do
|
|
671
|
+
version=\${node%/bin/node}; version=\${version##*/v}
|
|
672
|
+
major=\${version%%.*}; rest=\${version#*.}; minor=\${rest%%.*}; patch=\${rest#*.}
|
|
673
|
+
case "$major:$minor:$patch" in (*[!0-9:]*|:*|*::*|*:) continue ;; esac
|
|
674
|
+
[ "$version" = "$major.$minor.$patch" ] || continue
|
|
675
|
+
[ "$major" -ge 24 ] 2>/dev/null || continue
|
|
676
|
+
printf '%s:%s:%s:%s\\n' "$major" "$minor" "$patch" "$node"
|
|
677
|
+
done | /usr/bin/sort -t : -k1,1nr -k2,2nr -k3,3nr
|
|
678
|
+
)
|
|
679
|
+
IFS='\n'
|
|
680
|
+
set -f
|
|
681
|
+
for record in $nvm_nodes; do candidate=\${record#*:*:*:}; try_node "$candidate" "$@"; done
|
|
682
|
+
IFS=$savedIFS
|
|
683
|
+
IFS=:
|
|
684
|
+
set -f
|
|
685
|
+
for directory in \${PATH-}; do
|
|
686
|
+
IFS=$savedIFS
|
|
687
|
+
case "$directory" in /*) try_node "$directory/node" "$@";; esac
|
|
688
|
+
IFS=:
|
|
689
|
+
done
|
|
690
|
+
IFS=$savedIFS
|
|
691
|
+
# APTLY_CANDIDATES_END
|
|
692
|
+
stop
|
|
693
|
+
`;
|
|
694
|
+
}
|