axstack 0.67.0 → 0.68.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 (85) hide show
  1. package/README.md +2 -2
  2. package/docs/host-operations.md +3 -6
  3. package/docs/installation.md +8 -8
  4. package/docs/workflows.md +5 -9
  5. package/package.json +2 -2
  6. package/skills/axstack/references/automations.md +3 -14
  7. package/skills/axstack/references/autopilot.md +1 -0
  8. package/skills/axstack/references/capture-receipts.md +22 -0
  9. package/skills/axstack/references/lifecycle.md +1 -1
  10. package/skills/axstack/references/live-run.md +59 -0
  11. package/skills/axstack/references/pr-shape.md +13 -16
  12. package/skills/axstack/references/review-manager-prompt.md +21 -19
  13. package/skills/axstack/references/run-record.md +2 -2
  14. package/skills/axstack/references/test-audit-weekly.md +1 -2
  15. package/skills/axstack/references/ui-verification.md +5 -3
  16. package/skills/axstack/references/workspace-hygiene.md +3 -0
  17. package/skills/axstack/sandbox/Dockerfile +28 -0
  18. package/skills/axstack/sandbox/host-execution.md +14 -0
  19. package/skills/axstack/sandbox/inventory.json +503 -0
  20. package/skills/axstack/sandbox/launcher-capture.js +63 -0
  21. package/skills/axstack/sandbox/launcher-contract.schema.json +341 -0
  22. package/skills/axstack/sandbox/launcher-contracts.js +35 -0
  23. package/skills/axstack/sandbox/launcher-docker.js +75 -0
  24. package/skills/axstack/sandbox/launcher-host-budget.json +10 -0
  25. package/skills/axstack/sandbox/launcher-host.js +165 -0
  26. package/skills/axstack/sandbox/launcher-host.json +5 -0
  27. package/skills/axstack/sandbox/launcher-image.json +4 -0
  28. package/skills/axstack/sandbox/launcher-interface.md +7 -0
  29. package/skills/axstack/sandbox/launcher-policy.js +135 -0
  30. package/skills/axstack/sandbox/launcher-policy.json +121 -0
  31. package/skills/axstack/sandbox/launcher-runtime.js +157 -0
  32. package/skills/axstack/sandbox/launcher-source.js +72 -0
  33. package/skills/axstack/sandbox/launcher.js +106 -0
  34. package/skills/axstack/sandbox/network-address.js +39 -0
  35. package/skills/axstack/sandbox/network-firewall.js +81 -0
  36. package/skills/axstack/sandbox/network-rules.js +86 -0
  37. package/skills/axstack/sandbox/network-runtime.js +109 -0
  38. package/skills/axstack/sandbox/network.js +49 -0
  39. package/skills/axstack/sandbox/probes-android-platform.xml +17 -0
  40. package/skills/axstack/sandbox/probes-check.js +185 -0
  41. package/skills/axstack/sandbox/probes-exec.js +20 -0
  42. package/skills/axstack/sandbox/probes-image-build.js +129 -0
  43. package/skills/axstack/sandbox/probes-image-pins.json +370 -0
  44. package/skills/axstack/sandbox/probes-link-local.js +25 -0
  45. package/skills/axstack/sandbox/probes-storage.js +33 -0
  46. package/skills/axstack/sandbox/probes-udp.js +44 -0
  47. package/skills/axstack/sandbox/probes.js +239 -0
  48. package/skills/axstack/sandbox/proxy-command.js +6 -0
  49. package/skills/axstack/sandbox/proxy-config.json +9 -0
  50. package/skills/axstack/sandbox/proxy-dns.js +114 -0
  51. package/skills/axstack/sandbox/proxy-policy.js +22 -0
  52. package/skills/axstack/sandbox/proxy.js +119 -0
  53. package/skills/axstack/sandbox/reap.md +7 -0
  54. package/skills/axstack/sandbox/sidecars.json +153 -0
  55. package/skills/axstack/sandbox/storage-checks.js +39 -0
  56. package/skills/axstack/sandbox/storage-cleanup.js +49 -0
  57. package/skills/axstack/sandbox/storage-execution.js +110 -0
  58. package/skills/axstack/sandbox/storage-plan.js +78 -0
  59. package/skills/axstack/sandbox/storage-support.js +91 -0
  60. package/skills/axstack/sandbox/storage.js +75 -0
  61. package/skills/axstack/scripts/archive-evidence.js +2 -2
  62. package/skills/axstack/scripts/capture-identity.js +122 -0
  63. package/skills/axstack/scripts/check-run.js +248 -0
  64. package/skills/axstack/scripts/check-staged-file-tokens.js +6 -3
  65. package/skills/axstack/scripts/command-capture.js +81 -0
  66. package/skills/axstack/scripts/evidence-inspector.js +182 -0
  67. package/skills/axstack/scripts/git-argv.js +6 -0
  68. package/skills/axstack/scripts/image-evidence.js +183 -0
  69. package/skills/axstack/scripts/pr-shape.js +54 -29
  70. package/skills/axstack/scripts/readiness-run.js +3 -75
  71. package/skills/axstack/scripts/readiness.js +2 -2
  72. package/skills/axstack/scripts/run-init.js +13 -11
  73. package/skills/axstack/scripts/schedule-drift.js +5 -3
  74. package/skills/axstack-audit/references/record.md +1 -1
  75. package/skills/axstack-explain/references/inline-pages.md +8 -4
  76. package/skills/axstack-implement/SKILL.md +6 -5
  77. package/skills/axstack-review/references/candidate-brief.md +12 -21
  78. package/skills/axstack-review/references/codebase-brief.md +1 -0
  79. package/skills/axstack-review/references/codebase-mode.md +4 -1
  80. package/skills/axstack-review/references/codebase-report.md +2 -1
  81. package/skills/axstack-review/references/review-candidate.md +2 -2
  82. package/skills/axstack-review/references/review-receipt.md +8 -3
  83. package/skills/axstack-verify/SKILL.md +10 -4
  84. package/skills/axstack-watch/references/proven-verification.md +3 -2
  85. package/skills/axstack-watch/references/readiness.md +56 -61
