axstack 0.67.0 → 0.69.0

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.
Files changed (97) hide show
  1. package/README.md +2 -2
  2. package/docs/host-operations.md +3 -6
  3. package/docs/installation.md +10 -10
  4. package/docs/workflows.md +7 -11
  5. package/package.json +2 -2
  6. package/profiles/presets/claude-only.json +2 -2
  7. package/profiles/presets/codex-only.json +2 -2
  8. package/profiles/presets/mixed.json +2 -2
  9. package/skills/axstack/references/automations.md +18 -33
  10. package/skills/axstack/references/autopilot.md +1 -0
  11. package/skills/axstack/references/capture-receipts.md +22 -0
  12. package/skills/axstack/references/contracts.md +1 -1
  13. package/skills/axstack/references/lifecycle.md +1 -1
  14. package/skills/axstack/references/live-run.md +59 -0
  15. package/skills/axstack/references/local-artifacts.md +1 -1
  16. package/skills/axstack/references/pr-shape.md +13 -16
  17. package/skills/axstack/references/review-manager-prompt.md +38 -42
  18. package/skills/axstack/references/role-roster.md +1 -1
  19. package/skills/axstack/references/run-record.md +7 -5
  20. package/skills/axstack/references/test-audit-weekly.md +1 -2
  21. package/skills/axstack/references/ui-verification.md +5 -3
  22. package/skills/axstack/references/workspace-hygiene.md +3 -0
  23. package/skills/axstack/sandbox/Dockerfile +28 -0
  24. package/skills/axstack/sandbox/host-execution.md +14 -0
  25. package/skills/axstack/sandbox/inventory.json +503 -0
  26. package/skills/axstack/sandbox/launcher-capture.js +63 -0
  27. package/skills/axstack/sandbox/launcher-contract.schema.json +341 -0
  28. package/skills/axstack/sandbox/launcher-contracts.js +35 -0
  29. package/skills/axstack/sandbox/launcher-docker.js +75 -0
  30. package/skills/axstack/sandbox/launcher-host-budget.json +10 -0
  31. package/skills/axstack/sandbox/launcher-host.js +165 -0
  32. package/skills/axstack/sandbox/launcher-host.json +5 -0
  33. package/skills/axstack/sandbox/launcher-image.json +4 -0
  34. package/skills/axstack/sandbox/launcher-interface.md +7 -0
  35. package/skills/axstack/sandbox/launcher-policy.js +135 -0
  36. package/skills/axstack/sandbox/launcher-policy.json +121 -0
  37. package/skills/axstack/sandbox/launcher-runtime.js +157 -0
  38. package/skills/axstack/sandbox/launcher-source.js +72 -0
  39. package/skills/axstack/sandbox/launcher.js +106 -0
  40. package/skills/axstack/sandbox/network-address.js +39 -0
  41. package/skills/axstack/sandbox/network-firewall.js +81 -0
  42. package/skills/axstack/sandbox/network-rules.js +86 -0
  43. package/skills/axstack/sandbox/network-runtime.js +109 -0
  44. package/skills/axstack/sandbox/network.js +49 -0
  45. package/skills/axstack/sandbox/probes-android-platform.xml +17 -0
  46. package/skills/axstack/sandbox/probes-check.js +185 -0
  47. package/skills/axstack/sandbox/probes-exec.js +20 -0
  48. package/skills/axstack/sandbox/probes-image-build.js +129 -0
  49. package/skills/axstack/sandbox/probes-image-pins.json +370 -0
  50. package/skills/axstack/sandbox/probes-link-local.js +25 -0
  51. package/skills/axstack/sandbox/probes-storage.js +33 -0
  52. package/skills/axstack/sandbox/probes-udp.js +44 -0
  53. package/skills/axstack/sandbox/probes.js +239 -0
  54. package/skills/axstack/sandbox/proxy-command.js +6 -0
  55. package/skills/axstack/sandbox/proxy-config.json +9 -0
  56. package/skills/axstack/sandbox/proxy-dns.js +114 -0
  57. package/skills/axstack/sandbox/proxy-policy.js +22 -0
  58. package/skills/axstack/sandbox/proxy.js +119 -0
  59. package/skills/axstack/sandbox/reap.md +7 -0
  60. package/skills/axstack/sandbox/sidecars.json +153 -0
  61. package/skills/axstack/sandbox/storage-checks.js +39 -0
  62. package/skills/axstack/sandbox/storage-cleanup.js +49 -0
  63. package/skills/axstack/sandbox/storage-execution.js +110 -0
  64. package/skills/axstack/sandbox/storage-plan.js +78 -0
  65. package/skills/axstack/sandbox/storage-support.js +91 -0
  66. package/skills/axstack/sandbox/storage.js +75 -0
  67. package/skills/axstack/scripts/archive-evidence.js +2 -2
  68. package/skills/axstack/scripts/capture-identity.js +122 -0
  69. package/skills/axstack/scripts/check-run.js +248 -0
  70. package/skills/axstack/scripts/check-staged-file-tokens.js +6 -3
  71. package/skills/axstack/scripts/command-capture.js +81 -0
  72. package/skills/axstack/scripts/evidence-inspector.js +182 -0
  73. package/skills/axstack/scripts/git-argv.js +6 -0
  74. package/skills/axstack/scripts/image-evidence.js +183 -0
  75. package/skills/axstack/scripts/lane-owner.js +183 -0
  76. package/skills/axstack/scripts/pr-digest.js +17 -1
  77. package/skills/axstack/scripts/pr-fresh.js +139 -0
  78. package/skills/axstack/scripts/pr-shape.js +54 -29
  79. package/skills/axstack/scripts/readiness-run.js +3 -75
  80. package/skills/axstack/scripts/readiness.js +2 -2
  81. package/skills/axstack/scripts/run-init.js +13 -11
  82. package/skills/axstack/scripts/schedule-drift.js +221 -4
  83. package/skills/axstack-audit/references/record.md +1 -1
  84. package/skills/axstack-brainstorm/references/arena.md +5 -5
  85. package/skills/axstack-explain/references/inline-pages.md +8 -4
  86. package/skills/axstack-implement/SKILL.md +6 -5
  87. package/skills/axstack-review/SKILL.md +2 -3
  88. package/skills/axstack-review/references/candidate-brief.md +12 -21
  89. package/skills/axstack-review/references/codebase-brief.md +1 -0
  90. package/skills/axstack-review/references/codebase-mode.md +4 -1
  91. package/skills/axstack-review/references/codebase-report.md +2 -1
  92. package/skills/axstack-review/references/peer-mode.md +11 -12
  93. package/skills/axstack-review/references/review-candidate.md +2 -2
  94. package/skills/axstack-review/references/review-receipt.md +8 -3
  95. package/skills/axstack-verify/SKILL.md +10 -4
  96. package/skills/axstack-watch/references/proven-verification.md +3 -2
  97. package/skills/axstack-watch/references/readiness.md +56 -61