@@ -0,0 +1,72 @@
1
+ import { chmodSync, mkdirSync, symlinkSync, writeFileSync } from 'node:fs';
2
+ import { gitArgv } from '../scripts/git-argv.js';
3
+ import { hold, safePath } from './launcher-policy.js';
4
+
5
+ const excluded = new Set(['.git', 'node_modules', '.venv', 'venv', '__pycache__', '.gradle', '.pnpm-store']);
6
+ export async function exportSource(p, execute) {
7
+ const root = safePath(p.sourceExport.path);
8
+ const git = async (...args) => {
9
+ const r = await execute(gitArgv('-C', p.request.repo, ...args), { maxBytes: p.policy.sourceMaxBytes });
10
+ if (r.exitCode !== 0) hold(`source export Git failure: ${args[0]}`);
11
+ return r.stdout;
12
+ };
13
+ const listing = await git('ls-tree', '-rz', '--full-tree', p.request.head);
14
+ const base = await git('ls-tree', '-rz', '--full-tree', p.request.base);
15
+ const parse = text => String(text).split('\0').filter(Boolean).map(line => {
16
+ const match = /^(\d{6}) (blob|commit) ([a-f0-9]{40,64})\t([\s\S]+)$/.exec(line);
17
+ if (!match) hold('unsupported Git source entry');
18
+ const [, mode, type, sha, path] = match;
19
+ if (path.startsWith('/') || path.split('/').some(x => !x || x === '.' || x === '..') || /[\0\r\n]/.test(path)) hold('unsafe tracked path');
20
+ return { mode, type, sha, path };
21
+ });
22
+ const entries = parse(listing), baseLinks = new Map(parse(base).filter(e => e.mode === '160000').map(e => [e.path, e.sha]));
23
+ for (const e of entries.filter(e => e.mode === '160000')) if (baseLinks.get(e.path) !== e.sha) hold(`changed/private submodule limitation: ${e.path}`);
24
+ for (const e of entries) if (e.mode === '160000') baseLinks.delete(e.path);
25
+ if (baseLinks.size) hold('removed/changed submodule limitation');
26
+ const selected = entries.filter(e => e.mode !== '160000' && !e.path.split('/').some(x => excluded.has(x)));
27
+ const links = new Map(), blobs = [], directories = new Set();
28
+ let bytes = 4096;
29
+ for (const e of selected) {
30
+ if (!['100644', '100755', '120000'].includes(e.mode) || e.type !== 'blob') hold(`special tracked entry: ${e.path}`);
31
+ const r = await execute(gitArgv('-C', p.request.repo, 'cat-file', 'blob', e.sha), { maxBytes: p.policy.sourceMaxBytes, binary: true });
32
+ if (r.exitCode !== 0) hold(`source blob unavailable: ${e.path}`);
33
+ const data = typeof r.stdout === 'string' ? new TextEncoder().encode(r.stdout) : r.stdout;
34
+ if (new TextDecoder().decode(data.subarray(0, 100)).startsWith('version https://git-lfs.github.com/spec/v1')) hold(`LFS object not fetched on host: ${e.path}`);
35
+ const parts = e.path.split('/'); parts.pop();
36
+ while (parts.length) { directories.add(parts.join('/')); parts.pop(); }
37
+ bytes += Math.max(4096, Math.ceil(data.length / 4096) * 4096);
38
+ if (bytes + directories.size * 4096 > p.sourceExport.maxBytes) hold('host source export cap exceeded');
39
+ if (e.mode === '120000') {
40
+ const target = new TextDecoder('utf-8', { fatal: true }).decode(data);
41
+ if (!target || target.startsWith('/') || target.includes('\0')) hold(`unsafe symlink: ${e.path}`);
42
+ links.set(e.path, target);
43
+ }
44
+ blobs.push({ ...e, data });
45
+ }
46
+ // Resolve symlink chains lexically; never follow any host filesystem link.
47
+ for (const [path, target] of links) {
48
+ const pending = [...path.split('/').slice(0, -1), ...target.split('/')], resolved = [];
49
+ let hops = 0;
50
+ while (pending.length) {
51
+ const part = pending.shift();
52
+ if (!part || part === '.') continue;
53
+ if (part === '..') {
54
+ if (!resolved.length) hold('source symlink escapes export');
55
+ resolved.pop(); continue;
56
+ }
57
+ resolved.push(part);
58
+ const link = resolved.join('/');
59
+ if (links.has(link)) {
60
+ if (++hops > 40) hold('source symlink cycle');
61
+ resolved.pop(); pending.unshift(...links.get(link).split('/'));
62
+ }
63
+ }
64
+ }
65
+ // Git trees cannot contain a symlink as the parent of another tracked path.
66
+ mkdirSync(root, { mode: 0o755 });
67
+ for (const dir of [...directories].sort((a, b) => a.split('/').length - b.split('/').length)) mkdirSync(`${root}/${dir}`, { mode: 0o755 });
68
+ for (const e of blobs) {
69
+ if (e.mode === '120000') symlinkSync(links.get(e.path), `${root}/${e.path}`);
70
+ else { writeFileSync(`${root}/${e.path}`, e.data, { flag: 'wx', mode: e.mode === '100755' ? 0o555 : 0o444 }); chmodSync(`${root}/${e.path}`, e.mode === '100755' ? 0o555 : 0o444); }
71
+ }
72
+ }
@@ -0,0 +1,106 @@
1
+ import * as network from './network.js';
2
+ import * as storage from './storage.js';
3
+ import * as probes from './probes.js';
4
+ import { buildPlan } from './launcher-policy.js';
5
+ import { reapRuns, runPlan } from './launcher-runtime.js';
6
+ import * as hostIO from './launcher-host.js';
7
+ import { dockerObservers } from './launcher-docker.js';
8
+ import { exportSource } from './launcher-source.js';
9
+ import { recordCapture, saveReceipt } from './launcher-capture.js';
10
+
11
+ const dependencies = { ...network, ...storage, ...probes, ...hostIO,
12
+ ...dockerObservers(hostIO.execute), liveness: hostIO.processState,
13
+ exportSource: p => exportSource(p, hostIO.execute), recordCapture, saveReceipt };
14
+
15
+ /**
16
+ * B owns launcher*. Planning is stateless and allowed on any host; run/reap are
17
+ * axat-vps-only. Assets/facts are trusted launcher observations, never PR inputs.
18
+ * @param {import('./launcher-contracts.js').PlanInput} input
19
+ * @returns {import('./launcher-contracts.js').Plan} Exact argv, rules, storage, probes and caps; terms may hold execution.
20
+ * @throws {Error} Invalid input; sandboxHold:true for incomplete/unsafe prerequisites.
21
+ */
22
+ export function plan(input) { return buildPlan(input, { ...network, ...storage, ...probes }); }
23
+
24
+ /**
25
+ * Revalidate identity/policy/caps and perform fresh enumeration + probes before PR code.
26
+ * Host W3-1 capture owns receipt/log writes outside all untrusted writable roots.
27
+ * @param {{plan:import('./launcher-contracts.js').Plan, evidenceDir:string}} input
28
+ * @returns {Promise<import('./launcher-contracts.js').Receipt>}
29
+ * @throws {Error} sandboxHold:true on any failed/unknown gate or cleanup uncertainty.
30
+ */
31
+ export async function run(input) { return runPlan(input, dependencies); }
32
+
33
+ /**
34
+ * Reap only labelled non-live runs. Unreadable PID/start/boot identity holds;
35
+ * already-removed objects succeed. Never remove a rule before its containers.
36
+ * @param {{assets:import('./launcher-contracts.js').Assets, host:import('./launcher-contracts.js').HostFacts}} input
37
+ * @returns {Promise<import('./launcher-contracts.js').Term[]>} Per-resource cleanup facts, no aggregate verdict.
38
+ * @throws {Error} sandboxHold:true on wrong host, unreadable liveness or leftover owned state.
39
+ */
40
+ export async function reap(input) { return reapRuns(input, dependencies); }
41
+
42
+ // Private injection seam: package tests supply the frozen C/D/E interfaces.
43
+ export function createLauncher(dependencies) {
44
+ return { plan: input => buildPlan(input, dependencies), run: input => runPlan(input, dependencies), reap: input => reapRuns(input, dependencies) };
45
+ }
46
+
47
+ export const help = `Usage: bun launcher.js plan --input FILE
48
+ bun launcher.js run --input FILE --evidence-dir DIR
49
+ bun launcher.js reap
50
+ bun launcher.js --help
51
+ Plan prints exact Docker argv and every packet-filter rule without mutations.
52
+ Run/reap require hostname axat-vps AND the packaged SHA-256 of trimmed /etc/machine-id.
53
+ Owned directory: /var/lib/axstack/sandbox; image file and labelled Docker volume:
54
+ exact paths/names in plan.storage.imageFile and plan.storage.volumeName;
55
+ loop device: observed /dev/loopN, bound to that image file.
56
+ Host admission uses flock plus a short-lived Bun stdin helper (no daemon/timer).
57
+ It writes admission.lock, <runId>/plan.json and <runId>/source under the owned directory.
58
+ Evidence requires a fresh owned 0700 --evidence-dir on the budgeted filesystem:
59
+ <runId>-plan.json,
60
+ W3-1 capture .log/.json files and <runId>-sandbox.json, bounded by packaged caps.
61
+ Run creates tracked-only source exports, capped ext4 storage, containers, networks,
62
+ scoped axstack_sandbox packet-filter rules, host capture logs and receipt files.
63
+ Pinned sidecars get a fixed 10-second startup grace inside the wall-time.
64
+ Run checks fresh per-run containment probes before PR commands; no reused results.
65
+ Reap removes only non-live labelled runs: containers before rules, volume before
66
+ matching loop detach/readback and image deletion. No unrelated state is pruned.
67
+ The owned inet axstack_sandbox table and input/forward chains persist after cleanup.
68
+ Writable /work tmpfs permits execution; /tmp and declared data tmpfs use noexec.
69
+ PID liveness uses /proc/<pid>/stat field 22 start ticks and the kernel boot ID;
70
+ unreadable records hold: the owning driver must resolve them before another run.
71
+ Host wall-time covers every container (proxy and sidecars included): 900 seconds,
72
+ 10 seconds grace, fixed maximum 910 seconds. Caller timeout MUST exceed 910 seconds.
73
+ SIGTERM, SIGINT and SIGHUP attempt best-effort cleanup. SIGKILL can leave bounded
74
+ objects until the next successful run/reap; a hung live launcher is not reaped.
75
+ Exit codes for run/reap: 0 facts/success (child exit recorded separately),
76
+ 1 invalid input/I/O, exit 2 containment, identity, capacity or cleanup hold.
77
+ Residual risks: shared kernel escape, opaque allowlisted HTTPS tunnels and no
78
+ upper bound on orphan lifetime if later reaping passes are missed or held.
79
+ `;
80
+
81
+ export async function cli(args) {
82
+ if (args.length === 1 && args[0] === '--help') { console.log(help); return 0; }
83
+ const [mode, ...rest] = args;
84
+ if (!['plan', 'run', 'reap'].includes(mode)) throw Error('expected plan, run or reap; see --help');
85
+ const flags = {};
86
+ for (let i = 0; i < rest.length; i += 2) {
87
+ const key = rest[i];
88
+ if (!['--input', '--evidence-dir'].includes(key) || !rest[i + 1] || key in flags) throw Error('invalid option; see --help');
89
+ flags[key] = rest[i + 1];
90
+ }
91
+ if (mode === 'reap') {
92
+ if (rest.length) throw Error('reap accepts no options');
93
+ const assets = await hostIO.loadAssets();
94
+ console.log(JSON.stringify(await reap({ assets, host: await hostIO.observeHost(assets) }), null, 2));
95
+ return 0;
96
+ }
97
+ if (!flags['--input'] || (mode === 'run') !== Boolean(flags['--evidence-dir'])) throw Error('invalid options; see --help');
98
+ const input = await Bun.file(flags['--input']).json();
99
+ const result = mode === 'plan' ? plan(input) : await run({ plan: input, evidenceDir: flags['--evidence-dir'] });
100
+ console.log(JSON.stringify(result, null, 2));
101
+ return 0;
102
+ }
103
+ if (import.meta.main) {
104
+ try { process.exitCode = await cli(process.argv.slice(2)); }
105
+ catch (error) { console.error(error.message); process.exitCode = error.sandboxHold ? 2 : 1; }
106
+ }
@@ -0,0 +1,39 @@
1
+ // Shared destination classification: never treat mapped/transition IPv6 as public.
2
+ export const deniedV4 = ['0.0.0.0/8', '10.0.0.0/8', '100.64.0.0/10', '127.0.0.0/8', '169.254.0.0/16', '172.16.0.0/12', '192.0.0.0/24', '192.0.2.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24', '203.0.113.0/24', '224.0.0.0/4', '240.0.0.0/4'];
3
+ export const deniedV6 = ['2001::/23', '2001:db8::/32', '2002::/16', '3fff::/20'];
4
+
5
+ export function ipAddress(address) {
6
+ if (typeof address !== 'string' || address.includes('%') || address.includes('/')) throw Error('Invalid IP address');
7
+ if (/^(0|[1-9]\d{0,2})(\.(0|[1-9]\d{0,2})){3}$/.test(address)) {
8
+ const bytes = address.split('.').map(Number);
9
+ if (bytes.some(b => b > 255)) throw Error('Invalid IP address');
10
+ return { version: 4, text: address, value: bytes.reduce((v, b) => (v << 8n) | BigInt(b), 0n) };
11
+ }
12
+ if (!/^[0-9a-fA-F:.]+$/.test(address) || !address.includes(':')) throw Error('Invalid IP address');
13
+ let text;
14
+ try { text = new URL(`http://[${address}]/`).hostname.slice(1, -1); } catch { throw Error('Invalid IP address'); }
15
+ const halves = text.split('::');
16
+ const left = halves[0] ? halves[0].split(':') : [];
17
+ const right = halves[1] ? halves[1].split(':') : [];
18
+ const words = halves.length === 2 ? [...left, ...Array(8 - left.length - right.length).fill('0'), ...right] : left;
19
+ if (words.length !== 8) throw Error('Invalid IP address');
20
+ return { version: 6, text, value: words.reduce((v, w) => (v << 16n) | BigInt(`0x${w}`), 0n) };
21
+ }
22
+
23
+ export function inSubnet(address, cidr) {
24
+ const ip = ipAddress(address);
25
+ const [base, bits] = cidr.split('/');
26
+ const network = ipAddress(base);
27
+ const shift = BigInt((ip.version === 4 ? 32 : 128) - Number(bits));
28
+ return ip.version === network.version && ip.value >> shift === network.value >> shift;
29
+ }
30
+
31
+ export function publicDestination(address, hostAddresses = []) {
32
+ try {
33
+ const ip = ipAddress(address);
34
+ if (hostAddresses.some(a => { const host = ipAddress(a); return ip.version === host.version && ip.value === host.value; })) return false;
35
+ return ip.version === 4
36
+ ? !deniedV4.some(cidr => inSubnet(address, cidr))
37
+ : inSubnet(address, '2000::/3') && !deniedV6.some(cidr => inSubnet(address, cidr));
38
+ } catch { return false; }
39
+ }
@@ -0,0 +1,81 @@
1
+ export const hold = message => Object.assign(Error(message), { sandboxHold: true });
2
+
3
+ export async function commandRunner(argv) {
4
+ const child = Bun.spawn(argv, { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', timeout: 15000, killSignal: 'SIGKILL', env: { PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', LANG: 'C' } });
5
+ const [exitCode, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]);
6
+ return { exitCode, stdout, stderr };
7
+ }
8
+
9
+ export function createFirewall({ runner = commandRunner } = {}) {
10
+ async function readTable() {
11
+ const result = await runner(['nft', '-j', 'list', 'table', 'inet', 'axstack_sandbox']);
12
+ if (result.exitCode !== 0) throw hold(`Cannot read sandbox firewall: ${result.stderr}`);
13
+ try { const data = JSON.parse(result.stdout); if (!Array.isArray(data.nftables)) throw Error(); return data.nftables; }
14
+ catch { throw hold('Malformed firewall readback'); }
15
+ }
16
+ async function matches(wanted) {
17
+ return (await readTable()).filter(item => item.rule?.chain === wanted.chain && item.rule?.comment === wanted.comment).map(item => item.rule);
18
+ }
19
+ // nft set ordering and object key ordering are not semantically significant.
20
+ const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object'
21
+ ? Object.fromEntries(Object.keys(value).sort().map(key => [key, key === 'counter' && (value[key] === null || Number.isSafeInteger(value[key]?.packets) && Number.isSafeInteger(value[key]?.bytes)) ? null : key === 'set' && Array.isArray(value[key]) ? value[key].map(canonical).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))) : canonical(value[key])])) : value;
22
+ const equal = (a, b) => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
23
+ async function check(wanted, { allowAbsent = false } = {}) {
24
+ const found = await matches(wanted);
25
+ return allowAbsent && found.length === 0 || found.length === 1 && equal(found[0].expr, wanted.expr);
26
+ }
27
+ async function remove(wanted) {
28
+ const found = await matches(wanted);
29
+ if (found.some(rule => !equal(rule.expr, wanted.expr))) throw hold(`Changed firewall rule ${wanted.comment}`);
30
+ for (const rule of found) {
31
+ if (!Number.isSafeInteger(rule.handle) || rule.handle <= 0) throw hold('Missing rule handle');
32
+ const result = await runner(['nft', 'delete', 'rule', 'inet', 'axstack_sandbox', wanted.chain, 'handle', String(rule.handle)]);
33
+ // Another reaper may have removed this exact object. Readback decides.
34
+ if (result.exitCode !== 0 && (await matches(wanted)).length) throw hold(`Rule deletion failed: ${wanted.comment}`);
35
+ }
36
+ if ((await matches(wanted)).length) throw hold(`Rule remains: ${wanted.comment}`);
37
+ return true;
38
+ }
39
+ async function ensureTable() {
40
+ const listed = await runner(['nft', '-j', 'list', 'tables']);
41
+ if (listed.exitCode !== 0) throw hold('Cannot enumerate firewall tables');
42
+ let tables;
43
+ try { tables = JSON.parse(listed.stdout).nftables; if (!Array.isArray(tables)) throw Error(); } catch { throw hold('Malformed table enumeration'); }
44
+ if (!tables.some(item => item.table?.family === 'inet' && item.table?.name === 'axstack_sandbox')) {
45
+ await runner(['nft', 'add', 'table', 'inet', 'axstack_sandbox']);
46
+ }
47
+ for (const name of ['input', 'forward']) {
48
+ let chain = (await readTable()).find(item => item.chain?.name === name)?.chain;
49
+ if (!chain) {
50
+ await runner(['nft', 'add', 'chain', 'inet', 'axstack_sandbox', name, `{ type filter hook ${name} priority -10; }`]);
51
+ chain = (await readTable()).find(item => item.chain?.name === name)?.chain;
52
+ }
53
+ if (chain?.type !== 'filter' || chain.hook !== name || chain.prio !== -10 || chain.policy !== 'accept') throw hold(`Unexpected sandbox ${name} base chain; no policy changed`);
54
+ }
55
+ }
56
+ async function checkChains({ allowAbsent = false } = {}) {
57
+ const snapshot = await readTable();
58
+ for (const name of ['input', 'forward']) {
59
+ const chain = snapshot.find(item => item.chain?.name === name)?.chain;
60
+ if (!chain && allowAbsent) continue;
61
+ if (chain?.type !== 'filter' || chain.hook !== name || chain.prio !== -10 || chain.policy !== 'accept') throw hold(`Changed sandbox ${name} base chain; no policy changed`);
62
+ }
63
+ return snapshot;
64
+ }
65
+ return { readTable, check, remove, ensureTable, checkChains };
66
+ }
67
+
68
+ if (import.meta.main) {
69
+ const [action, json] = process.argv.slice(2);
70
+ if (action === '--help') console.log('Usage: network-firewall.js check|remove <rule JSON>\nSide effects: check reads only inet axstack_sandbox; remove deletes matching rule handles only. Never flushes a table or changes policy. Exit: 0 present/removed; 2 missing, changed or unknown; 1 malformed input.');
71
+ else {
72
+ try {
73
+ const rule = JSON.parse(json);
74
+ if (!['input', 'forward'].includes(rule.chain) || !/^axstack:[a-f0-9]{12}:\d+$/.test(rule.comment) || !Array.isArray(rule.expr)) throw Error('Invalid owned rule descriptor');
75
+ const firewall = createFirewall();
76
+ if (action === 'check') { if (!await firewall.check(rule)) throw hold(`Missing or changed rule ${rule.comment}`); }
77
+ else if (action === 'remove') await firewall.remove(rule);
78
+ else throw Error('Expected check or remove');
79
+ } catch (error) { console.error(error.message); process.exitCode = error.sandboxHold ? 2 : 1; }
80
+ }
81
+ }
@@ -0,0 +1,86 @@
1
+ import { deniedV4, deniedV6, ipAddress } from './network-address.js';
2
+
3
+ export function networkIdentity(runId) {
4
+ if (typeof runId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(runId)) throw Error('Invalid run ID');
5
+ return new Bun.CryptoHasher('sha256').update(runId).digest('hex').slice(0, 12);
6
+ }
7
+
8
+ export function networkDefinitions(runId, service) {
9
+ const hash = networkIdentity(runId);
10
+ const subnetSlot = Number.parseInt(hash.slice(0, 4), 16) % 16384;
11
+ /** @type {import('./launcher-contracts.js').Network['profile'][]} */
12
+ const profiles = service ? ['fetch', 'service', 'egress'] : ['fetch', 'egress'];
13
+ return profiles.map((profile, index) => {
14
+ const id = `axstack-${hash}-${profile}`;
15
+ const iface = `ax${hash}${profile[0]}`;
16
+ const slot = subnetSlot * 3 + index;
17
+ const subnets = [`10.${64 + (slot >> 8)}.${slot & 255}.0/24`, `${ipAddress(`fd73:${hash.slice(0, 4)}:${hash.slice(4, 8)}:${index}::`).text}/64`];
18
+ const internal = profile !== 'egress';
19
+ return { id, name: id, interface: iface, profile, internal, subnets,
20
+ createArgv: ['docker', 'network', 'create', '--driver', 'bridge', '--ipv6', ...(internal ? ['--internal'] : []),
21
+ '--subnet', subnets[0], '--subnet', subnets[1], '--opt', `com.docker.network.bridge.name=${iface}`,
22
+ '--label', 'axstack.sandbox=true', '--label', `axstack.sandbox.runId=${runId}`, id],
23
+ removeArgv: ['docker', 'network', 'rm', id] };
24
+ });
25
+ }
26
+
27
+ const match = (left, right, op = '==') => ({ match: { op, left, right } });
28
+ const destination = (family, address, op = '==') => {
29
+ const [base, bits] = address.split('/');
30
+ return match({ payload: { protocol: family, field: 'daddr' } }, bits ? { prefix: { addr: base, len: Number(bits) } } : base, op);
31
+ };
32
+
33
+ export function networkRules(networks, addresses, proxy, hash) {
34
+ /** @type {import('./launcher-contracts.js').Rule[]} */
35
+ const rules = [];
36
+ function rawRule(network, chain, tokens, expr, direction = 'iifname') {
37
+ const id = `axstack:${hash}:${rules.length}`;
38
+ const expression = [direction, JSON.stringify(network.interface), ...tokens];
39
+ const nftExpr = [match({ meta: { key: direction } }, network.interface), ...expr];
40
+ const descriptor = JSON.stringify({ chain, comment: id, expr: nftExpr });
41
+ rules.push({ id, family: 'inet', table: 'axstack_sandbox', chain, interfaces: [network.interface], expression,
42
+ installArgv: ['nft', 'add', 'rule', 'inet', 'axstack_sandbox', chain, ...expression, 'comment', JSON.stringify(id)],
43
+ checkArgv: [process.execPath, `${import.meta.dir}/network-firewall.js`, 'check', descriptor],
44
+ removeArgv: [process.execPath, `${import.meta.dir}/network-firewall.js`, 'remove', descriptor] });
45
+ }
46
+ function rule(network, chain, tokens, expr, direction = 'iifname') {
47
+ if (direction === 'iifname' && tokens.at(-1) === 'drop') {
48
+ rawRule(network, chain, ['udp', 'sport', '20053', ...tokens.slice(0, -1), 'counter', 'drop'],
49
+ [match({ payload: { protocol: 'udp', field: 'sport' } }, 20053), ...expr.slice(0, -1), { counter: null }, { drop: null }]);
50
+ }
51
+ rawRule(network, chain, tokens, expr, direction);
52
+ }
53
+ for (const network of networks) {
54
+ // Link-local kernel neighbour discovery is required before IPv6 data can
55
+ // reach the host-input drop. It exposes no host data socket or routed path.
56
+ rule(network, 'input', ['icmpv6', 'type', '{ nd-neighbor-solicit, nd-neighbor-advert }', 'ip6', 'hoplimit', '255', 'return'],
57
+ [match({ payload: { protocol: 'icmpv6', field: 'type' } }, { set: ['nd-neighbor-solicit', 'nd-neighbor-advert'] }), match({ payload: { protocol: 'ip6', field: 'hoplimit' } }, 255), { return: null }]);
58
+ rule(network, 'input', ['drop'], [{ drop: null }]);
59
+ // No unsolicited traffic into a run, even if an unrelated Docker rule accepts it.
60
+ rule(network, 'forward', ['iifname', '!=', JSON.stringify(network.interface), 'ct', 'state', '!=', '{ established, related }', 'drop'],
61
+ [match({ meta: { key: 'iifname' } }, network.interface, '!='), match({ ct: { key: 'state' } }, { set: ['established', 'related'] }, '!='), { drop: null }], 'oifname');
62
+ if (network.internal) {
63
+ rule(network, 'forward', ['oifname', '!=', JSON.stringify(network.interface), 'drop'],
64
+ [match({ meta: { key: 'oifname' } }, network.interface, '!='), { drop: null }]);
65
+ for (const [index, family] of ['ip', 'ip6'].entries()) {
66
+ rule(network, 'forward', [family, 'daddr', '!=', network.subnets[index], 'drop'],
67
+ [destination(family, network.subnets[index], '!='), { drop: null }]);
68
+ }
69
+ continue;
70
+ }
71
+ for (const address of [...new Set([...deniedV4, ...deniedV6, ...addresses])]) {
72
+ const family = ipAddress(address.split('/')[0]).version === 4 ? 'ip' : 'ip6';
73
+ rule(network, 'forward', [family, 'daddr', address, 'drop'], [destination(family, address), { drop: null }]);
74
+ }
75
+ rule(network, 'forward', ['ip6', 'daddr', '!=', '2000::/3', 'drop'], [destination('ip6', '2000::/3', '!='), { drop: null }]);
76
+ for (const resolver of [proxy.resolverIpv4, proxy.resolverIpv6]) {
77
+ const family = ipAddress(resolver).version === 4 ? 'ip' : 'ip6';
78
+ for (const protocol of ['udp', 'tcp']) rule(network, 'forward', [family, 'daddr', resolver, protocol, 'dport', '53', 'return'],
79
+ [destination(family, resolver), match({ payload: { protocol, field: 'dport' } }, 53), { return: null }]);
80
+ }
81
+ rule(network, 'forward', ['tcp', 'dport', '{ 80, 443 }', 'return'],
82
+ [match({ payload: { protocol: 'tcp', field: 'dport' } }, { set: [80, 443] }), { return: null }]);
83
+ rule(network, 'forward', ['drop'], [{ drop: null }]);
84
+ }
85
+ return rules;
86
+ }
@@ -0,0 +1,109 @@
1
+ import { commandRunner, createFirewall, hold } from './network-firewall.js';
2
+ import { networkDefinitions, networkIdentity } from './network-rules.js';
3
+
4
+ export function createNetworkRuntime({ runner = commandRunner } = {}) {
5
+ const firewall = createFirewall({ runner });
6
+ /** @returns {import('./launcher-contracts.js').Term} */
7
+ const pass = (id, evidence) => ({ id, status: 'pass', evidence });
8
+ function validate(owner, plan) {
9
+ if (owner?.label !== 'axstack.sandbox' || !owner.runId || !Number.isSafeInteger(owner.pid) || owner.pid < 1 || !owner.startTimeTicks || !owner.bootId) throw Error('Invalid network owner');
10
+ const hash = networkIdentity(owner.runId);
11
+ if (!plan?.networks?.length || !plan?.rules?.length) throw hold('Incomplete network plan');
12
+ const expected = networkDefinitions(owner.runId, plan.networks.some(n => n.profile === 'service'));
13
+ if (JSON.stringify(plan.networks) !== JSON.stringify(expected)) throw hold('Network ownership/argv mismatch');
14
+ for (const rule of plan.rules) {
15
+ if (rule.table !== 'axstack_sandbox' || rule.family !== 'inet' || !rule.id.startsWith(`axstack:${hash}:`) || !['input', 'forward'].includes(rule.chain) || !['iifname', 'oifname'].includes(rule.expression[0]) || !plan.networks.some(n => JSON.stringify(n.interface) === rule.expression[1])) throw hold('Unscoped firewall rule');
16
+ if (JSON.stringify(rule.installArgv) !== JSON.stringify(['nft', 'add', 'rule', 'inet', 'axstack_sandbox', rule.chain, ...rule.expression, 'comment', JSON.stringify(rule.id)])) throw hold('Changed rule installation argv');
17
+ const wanted = descriptor(rule);
18
+ const first = wanted.expr?.[0]?.match;
19
+ if (first?.op !== '==' || first?.left?.meta?.key !== rule.expression[0] || JSON.stringify(first?.right) !== rule.expression[1]) throw hold('Unscoped rule readback/removal descriptor');
20
+ }
21
+ }
22
+ function descriptor(rule) {
23
+ const wanted = JSON.parse(rule.checkArgv.at(-1));
24
+ if (wanted.comment !== rule.id || wanted.chain !== rule.chain) throw hold('Rule descriptor mismatch');
25
+ return wanted;
26
+ }
27
+ async function inspect(network) {
28
+ const result = await runner(['docker', 'network', 'ls', '--filter', `name=^${network.name}$`, '--format', '{{.Name}}']);
29
+ if (result.exitCode !== 0) throw hold('Cannot enumerate Docker networks');
30
+ if (!result.stdout.trim()) return null;
31
+ const inspected = await runner(['docker', 'network', 'inspect', network.name]);
32
+ if (inspected.exitCode !== 0) throw hold(`Cannot inspect network ${network.name}`);
33
+ try { const data = JSON.parse(inspected.stdout); if (!Array.isArray(data) || data.length !== 1) throw Error(); return data[0]; }
34
+ catch { throw hold('Malformed network inspection'); }
35
+ }
36
+ function owned(network, actual, owner) {
37
+ if (actual.Name !== network.name || actual.Labels?.['axstack.sandbox'] !== 'true' || actual.Labels?.['axstack.sandbox.runId'] !== owner.runId || actual.Options?.['com.docker.network.bridge.name'] !== network.interface) throw hold(`Foreign network ${network.name}`);
38
+ }
39
+ async function assertContainersGone(owner) {
40
+ const result = await runner(['docker', 'ps', '-a', '--quiet', '--filter', 'label=axstack.sandbox=true', '--filter', `label=axstack.sandbox.runId=${owner.runId}`]);
41
+ if (result.exitCode !== 0 || result.stdout.trim()) throw hold('Owned containers not independently confirmed gone');
42
+ }
43
+ async function installNetwork({ owner, plan }) {
44
+ validate(owner, plan);
45
+ await assertContainersGone(owner);
46
+ await firewall.ensureTable();
47
+ const terms = [];
48
+ for (const network of plan.networks) {
49
+ if (await inspect(network)) throw hold(`Run network already exists: ${network.name}`);
50
+ const created = await runner(network.createArgv);
51
+ if (created.exitCode !== 0) throw hold(`Network creation failed: ${network.name}`);
52
+ const actual = await inspect(network);
53
+ if (!actual) throw hold(`Network missing after creation: ${network.name}`);
54
+ owned(network, actual, owner);
55
+ const subnets = (actual.IPAM?.Config ?? []).map(item => item.Subnet).sort();
56
+ if (actual.Driver !== 'bridge' || actual.Internal !== network.internal || actual.EnableIPv6 !== true || JSON.stringify(subnets) !== JSON.stringify([...network.subnets].sort()) || Object.keys(actual.Containers ?? {}).length) throw hold(`Unexpected network policy: ${network.name}`);
57
+ terms.push(pass(`network:${network.id}`, [JSON.stringify(actual)]));
58
+ }
59
+ for (const rule of plan.rules) {
60
+ const installed = await runner(rule.installArgv);
61
+ if (installed.exitCode !== 0 || !await firewall.check(descriptor(rule))) throw hold(`Rule installation/readback failed: ${rule.id}`);
62
+ terms.push(pass(`rule:${rule.id}`, [JSON.stringify(rule.expression)]));
63
+ }
64
+ await firewall.checkChains();
65
+ for (const rule of plan.rules) if (!await firewall.check(descriptor(rule))) throw hold(`Rule disappeared before admission: ${rule.id}`);
66
+ return terms;
67
+ }
68
+ async function cleanupNetwork({ owner, plan }) {
69
+ validate(owner, plan);
70
+ await assertContainersGone(owner);
71
+ const existing = [];
72
+ for (const network of plan.networks) {
73
+ const actual = await inspect(network);
74
+ if (actual) {
75
+ owned(network, actual, owner);
76
+ if (Object.keys(actual.Containers ?? {}).length) throw hold(`Attached containers remain: ${network.name}`);
77
+ existing.push(network);
78
+ }
79
+ }
80
+ // Enumeration proves absence; failed/changed readback is never absence.
81
+ const listed = await runner(['nft', '-j', 'list', 'tables']);
82
+ if (listed.exitCode !== 0) throw hold('Cannot enumerate firewall tables during cleanup');
83
+ let tables;
84
+ try { tables = JSON.parse(listed.stdout).nftables; if (!Array.isArray(tables)) throw Error(); }
85
+ catch { throw hold('Malformed cleanup table enumeration'); }
86
+ const present = tables.some(item => item.table?.family === 'inet' && item.table?.name === 'axstack_sandbox');
87
+ const snapshot = present ? await firewall.checkChains({ allowAbsent: true }) : [];
88
+ // A failed install can leave any prefix. Validate every surviving rule
89
+ // before mutations, while independently proving all containers are gone.
90
+ if (present) for (const rule of plan.rules) {
91
+ if (!await firewall.check(descriptor(rule), { allowAbsent: true })) throw hold(`Changed rule at cleanup: ${rule.id}`);
92
+ }
93
+ await assertContainersGone(owner);
94
+ const terms = [pass('containers-gone', ['Docker lists no running or stopped owned container']), pass('cleanup-rules-readback', [JSON.stringify(snapshot)])];
95
+ // Networks disappear first while the firewall is still protecting their interfaces.
96
+ for (const network of existing) {
97
+ await runner(network.removeArgv);
98
+ if (await inspect(network)) throw hold(`Network remains: ${network.name}`);
99
+ terms.push(pass(`removed:${network.id}`, ['Docker network absence confirmed']));
100
+ }
101
+ await assertContainersGone(owner);
102
+ for (const rule of present ? plan.rules : []) {
103
+ await firewall.remove(descriptor(rule));
104
+ terms.push(pass(`removed:${rule.id}`, ['Rule handle absence confirmed']));
105
+ }
106
+ return terms;
107
+ }
108
+ return { installNetwork, cleanupNetwork };
109
+ }
@@ -0,0 +1,49 @@
1
+ import inventory from './inventory.json';
2
+ import config from './proxy-config.json';
3
+ import { ipAddress } from './network-address.js';
4
+ import { networkRules, networkIdentity, networkDefinitions } from './network-rules.js';
5
+ import { createNetworkRuntime } from './network-runtime.js';
6
+ export { proxyArgv } from './proxy-command.js';
7
+
8
+ /**
9
+ * C owns network* and proxy-config.json. Pure plan: one shared owned nft table;
10
+ * every rule matches only this run's interfaces; no base policy changes.
11
+ * @param {{runId:string, host:import('./launcher-contracts.js').HostFacts, proxy:import('./launcher-contracts.js').ProxyConfig, registryAllowlist:string[], sidecarIds:string[]}} _input
12
+ * @returns {import('./launcher-contracts.js').NetworkPlan}
13
+ * @throws {Error} Invalid config; sandboxHold:true for incomplete address facts.
14
+ */
15
+ export function planNetwork(_input) {
16
+ const { runId, host, proxy, registryAllowlist, sidecarIds } = _input;
17
+ const hash = networkIdentity(runId);
18
+ if (!host?.addresses?.length) throw Object.assign(Error('Incomplete host address facts'), { sandboxHold: true });
19
+ const addresses = [...new Set(host.addresses.map(address => ipAddress(address).text))].sort();
20
+ if (!Array.isArray(registryAllowlist) || JSON.stringify([...registryAllowlist].sort()) !== JSON.stringify([...inventory.registryAllowlist].sort())) throw Error('Registry list must match inventory');
21
+ if (JSON.stringify(Object.keys(proxy ?? {}).sort()) !== JSON.stringify(Object.keys(config).sort()) || Object.keys(config).some(k => proxy[k] !== config[k])) throw Error('Invalid fixed proxy config');
22
+ if (!Array.isArray(sidecarIds) || sidecarIds.some(id => typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id))) throw Error('Invalid sidecar IDs');
23
+ const networks = networkDefinitions(runId, sidecarIds.length > 0);
24
+ return { networks, rules: networkRules(networks, addresses, proxy, hash), proxy: { image: proxy.image,
25
+ networkIds: networks.filter(n => n.profile !== 'service').map(n => n.id),
26
+ environment: [
27
+ { name: 'AXSTACK_PROXY_ALLOWLIST', value: JSON.stringify(inventory.registryAllowlist) },
28
+ { name: 'AXSTACK_PROXY_RESOLVERS', value: JSON.stringify([config.resolverIpv4, config.resolverIpv6]) },
29
+ { name: 'AXSTACK_PROXY_HOST_ADDRESSES', value: JSON.stringify(addresses) },
30
+ { name: 'AXSTACK_PROXY_PORT', value: String(config.port) },
31
+ ] } };
32
+ }
33
+
34
+ /**
35
+ * Create run networks and install/check all rules before any container starts.
36
+ * @param {{owner:import('./launcher-contracts.js').Owner, plan:import('./launcher-contracts.js').NetworkPlan}} _input
37
+ * @returns {Promise<import('./launcher-contracts.js').Term[]>}
38
+ * @throws {Error} sandboxHold:true on failed/unknown installation or readback.
39
+ */
40
+ export async function installNetwork(_input) { return createNetworkRuntime().installNetwork(_input); }
41
+
42
+ /**
43
+ * Check rules still present, verify containers gone, remove only this run's rules/networks.
44
+ * Independently verify absence; a caller assertion of removal is insufficient.
45
+ * @param {{owner:import('./launcher-contracts.js').Owner, plan:import('./launcher-contracts.js').NetworkPlan}} _input
46
+ * @returns {Promise<import('./launcher-contracts.js').Term[]>}
47
+ * @throws {Error} sandboxHold:true for live containers or cleanup uncertainty.
48
+ */
49
+ export async function cleanupNetwork(_input) { return createNetworkRuntime().cleanupNetwork(_input); }
@@ -0,0 +1,17 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!-- Local package registration of the checksum-verified official API 37.0 r2 archive.
3
+ Source: https://dl.google.com/android/repository/repository2-3.xml
4
+ Archive omits package.xml; fractional API source.properties is not legacy-readable. -->
5
+ <ns2:repository xmlns:ns2="http://schemas.android.com/repository/android/common/02"
6
+ xmlns:sdk="http://schemas.android.com/sdk/android/repo/repository2/03"
7
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
8
+ <localPackage path="platforms;android-37.0" obsolete="false">
9
+ <type-details xsi:type="sdk:platformDetailsType">
10
+ <api-level>37.0</api-level><codename></codename>
11
+ <extension-level>22</extension-level><base-extension>true</base-extension>
12
+ <layoutlib api="15"/>
13
+ </type-details>
14
+ <revision><major>2</major></revision>
15
+ <display-name>Android SDK Platform 37.0</display-name>
16
+ </localPackage>
17
+ </ns2:repository>