@@ -0,0 +1,185 @@
1
+ import { readlink } from 'node:fs/promises';
2
+ import { execute } from './probes-exec.js';
3
+ import { scopeLinkLocal } from './probes-link-local.js';
4
+ import { udpSnapshot, udpDenial, udpProbePort } from './probes-udp.js';
5
+
6
+ const loopback = (address) => /^127\./.test(address) || address === '::1';
7
+
8
+ /** Inspect every process returned by Docker top, including pid 1, without image tools. */
9
+ export function inspectIdentity(statuses) {
10
+ if (!statuses.length) return { status: 'unknown', evidence: ['no live process statuses'] };
11
+ let failed = false;
12
+ for (const text of statuses) {
13
+ const uid = text.match(/^Uid:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*$/m);
14
+ const caps = ['CapInh', 'CapPrm', 'CapEff', 'CapBnd', 'CapAmb'].map((field) => text.match(new RegExp(`^${field}:\\s+([a-fA-F0-9]+)\\s*$`, 'm')));
15
+ const nnp = text.match(/^NoNewPrivs:\s+([01])\s*$/m);
16
+ const seccomp = text.match(/^Seccomp:\s+([012])\s*$/m);
17
+ if (!uid || caps.some((c) => !c) || !nnp || !seccomp) return { status: 'unknown', evidence: ['missing process security fields'] };
18
+ if (uid.slice(1).some((id) => Number(id) === 0) || caps.some((c) => BigInt(`0x${c[1]}`) !== 0n) || nnp[1] !== '1' || seccomp[1] !== '2') failed = true;
19
+ }
20
+ return { status: failed ? 'fail' : 'pass', evidence: statuses };
21
+ }
22
+
23
+ /** A connected socket is reachable even if TLS/HTTP fails after connection. */
24
+ export function classifyConnection(result, target, expected) {
25
+ const unknown = () => ({ status: 'unknown', evidence: [JSON.stringify(result)] });
26
+ if (result.timedOut || result.truncated) return unknown();
27
+ // A socket to loopback in the container cannot identify a host listener.
28
+ // Prove distinct live network namespaces instead of probing the wrong endpoint.
29
+ if (loopback(target.address)) {
30
+ const { hostNetworkNamespace: host, containerNetworkNamespace: container } = result;
31
+ if (!/^net:\[\d+\]$/.test(host) || !/^net:\[\d+\]$/.test(container)) return unknown();
32
+ return { status: expected === 'deny' && host !== container ? 'pass' : 'fail', evidence: [JSON.stringify(result)] };
33
+ }
34
+ let reachable, retained = result;
35
+ if (target.service && target.protocol === 'tcp') {
36
+ let output; try { output = JSON.parse(result.stdout); } catch { return unknown(); }
37
+ if (typeof output.tcpConnected !== 'boolean' || output.tcpConnected && !output.peerAddress) return unknown();
38
+ reachable = output.tcpConnected;
39
+ } else if (target.protocol === 'icmp') {
40
+ if (![0, 1].includes(result.exitCode) && !(result.exitCode === 2 && /^ping: connect: Network is unreachable\s*$/.test(result.stderr))) return unknown();
41
+ reachable = result.exitCode === 0;
42
+ } else if (target.protocol === 'udp' || target.kind === 'dns') {
43
+ if (/status: (NOERROR|NXDOMAIN|REFUSED|SERVFAIL)/.test(result.stdout) && result.exitCode === 0) {
44
+ reachable = target.kind === 'dns' ? /ANSWER:\s*[1-9]\d*/.test(result.stdout) : true;
45
+ }
46
+ else if (target.kind === 'dns' && result.exitCode === 9 && /no servers could be reached|timed out/.test(result.stdout)) reachable = false;
47
+ else if (target.protocol === 'udp' && target.kind !== 'dns' && expected === 'deny' && (result.exitCode === 9 || result.exitCode === 0 && result.stdout.trim() === '{"udpSent":1}') &&
48
+ (result.udpNoRoute === true || result.udpDenial?.sourcePort === udpProbePort && Number.isSafeInteger(result.udpDenial.before) && result.udpDenial.after === result.udpDenial.before + 1)) reachable = false;
49
+ // Silence alone, a stale/missing counter or unrelated/noisy traffic proves nothing.
50
+ else return unknown();
51
+ } else {
52
+ let output;
53
+ try { output = JSON.parse(result.stdout); } catch { return unknown(); }
54
+ retained = { ...result, stdout: JSON.stringify({ remote_ip: output.remote_ip, http_connect: output.http_connect, http_code: output.http_code, ...(target.redirect ? { num_redirects: output.num_redirects } : {}) }) };
55
+ if (target.redirect && !(Number(output.num_redirects) >= 1)) return unknown();
56
+ if (Number(output.http_connect) === 403) reachable = false;
57
+ else if (output.remote_ip) reachable = true;
58
+ else if ([6, 7, 28].includes(result.exitCode)) reachable = false;
59
+ else return unknown();
60
+ }
61
+ return { status: reachable === (expected === 'allow') ? 'pass' : 'fail', evidence: [JSON.stringify(retained)] };
62
+ }
63
+
64
+ export function createProbeChecker({ runner = execute, readText = (path) => Bun.file(path).text(), readNamespace = readlink, readProxyConfig = () => Bun.file(new URL('./proxy-config.json', import.meta.url)).json() } = {}) {
65
+ async function liveContainer(id) {
66
+ if (!/^[a-zA-Z0-9][\w.-]*$/.test(id)) throw Error('invalid container id');
67
+ const result = await runner(['docker', 'inspect', '--type', 'container', id]);
68
+ if (result.exitCode !== 0 || result.timedOut || result.truncated) throw Error('container inspect unavailable');
69
+ const [container] = JSON.parse(result.stdout);
70
+ if (!container?.State?.Running || !Number.isSafeInteger(container.State.Pid) || container.State.Pid < 2) throw Error('container not live');
71
+ return container;
72
+ }
73
+
74
+ async function identity(id) {
75
+ const container = await liveContainer(id);
76
+ const top = await runner(['docker', 'top', id, '-eo', 'pid']);
77
+ if (top.exitCode !== 0 || top.timedOut || top.truncated) throw Error('container process enumeration unavailable');
78
+ const pids = top.stdout.trim().split('\n').slice(1).map((s) => Number(s.trim()));
79
+ if (!pids.includes(container.State.Pid) || pids.some((pid) => !Number.isSafeInteger(pid) || pid < 2)) throw Error('incomplete process enumeration');
80
+ const statuses = await Promise.all(pids.map((pid) => readText(`/proc/${pid}/status`)));
81
+ const after = await liveContainer(id);
82
+ const next = await runner(['docker', 'top', id, '-eo', 'pid']);
83
+ if (after.State.Pid !== container.State.Pid || next.exitCode !== 0 || next.stdout !== top.stdout) throw Error('process set changed during identity probe');
84
+ return inspectIdentity(statuses);
85
+ }
86
+
87
+ async function network(id, expected, target, proxyId) {
88
+ if (!['allow', 'deny'].includes(expected)) throw Error('invalid expected outcome');
89
+ const container = await liveContainer(id), pid = container.State.Pid;
90
+ const start = await readText(`/proc/${pid}/stat`);
91
+ if (loopback(target.address)) {
92
+ const [hostNetworkNamespace, containerNetworkNamespace] = await Promise.all([readNamespace('/proc/self/ns/net'), readNamespace(`/proc/${pid}/ns/net`)]);
93
+ if ((await liveContainer(id)).State.Pid !== pid) throw Error('container replaced during namespace observation');
94
+ return classifyConnection({ hostNetworkNamespace, containerNetworkNamespace }, target, expected);
95
+ }
96
+ const prefix = ['nsenter', '--target', String(pid), '--net', '--', 'setpriv', '--reuid=65534', '--regid=65534', '--clear-groups', '--bounding-set=-all', '--inh-caps=-all', '--ambient-caps=-all', '--no-new-privs', '--'];
97
+ if (['host-address', 'host-listener'].includes(target.kind) && /^fe[89ab][0-9a-f]:/i.test(target.address)) {
98
+ const scoped = await scopeLinkLocal(target, container, runner, readNamespace, prefix);
99
+ if ((await liveContainer(id)).State.Pid !== pid) throw Error('container replaced during link-local observation');
100
+ if (scoped.separated) return { status: expected === 'deny' ? 'pass' : 'fail', evidence: scoped.evidence };
101
+ target = scoped.target;
102
+ }
103
+ const udpDenied = target.protocol === 'udp' && target.kind !== 'dns' && expected === 'deny';
104
+ const noRoute = async () => {
105
+ const r = await runner([...prefix, 'ip', '-j', ...(target.address.includes(':') ? ['-6'] : ['-4']), 'route', 'get', target.address]);
106
+ return r.exitCode === 2 && !r.timedOut && !r.truncated && /RTNETLINK answers: Network is unreachable/.test(r.stderr);
107
+ };
108
+ // A disconnected namespace cannot hit a bridge's drop counter. A fresh kernel
109
+ // ENETUNREACH before and after the datagram is positive absence-of-path proof.
110
+ const routeAbsent = udpDenied && await noRoute();
111
+ const udpBefore = udpDenied && !routeAbsent ? await udpSnapshot(container, runner) : null;
112
+ let argv, resolution;
113
+ if (target.service && target.protocol === 'tcp') {
114
+ const connect = `const [hostname, port] = Bun.argv.slice(1); const timer = setTimeout(() => { console.log(JSON.stringify({tcpConnected:false,error:'timeout'})); process.exit(0); }, 2000); try { const socket = await Bun.connect({hostname,port:Number(port),socket:{data(){},error(){},close(){}}}); console.log(JSON.stringify({tcpConnected:true,peerAddress:socket.remoteAddress})); socket.terminate(); } catch(error) { console.log(JSON.stringify({tcpConnected:false,error:String(error.code)})); } finally { clearTimeout(timer); }`;
115
+ argv = [process.execPath, '--eval', connect, '--', target.address, String(target.port)];
116
+ } else if (target.protocol === 'icmp') {
117
+ argv = ['ping', '-n', '-c', '1', '-W', '2', target.address];
118
+ } else if (udpBefore) {
119
+ // send() reaches the kernel synchronously; the fresh terminal-drop counter,
120
+ // not waiting for a response, proves this single datagram was denied.
121
+ const send = `const [address, port, source] = Bun.argv.slice(1); const socket = await Bun.udpSocket({ hostname: address.includes(':') ? '::' : '0.0.0.0', port: Number(source) }); try { if (!socket.send(Buffer.alloc(12), Number(port), address)) throw Error('UDP send failed'); console.log('{"udpSent":1}'); } finally { socket.close(); }`;
122
+ argv = [process.execPath, '--eval', send, '--', target.address, String(target.port), String(udpProbePort)];
123
+ } else if (target.kind === 'dns' || target.protocol === 'udp') {
124
+ const resolver = target.kind === 'dns' ? target.id.includes('-stub:') ? '127.0.0.11' : target.id.startsWith('tailnet-dns:') ? '100.100.100.100' : (await readProxyConfig()).resolverIpv4 : target.address;
125
+ argv = ['dig', ...(udpBefore ? ['-b', `${target.address.includes(':') ? '::' : '0.0.0.0'}#${udpProbePort}`] : []), `@${resolver}`, '-p', String(target.port ?? 53), '+time=2', '+tries=1', target.protocol === 'tcp' ? '+tcp' : '+notcp', target.kind === 'dns' ? target.address : 'example.com', 'A'];
126
+ } else {
127
+ const host = target.address.includes(':') ? `[${target.address.replace('%', '%25')}]` : target.address;
128
+ argv = ['curl', '--silent', '--show-error', '--insecure', '--connect-timeout', '2', '--max-time', '4', ...(target.redirect ? ['--location', '--max-redirs', '5'] : []), '--output', '/dev/null', '--write-out', '{"remote_ip":"%{remote_ip}","http_connect":"%{http_connect}","http_code":"%{http_code}","num_redirects":"%{num_redirects}"}', '--noproxy', '*'];
129
+ if (proxyId) {
130
+ const proxy = await liveContainer(proxyId);
131
+ const peers = Object.entries(proxy.NetworkSettings.Networks).filter(([name]) => container.NetworkSettings.Networks[name]);
132
+ const address = peers[0]?.[1]?.IPAddress;
133
+ const config = await readProxyConfig();
134
+ if (!address || !Number.isInteger(config.port) || config.port < 1 || config.port > 65535) throw Error('proxy endpoint unavailable');
135
+ argv.splice(-2, 2, '--noproxy', '', '--proxy', `http://${address}:${config.port}`, '--proxytunnel');
136
+ }
137
+ if (!proxyId && !target.address.includes(':') && !/^(?:\d+\.){3}\d+$/.test(target.address)) {
138
+ const config = await readProxyConfig();
139
+ if (!/^(?:\d+\.){3}\d+$/.test(config.resolverIpv4)) throw Error('fixed public resolver unavailable');
140
+ resolution = await runner([...prefix, 'dig', `@${config.resolverIpv4}`, '+time=2', '+tries=1', '+short', target.address, 'A']);
141
+ const answers = resolution.stdout.trim().split(/\s+/).filter((address) => /^(?:\d+\.){3}\d+$/.test(address) && address.split('.').every((part) => Number(part) <= 255));
142
+ if (resolution.exitCode !== 0 || resolution.timedOut || resolution.truncated || !answers.length) return classifyConnection(resolution, { ...target, kind: 'dns', protocol: 'udp' }, expected);
143
+ argv.push('--resolve', `${target.address}:${target.port ?? 443}:${answers.join(',')}`);
144
+ }
145
+ argv.push(`${target.port === 80 ? 'http' : 'https'}://${host}:${target.port ?? 443}/`);
146
+ }
147
+ const result = { udpDenial: null, udpNoRoute: false, ...await runner([...prefix, ...argv]), ...(resolution ? { dns: resolution } : {}) };
148
+ const after = await liveContainer(id);
149
+ if (after.State.Pid !== pid || await readText(`/proc/${pid}/stat`) !== start) {
150
+ // /proc stat CPU counters may advance; compare start-time field, not all bytes.
151
+ const ticks = (text) => text.slice(text.lastIndexOf(')') + 2).split(' ')[19];
152
+ if (after.State.Pid !== pid || ticks(await readText(`/proc/${pid}/stat`)) !== ticks(start)) throw Error('container process replaced');
153
+ }
154
+ if (routeAbsent) result.udpNoRoute = await noRoute();
155
+ if (udpBefore) {
156
+ try { result.udpDenial = udpDenial(udpBefore, await udpSnapshot(await liveContainer(id), runner)); }
157
+ catch (error) { return { status: 'unknown', evidence: [JSON.stringify(result), String(error)] }; }
158
+ }
159
+ return classifyConnection(result, target, expected);
160
+ }
161
+
162
+ return { identity, network };
163
+ }
164
+
165
+ const checker = createProbeChecker();
166
+
167
+ if (import.meta.main) {
168
+ const [mode, id, expected, raw, proxyId] = Bun.argv.slice(2);
169
+ if (mode === '--help') {
170
+ console.log('Usage: bun probes-check.js identity CONTAINER | network CONTAINER allow|deny TARGET_JSON [PROXY_CONTAINER]\nTrusted synthetic probes only. Reads Docker inspect/top and /proc; starts bounded docker, nsenter, setpriv, curl/dig/ping processes; temporarily enters the container network namespace only; drops user/capabilities before sockets. Reads fresh owned UDP drop counters around reserved-source-port denial datagrams; fresh kernel no-route readback handles disconnected namespaces; silence alone stays unknown. No mounts, files, rules or containers created. No cleanup assets. Requires host root, Docker, util-linux, curl, dnsutils and iputils-ping. Outputs one pass/fail/unknown term; grants no authority. Exit 0 facts, 1 invalid input, 2 incomplete.');
171
+ } else {
172
+ let result;
173
+ try {
174
+ if (mode === 'identity') result = await checker.identity(id);
175
+ else if (mode === 'network') {
176
+ const value = JSON.parse(raw);
177
+ const target = Array.isArray(value) ? Object.fromEntries(['kind', 'address', 'port', 'protocol', 'id', 'redirect', 'service'].map((key, i) => [key, value[i]])) : value;
178
+ result = await checker.network(id, expected, target, proxyId);
179
+ }
180
+ else throw Error('invalid probe mode; use --help');
181
+ } catch (error) { result = { status: 'unknown', evidence: [String(error)] }; }
182
+ console.log(JSON.stringify(result));
183
+ if (result.status === 'unknown') process.exitCode = 2;
184
+ }
185
+ }
@@ -0,0 +1,20 @@
1
+ /** Bounded trusted command execution. No shell and no inherited host environment. */
2
+ export async function execute(argv) {
3
+ const child = Bun.spawn(argv, { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: { PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/bin', LC_ALL: 'C' }, timeout: 15000, killSignal: 'SIGKILL' });
4
+ let truncated = false;
5
+ async function read(stream) {
6
+ const chunks = []; let bytes = 0;
7
+ for await (const chunk of stream) {
8
+ bytes += chunk.length;
9
+ if (bytes > 8 * 1024 * 1024) { truncated = true; child.kill('SIGKILL'); break; }
10
+ chunks.push(chunk);
11
+ }
12
+ return Buffer.concat(chunks).toString('utf8');
13
+ }
14
+ const [stdout, stderr, exitCode] = await Promise.all([read(child.stdout), read(child.stderr), child.exited]);
15
+ return { stdout, stderr, exitCode, truncated, timedOut: child.signalCode === 'SIGKILL' };
16
+ }
17
+
18
+ export function hold(message, terms) {
19
+ return Object.assign(Error(message), { sandboxHold: true, terms });
20
+ }
@@ -0,0 +1,129 @@
1
+ import { mkdir, rm, symlink } from 'node:fs/promises';
2
+
3
+ /** Fixed image-build commands. This plan does not fetch or install anything. */
4
+ export function provisionPlan(pins) {
5
+ if (pins.platform !== 'linux/amd64' || !Array.isArray(pins.artifacts)) throw Error('unsupported pin manifest');
6
+ const ids = new Set();
7
+ return pins.artifacts.map((a) => {
8
+ if (!/^[\w.-]+$/.test(a.id) || ids.has(a.id) || !a.version || !a.source?.startsWith('https://') || !a.url?.startsWith('https://') || !/^\/opt\/[\w./-]+$/.test(a.destination) || a.destination.split('/').includes('..')) throw Error('invalid pin');
9
+ ids.add(a.id);
10
+ if (!new RegExp(`^[a-f0-9]{${{ sha1: 40, sha256: 64, sha512: 128 }[a.algorithm] ?? 0}}$`).test(a.checksum)) throw Error(`invalid checksum ${a.id}`);
11
+ if (!['sha1', 'sha256', 'sha512'].includes(a.algorithm)) throw Error(`unsupported checksum algorithm ${a.id}`);
12
+ const stage = `/tmp/axstack-image-${a.id}`, archive = `${stage}/artifact`, dest = a.destination;
13
+ const source = ['python', 'rust', 'cargo'].includes(a.kind) ? `${stage}/source` : dest;
14
+ const steps = [];
15
+ const command = (argv, cwd = '/') => steps.push({ argv, cwd });
16
+ if (['tar', 'content', 'python', 'rust', 'cargo'].includes(a.kind)) {
17
+ command(['mkdir', '-p', source]);
18
+ command(['tar', '-xf', archive, '-C', source, `--strip-components=${a.strip ?? 0}`, '--no-same-owner']);
19
+ } else if (['zip', 'android'].includes(a.kind)) {
20
+ command(['mkdir', '-p', a.kind === 'android' ? `${stage}/unpacked` : dest]);
21
+ command(['unzip', '-q', archive, '-d', a.kind === 'android' ? `${stage}/unpacked` : dest]);
22
+ if (a.kind === 'android') command(['python3', '-c', 'import pathlib,shutil,sys; p=list(pathlib.Path(sys.argv[1]).iterdir()); assert len(p)==1 and p[0].is_dir(); shutil.copytree(p[0],sys.argv[2],dirs_exist_ok=True)', `${stage}/unpacked`, dest]);
23
+ } else if (a.kind === 'file') {
24
+ command(['mkdir', '-p', dest.slice(0, dest.lastIndexOf('/'))]);
25
+ command(['cp', archive, dest]);
26
+ if (a.id === 'solc') command(['chmod', '0755', dest]);
27
+ } else throw Error(`unknown artifact recipe ${a.kind}`);
28
+ if (a.kind === 'python') {
29
+ command(['./configure', `--prefix=${dest}`, '--with-ensurepip=install'], source);
30
+ command(['make', '-j2'], source); command(['make', 'install'], source);
31
+ }
32
+ if (a.kind === 'rust') command(['./install.sh', `--prefix=${dest}`, '--without=rust-docs', '--disable-ldconfig'], source);
33
+ if (a.kind === 'cargo') command(['/opt/rust/bin/cargo', 'install', '--locked', '--path', source, '--root', dest]);
34
+ if (a.kind === 'content') {
35
+ command(['git', 'init', '-q', dest]);
36
+ command(['git', '-C', dest, '-c', 'core.autocrlf=false', 'add', '-f', '.']);
37
+ for (const link of a.gitlinks ?? []) command(['git', '-C', dest, 'update-index', '--add', '--cacheinfo', `160000,${link.sha},${link.path}`]);
38
+ command(['git', '-C', dest, 'write-tree']);
39
+ }
40
+ if (a.id === 'swift') command(['sh', '-ec', `printf 'print("Swift smoke")\\n' > ${stage}/smoke.swift; /opt/swift/usr/bin/swift --version; /opt/swift/usr/bin/swiftc ${stage}/smoke.swift -o ${stage}/smoke; ${stage}/smoke`]);
41
+ if (a.id === 'swiftlint') command(['bash', '-euc', `set -o pipefail; printf 'print("Swift smoke")\\n' > ${stage}/smoke.swift; /opt/swiftlint/swiftlint version; /opt/swiftlint/swiftlint lint --strict --no-cache --quiet ${stage}/smoke.swift 2>&1 | tee ${stage}/lint.log >&2; ! grep -q 'Skipping enabled rule' ${stage}/lint.log`]);
42
+ return { id: a.id, status: 'unknown', evidence: [a.source], stage, downloadArgv: ['curl', '--fail', '--silent', '--show-error', '--location', '--proto', '=https', '--proto-redir', '=https', '--max-time', '600', '--output', archive, a.url], verify: { path: archive, algorithm: a.algorithm, checksum: a.checksum }, steps, ...(a.tree ? { expectedTree: a.tree } : {}) };
43
+ });
44
+ }
45
+
46
+ /** Verification precedes every install command; corruption stops the build. */
47
+ export async function verifyArtifact({ path, algorithm, checksum }) {
48
+ const hash = new Bun.CryptoHasher(algorithm);
49
+ for await (const chunk of Bun.file(path).stream()) hash.update(chunk);
50
+ if (hash.digest('hex') !== checksum) throw Error(`checksum mismatch: ${path}`);
51
+ }
52
+
53
+ async function runCommand(argv, cwd = '/') {
54
+ const child = Bun.spawn(argv, { cwd, env: { ...process.env, HOME: '/tmp/axstack-image-home', CARGO_HOME: '/tmp/axstack-image-cargo', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/tmp/axstack-image-gitconfig' }, stdin: 'ignore', stdout: 'pipe', stderr: 'inherit' });
55
+ const output = await new Response(child.stdout).text();
56
+ if (await child.exited !== 0) throw Error(`build command failed: ${JSON.stringify(argv)}`);
57
+ return output.trim();
58
+ }
59
+
60
+ async function install(pins, artifactsOnly = false) {
61
+ if (process.env.AXSTACK_IMAGE_BUILD !== '1' || process.getuid() !== 0) throw Error('run only in the Dockerfile image build');
62
+ await mkdir('/tmp/axstack-image-home', { recursive: true });
63
+ await Bun.write('/tmp/axstack-image-gitconfig', '');
64
+ for (const item of provisionPlan(pins)) {
65
+ await mkdir(item.stage, { recursive: false });
66
+ await runCommand(item.downloadArgv);
67
+ await verifyArtifact(item.verify);
68
+ for (const step of item.steps) {
69
+ const result = await runCommand(step.argv, step.cwd);
70
+ if (step.argv.at(-1) === 'write-tree' && result !== item.expectedTree) throw Error(`upstream tree mismatch ${item.id}`);
71
+ }
72
+ const artifact = pins.artifacts.find((a) => a.id === item.id);
73
+ if (artifact.kind === 'content') await rm(`${artifact.destination}/.git`, { recursive: true });
74
+ await rm(item.stage, { recursive: true });
75
+ console.log(JSON.stringify({ id: item.id, status: 'pass', evidence: [artifact.source, artifact.checksum, 'installed; toolchain smoke remains required'] }));
76
+ }
77
+ const links = {
78
+ '/usr/local/bin/bun': '/opt/bun-1.4.4/bun-linux-x64/bun',
79
+ '/usr/local/bin/npm': '/opt/npm/bin/npm-cli.js', '/usr/local/bin/npx': '/opt/npm/bin/npx-cli.js',
80
+ '/usr/local/bin/pnpm': '/opt/pnpm/bin/pnpm.cjs', '/usr/local/bin/pnpx': '/opt/pnpm/bin/pnpx.cjs',
81
+ '/usr/local/bin/solc': '/opt/svm/0.8.28/solc-0.8.28',
82
+ };
83
+ for (const v of ['1.2.2', '1.3.14', '1.4.4']) links[`/usr/local/bin/bun-${v}`] = `/opt/bun-${v}/bun-linux-x64/bun`;
84
+ for (const [path, target] of Object.entries(links)) await symlink(target, path);
85
+ // npm must resolve to the frozen inventory version rather than Node's bundled copy.
86
+ for (const line of ['20', '22', '24']) for (const name of ['npm', 'npx']) {
87
+ await rm(`/opt/node-${line}/bin/${name}`);
88
+ await symlink(`/usr/local/bin/${name}`, `/opt/node-${line}/bin/${name}`);
89
+ }
90
+ await runCommand(['/opt/python-3.12/bin/python3', '-m', 'ensurepip']);
91
+ await mkdir('/opt/android/licenses', { recursive: true });
92
+ await Bun.write('/opt/android/licenses/android-sdk-license', `${pins.androidLicense.sha1}\n`);
93
+ if (artifactsOnly) {
94
+ for (const path of ['/tmp/axstack-image-home', '/tmp/axstack-image-cargo', '/tmp/axstack-image-gitconfig']) await rm(path, { recursive: true });
95
+ return;
96
+ }
97
+ await preload();
98
+ }
99
+
100
+ async function preload() {
101
+ if (process.env.AXSTACK_IMAGE_BUILD !== '1' || process.getuid() !== 0) throw Error('run only in the Dockerfile image build');
102
+ await mkdir('/tmp/axstack-image-home', { recursive: true });
103
+ await Bun.write('/tmp/axstack-image-gitconfig', '');
104
+ // Pre-resolve AGP/Kotlin's transitive build artifacts with a trusted synthetic project.
105
+ const project = '/tmp/axstack-image-gradle';
106
+ await mkdir(project);
107
+ await Bun.write(`${project}/settings.gradle.kts`, 'pluginManagement { repositories { maven { url = uri("/opt/android-maven") }; google(); mavenCentral(); gradlePluginPortal() } }\ndependencyResolutionManagement { repositories { google(); mavenCentral() } }\nrootProject.name = "sandbox-preload"\n');
108
+ await Bun.write(`${project}/gradle.properties`, 'android.builtInKotlin=false\nandroid.newDsl=false\n');
109
+ await Bun.write(`${project}/build.gradle.kts`, 'plugins { id("com.android.library") version "9.4.1"; id("org.jetbrains.kotlin.android") version "2.2.10" }\nandroid { namespace = "sandbox.preload"; compileSdk = 37; buildToolsVersion = "37.0.0"; defaultConfig { minSdk = 26 } }\n');
110
+ await runCommand(['mkdir', '-p', `${project}/src/main`]);
111
+ await Bun.write(`${project}/src/main/AndroidManifest.xml`, '<manifest xmlns:android="http://schemas.android.com/apk/res/android"/>');
112
+ await runCommand(['/opt/gradle/gradle-9.6.0/bin/gradle', '--no-daemon', '--gradle-user-home', '/opt/gradle-build-cache', 'assembleDebug'], project);
113
+ await runCommand(['mv', '/opt/gradle-build-cache', '/opt/gradle-cache']);
114
+ for (const path of [project, '/tmp/axstack-image-home', '/tmp/axstack-image-cargo', '/tmp/axstack-image-gitconfig']) await rm(path, { recursive: true });
115
+ }
116
+
117
+ if (import.meta.main) {
118
+ const mode = Bun.argv[2];
119
+ if (mode === '--help') console.log('Usage: bun probes-image-build.js --plan|--run|--artifacts|--preload|--help\n--plan: read bundled pins, print pending per-artifact terms and exact download/install argv; no writes/network. --artifacts installs verified artifacts only; --preload builds the synthetic Android project only; --run does both. Writers: Dockerfile build only (root plus AXSTACK_IMAGE_BUILD=1), downloads pinned HTTPS artifacts, verifies published checksums, installs /opt toolchains, compiles/lints Swift smokes, creates /usr/local/bin links, uses/removes fixed /tmp/axstack-image-* scratch, preloads /opt/gradle-build-cache through a trusted synthetic project (network to upstream registries), moves its read-only dependency cache to /opt/gradle-cache. Public Solidity trees checked; content scripts never run. No host config, containers, mounts, credentials, dispatch or publication. Cleanup failure stops build. Exit 0 facts, 1 error; plan terms remain unknown until build and integration smoke.');
120
+ else {
121
+ try {
122
+ const pins = await Bun.file(new URL('./probes-image-pins.json', import.meta.url)).json();
123
+ if (mode === '--plan') console.log(JSON.stringify(provisionPlan(pins), null, 2));
124
+ else if (mode === '--run' || mode === '--artifacts') await install(pins, mode === '--artifacts');
125
+ else if (mode === '--preload') await preload();
126
+ else throw Error('use --plan, --run or --help');
127
+ } catch (error) { console.error(String(error)); process.exitCode = 1; }
128
+ }
129
+ }