axstack 0.65.0 → 0.67.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.
- package/README.md +2 -2
- package/docs/host-operations.md +6 -3
- package/package.json +1 -1
- package/skills/axstack/references/automations.md +8 -5
- package/skills/axstack/references/candidate-publication.md +7 -12
- package/skills/axstack/references/fleet-verification.md +3 -3
- package/skills/axstack/references/lifecycle.md +1 -1
- package/skills/axstack/references/pr-shape.md +8 -0
- package/skills/axstack/references/review-manager-prompt.md +16 -0
- package/skills/axstack/references/schedule-policy.json +123 -0
- package/skills/axstack/references/t3-runtime.md +5 -5
- package/skills/axstack/references/workspace-hygiene.md +9 -3
- package/skills/axstack/scripts/check-staged-file-tokens.js +1 -0
- package/skills/axstack/scripts/default-policy.js +1 -0
- package/skills/axstack/scripts/fleet-route-cli.js +2 -2
- package/skills/axstack/scripts/fleet-route-plan.js +2 -1
- package/skills/axstack/scripts/fleet-sample-io.js +1 -0
- package/skills/axstack/scripts/hub-usage.js +1 -1
- package/skills/axstack/scripts/pr-shape.js +161 -2
- package/skills/axstack/scripts/readiness-run.js +2 -0
- package/skills/axstack/scripts/readiness.js +10 -5
- package/skills/axstack/scripts/resolve-models.js +3 -1
- package/skills/axstack/scripts/schedule-drift.js +130 -0
- package/skills/axstack/scripts/scratch.js +201 -0
- package/skills/axstack/scripts/sync-default.js +1 -0
- package/skills/axstack/scripts/test-repository.js +1 -0
- package/skills/axstack/scripts/usage-split.js +286 -0
- package/skills/axstack-audit/SKILL.md +2 -0
- package/skills/axstack-review/references/review-receipt.md +1 -1
- package/skills/axstack-verify/SKILL.md +8 -1
- package/skills/voa/references/verification.md +5 -2
|
@@ -6,6 +6,7 @@ import { executeDeclared } from './readiness-run.js';
|
|
|
6
6
|
const scriptVersion = '1.1.0';
|
|
7
7
|
const criteriaVersion = 1;
|
|
8
8
|
|
|
9
|
+
/** @param {"ignore" | Uint8Array} [stdin] */
|
|
9
10
|
function gitOutput(repo, args, stdin = 'ignore') {
|
|
10
11
|
const argv = gitArgv('-C', repo, ...args);
|
|
11
12
|
const result = Bun.spawnSync(argv, { stdout: 'pipe', stderr: 'pipe', stdin });
|
|
@@ -110,10 +111,12 @@ const definitions = [
|
|
|
110
111
|
];
|
|
111
112
|
|
|
112
113
|
function packageManager(files, pkg) {
|
|
113
|
-
|
|
114
|
+
/** @type {[string, string[]][]} */
|
|
115
|
+
const lockfiles = [
|
|
114
116
|
['bun', ['bun.lock', 'bun.lockb']], ['npm', ['package-lock.json', 'npm-shrinkwrap.json']],
|
|
115
117
|
['pnpm', ['pnpm-lock.yaml']], ['yarn', ['yarn.lock']],
|
|
116
|
-
]
|
|
118
|
+
];
|
|
119
|
+
const locks = lockfiles.filter(([, names]) => names.some(files.has));
|
|
117
120
|
if (!locks.length) {
|
|
118
121
|
const dependencyFields = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies', 'bundledDependencies', 'bundleDependencies', 'workspaces'];
|
|
119
122
|
if (!files.has('pnpm-workspace.yaml') && dependencyFields.every((field) => !pkg?.[field] || Object.keys(pkg[field]).length === 0)) {
|
|
@@ -130,7 +133,9 @@ function packageManager(files, pkg) {
|
|
|
130
133
|
|
|
131
134
|
function declaredCommands(files, pkg, manager, set, invalidPackage) {
|
|
132
135
|
const prose = files.paths.filter((path) => /\.md$/i.test(path)).map((path) => files.read(path)).join('\n');
|
|
133
|
-
|
|
136
|
+
/** @type {[string, string[]][]} */
|
|
137
|
+
const groups = [['env.build', ['build']], ['testing.test', ['test']], ['testing.lint-typecheck', ['lint', 'typecheck']]];
|
|
138
|
+
for (const [id, names] of groups) {
|
|
134
139
|
if (invalidPackage) {
|
|
135
140
|
set(id, 'unknown', [`git show ${files.revision}:package.json`], 'invalid package.json');
|
|
136
141
|
continue;
|
|
@@ -189,9 +194,9 @@ function assess(files) {
|
|
|
189
194
|
const codeql = [];
|
|
190
195
|
for (const path of workflows) {
|
|
191
196
|
try {
|
|
192
|
-
const workflow = Bun.YAML.parse(files.read(path));
|
|
197
|
+
const workflow = /** @type {{ on?: string | string[] | Record<string, unknown>, jobs?: Record<string, { steps?: { run?: string, uses?: string }[] }> }} */ (Bun.YAML.parse(files.read(path)));
|
|
193
198
|
const trigger = workflow?.on;
|
|
194
|
-
const pr = trigger === 'pull_request' || (Array.isArray(trigger) ? trigger.includes('pull_request') : trigger && Object.hasOwn(trigger, 'pull_request'));
|
|
199
|
+
const pr = trigger === 'pull_request' || (Array.isArray(trigger) ? trigger.includes('pull_request') : trigger && Object.hasOwn(/** @type {Record<string, unknown>} */ (trigger), 'pull_request'));
|
|
195
200
|
const steps = Object.values(workflow?.jobs ?? {}).flatMap((job) => job?.steps ?? []);
|
|
196
201
|
const runs = steps.map((step) => step?.run).filter((run) => typeof run === 'string');
|
|
197
202
|
if (steps.some((step) => typeof step?.uses === 'string' && /^github\/codeql-action\//.test(step.uses))) codeql.push(path);
|
|
@@ -48,7 +48,9 @@ function providerFrom(catalog, provider) {
|
|
|
48
48
|
return instance;
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
|
|
51
|
+
/** @param {{ provider?: string, model?: string, class?: string, excluded: string[] }} options */
|
|
52
|
+
function modelFrom(models, options) {
|
|
53
|
+
const { provider, model: pin, class: modelClass, excluded } = options;
|
|
52
54
|
if (pin && pin !== 'null') {
|
|
53
55
|
const model = models.find((model) => model.id === pin && !excluded.includes(model.id));
|
|
54
56
|
if (!model) throw new Error(`missing requested model ${pin}`);
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
|
|
4
|
+
const HELP = `schedule-drift — canonical schedule comparison (R2 fact mode)
|
|
5
|
+
bun schedule-drift.js --export FILE --bindings FILE [--prompts DIR] [--now ISO] [--max-age-seconds N]
|
|
6
|
+
--export FILE Saved JSON: {version:1,host,exportedAt,complete:true,tasks:[{scheduledTaskId,
|
|
7
|
+
projectId,prompt,schedule,enabled}]}. Export every relevant project; never use a live database.
|
|
8
|
+
--bindings FILE Private JSON: {host,schedules:[{promptFile,scheduledTaskId,projectId,enabled,schedule,
|
|
9
|
+
values:{HOST_TOKEN:"literal value"}}]}. Declare all three packaged prompt filenames exactly once.
|
|
10
|
+
For intentional host exclusions use {promptFile,absent:true,scheduledTaskId?:expectedId}.
|
|
11
|
+
Fresh complete matching-host coverage yields n/a; any matching declared task ID fails.
|
|
12
|
+
Without a task ID, absent:true is an explicit host-scope declaration, not identity discovery.
|
|
13
|
+
Values substitute only explicit {{HOST_TOKEN}} placeholders. No implicit trim or normalization.
|
|
14
|
+
A live prompt containing any unfilled {{HOST_ prefix fails, even if bound bytes match.
|
|
15
|
+
Schedule is the exact host declaration; review-manager additionally requires interval 1800000.
|
|
16
|
+
--prompts DIR Directory containing the three packaged prompt files; default: installed ../references.
|
|
17
|
+
--now ISO Observation time with timezone; default: current UTC. Saved times prove no live delivery.
|
|
18
|
+
--max-age-seconds N Maximum export age, inclusive; positive integer, default 300. Future exports are unknown.
|
|
19
|
+
--help Show flags, schema, effects and limitations.
|
|
20
|
+
No writes, subprocesses, network, database access, schedule mutations or persistent state.
|
|
21
|
+
Stdout reports per-term pass/fail/unknown/n/a with evidence and counts only; no aggregate verdict or authority.
|
|
22
|
+
Exports and bindings stay private. Output contains hashes and filenames, never prompts, IDs or host values.
|
|
23
|
+
Missing, malformed, unavailable, stale or incomplete evidence is unknown; no comparison passes without fresh coverage.
|
|
24
|
+
Exit: 0 measured (including failed facts), 1 invalid CLI/error, 2 incomplete (unknown facts).
|
|
25
|
+
`;
|
|
26
|
+
const files = ['review-manager-prompt.md', 'pr-triage-nightly.md', 'test-audit-weekly.md'];
|
|
27
|
+
const sha256 = (bytes) => new Bun.CryptoHasher('sha256').update(bytes).digest('hex');
|
|
28
|
+
const time = (value) => typeof value === 'string' && /T.*(?:Z|[+-]\d\d:\d\d)$/.test(value) ? Date.parse(value) : NaN;
|
|
29
|
+
const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
30
|
+
const nonempty = (v) => typeof v === 'string' && v.length > 0;
|
|
31
|
+
const ordered = (value) => Array.isArray(value) ? value.map(ordered) : object(value)
|
|
32
|
+
? Object.fromEntries(Object.keys(value).sort().map((key) => [key, ordered(value[key])])) : value;
|
|
33
|
+
const equal = (a, b) => JSON.stringify(ordered(a)) === JSON.stringify(ordered(b));
|
|
34
|
+
|
|
35
|
+
function options(argv) {
|
|
36
|
+
const args = { '--prompts': `${import.meta.dir}/../references`, '--now': new Date().toISOString(), '--max-age-seconds': '300' };
|
|
37
|
+
const seen = new Set();
|
|
38
|
+
for (let i = 0; i < argv.length; i += 2) {
|
|
39
|
+
const key = argv[i];
|
|
40
|
+
if (!['--export', '--bindings', '--prompts', '--now', '--max-age-seconds'].includes(key) || !argv[i + 1] || seen.has(key)) {
|
|
41
|
+
throw new Error(`invalid argument: ${key}`);
|
|
42
|
+
}
|
|
43
|
+
seen.add(key);
|
|
44
|
+
args[key] = argv[i + 1];
|
|
45
|
+
}
|
|
46
|
+
if (!args['--export'] || !args['--bindings'] || !Number.isFinite(time(args['--now'])) ||
|
|
47
|
+
!/^[1-9]\d*$/.test(args['--max-age-seconds']) || !Number.isSafeInteger(Number(args['--max-age-seconds']))) {
|
|
48
|
+
throw new Error('expected --export, --bindings, timezone-qualified --now and positive --max-age-seconds');
|
|
49
|
+
}
|
|
50
|
+
return args;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function compare(args) {
|
|
54
|
+
const terms = [];
|
|
55
|
+
const term = (id, status, evidence) => terms.push({ id, status, evidence });
|
|
56
|
+
let source, bindings, exportSha256 = null, bindingsSha256 = null;
|
|
57
|
+
try {
|
|
58
|
+
const bytes = readFileSync(args['--export']);
|
|
59
|
+
exportSha256 = sha256(bytes);
|
|
60
|
+
source = JSON.parse(bytes.toString());
|
|
61
|
+
const declared = readFileSync(args['--bindings']);
|
|
62
|
+
bindingsSha256 = sha256(declared);
|
|
63
|
+
bindings = JSON.parse(declared.toString());
|
|
64
|
+
} catch { /* A missing or malformed saved export/binding is unavailable evidence. */ }
|
|
65
|
+
const age = (time(args['--now']) - time(source?.exportedAt)) / 1000;
|
|
66
|
+
const fresh = source?.version === 1 && source.complete === true && nonempty(source.host) &&
|
|
67
|
+
Array.isArray(source.tasks) && Number.isFinite(age) && age >= 0 && age <= Number(args['--max-age-seconds']);
|
|
68
|
+
const declared = object(bindings) && nonempty(bindings.host) && Array.isArray(bindings.schedules);
|
|
69
|
+
term('export', fresh ? 'pass' : 'unknown', fresh ? `complete export; age ${age}s; sha256 ${exportSha256}` : 'unavailable, incomplete, malformed, stale or future export');
|
|
70
|
+
term('host', !fresh || !declared ? 'unknown' : source.host === bindings.host ? 'pass' : 'fail', 'export host compared with private declared host');
|
|
71
|
+
for (const file of files) {
|
|
72
|
+
const rows = declared ? bindings.schedules.filter((b) => b?.promptFile === file) : [];
|
|
73
|
+
const binding = rows.length === 1 ? rows[0] : null;
|
|
74
|
+
const tasks = fresh && nonempty(binding?.scheduledTaskId)
|
|
75
|
+
? source.tasks.filter((t) => t?.scheduledTaskId === binding.scheduledTaskId) : [];
|
|
76
|
+
const task = tasks.length === 1 ? tasks[0] : null;
|
|
77
|
+
if (binding?.absent === true) {
|
|
78
|
+
const status = !fresh || source.host !== bindings.host ? 'unknown' : tasks.length ? 'fail' : 'n/a';
|
|
79
|
+
for (const suffix of ['binding', 'prompt', 'cadence', 'enabled']) {
|
|
80
|
+
term(`${file}.${suffix}`, status, 'explicit host exclusion; fresh complete matching-host export required; any declared task ID must be absent');
|
|
81
|
+
}
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const usable = fresh && declared && rows.length === 1 && task !== null;
|
|
85
|
+
const fact = (suffix, known, matches, evidence) => term(`${file}.${suffix}`,
|
|
86
|
+
!usable || !known ? 'unknown' : matches ? 'pass' : 'fail', evidence);
|
|
87
|
+
fact('binding', nonempty(binding?.projectId) && nonempty(task?.projectId),
|
|
88
|
+
task?.projectId === binding?.projectId, 'exact schedule ID and project binding; missing or duplicate identities are unknown');
|
|
89
|
+
let expected = null, packagedSha256 = null;
|
|
90
|
+
try {
|
|
91
|
+
const bytes = readFileSync(`${args['--prompts']}/${file}`);
|
|
92
|
+
packagedSha256 = sha256(bytes);
|
|
93
|
+
expected = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
94
|
+
expected = expected.replace(/\{\{(HOST_[A-Z_]+)\}\}/g, (_, key) => {
|
|
95
|
+
if (!object(binding?.values) || typeof binding.values[key] !== 'string') throw new Error('unbound host token');
|
|
96
|
+
return binding.values[key];
|
|
97
|
+
});
|
|
98
|
+
} catch { expected = null; }
|
|
99
|
+
const unfilled = nonempty(task?.prompt) && task.prompt.includes('{{HOST_');
|
|
100
|
+
fact('prompt', nonempty(task?.prompt) && (unfilled || expected !== null), !unfilled && expected === task?.prompt,
|
|
101
|
+
`live host tokens must be filled; exact UTF-8 bytes after declared host-token substitution; packaged sha256 ${packagedSha256 ?? 'unavailable'}`);
|
|
102
|
+
const scheduleKnown = validSchedule(binding?.schedule) && validSchedule(task?.schedule);
|
|
103
|
+
const canonical = file !== files[0] || equal(binding?.schedule, { type: 'interval', everyMs: 1800000 });
|
|
104
|
+
fact('cadence', scheduleKnown, canonical && equal(task?.schedule, binding?.schedule), 'exact declared schedule; review-manager interval fixed at 1800000ms');
|
|
105
|
+
fact('enabled', typeof binding?.enabled === 'boolean' && typeof task?.enabled === 'boolean',
|
|
106
|
+
task?.enabled === binding?.enabled, 'enabled state compared with private declaration');
|
|
107
|
+
}
|
|
108
|
+
const counts = Object.fromEntries(['pass', 'fail', 'unknown', 'n/a'].map((s) => [s, terms.filter((t) => t.status === s).length]));
|
|
109
|
+
return { version: 1, observedAt: args['--now'], exportSha256, bindingsSha256, terms, counts };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function validSchedule(s) {
|
|
113
|
+
if (!object(s)) return false;
|
|
114
|
+
if (s.type === 'interval') return Number.isSafeInteger(s.everyMs) && s.everyMs > 0;
|
|
115
|
+
if (s.type !== 'fixed_time' || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(s.timeOfDay)) return false;
|
|
116
|
+
return s.weekdays === undefined || s.weekdays === null || Array.isArray(s.weekdays) && s.weekdays.length > 0 &&
|
|
117
|
+
s.weekdays.every((d) => Number.isSafeInteger(d) && d >= 0 && d <= 6);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
try {
|
|
121
|
+
if (process.argv.slice(2).length === 1 && process.argv[2] === '--help') console.log(HELP);
|
|
122
|
+
else {
|
|
123
|
+
const report = compare(options(process.argv.slice(2)));
|
|
124
|
+
console.log(JSON.stringify(report, null, 2));
|
|
125
|
+
process.exitCode = report.counts.unknown ? 2 : 0;
|
|
126
|
+
}
|
|
127
|
+
} catch (error) {
|
|
128
|
+
console.error(`schedule-drift: ${error.message}`);
|
|
129
|
+
process.exitCode = 1;
|
|
130
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
const help = `Usage: bun scratch.js run [--root <existing-private-parent>] -- <command> [args...]
|
|
4
|
+
bun scratch.js plan --root <scratch-root> [--root <scratch-root> ...]
|
|
5
|
+
bun scratch.js --help
|
|
6
|
+
|
|
7
|
+
--root Absolute directory, with no symlink components. Run accepts one existing
|
|
8
|
+
owned 0700 parent outside realpath(HOME). Plan accepts named roots only.
|
|
9
|
+
--help Print flags, effects and exit codes; no writes or child process.
|
|
10
|
+
run Without --root, use a safe TMPDIR parent; if absent or unsafe, use /tmp.
|
|
11
|
+
Create a fresh axstack-scratch-<random>/ root (0700), owner.json (0600),
|
|
12
|
+
cwd/ (0700), tmp/ (0700). Print their declared absolute paths as JSON.
|
|
13
|
+
The owner stamp identifies this helper's paths, not execution authority.
|
|
14
|
+
plan Read only declared root metadata, owner.json and cwd/tmp metadata;
|
|
15
|
+
validate path components and realpath(HOME). No scan or deletion.
|
|
16
|
+
|
|
17
|
+
Process effects: run launches exactly the given command without a shell, waits
|
|
18
|
+
for its exit, sets cwd and TMPDIR to the declared children, inherits other env
|
|
19
|
+
(including HOME), and sends child stdout/stderr to this helper's stderr.
|
|
20
|
+
Filesystem effects: run creates only the paths above, retaining even partial
|
|
21
|
+
creation on error. Plan has no filesystem writes. Cleanup: none in any mode;
|
|
22
|
+
caller owns validated literal-path cleanup, including after failures.
|
|
23
|
+
Network/container effects: none by the helper. The child may start processes,
|
|
24
|
+
write files, use the network or containers under the caller's authority.
|
|
25
|
+
This is NOT filesystem containment: absolute paths and HOME remain the caller's
|
|
26
|
+
responsibility. It provides no process containment or descendant cleanup.
|
|
27
|
+
No dispatch, scheduling, retries, merging or phase selection.
|
|
28
|
+
|
|
29
|
+
Reports per-term pass/fail/unknown/n/a with evidence, no aggregate verdict.
|
|
30
|
+
Exit 0: measured, including failed plan criteria or a nonzero child exit.
|
|
31
|
+
Exit 1: invalid input or execution error. Exit 2: hold or incomplete observation.
|
|
32
|
+
Child exitCode and signal are stored separately in the JSON child field.
|
|
33
|
+
Check those fields: helper exit 0 does not mean the child passed.
|
|
34
|
+
Repository commands must select the repository explicitly.
|
|
35
|
+
The --cwd= form is required because the spaced bun --cwd <repo> form prints help
|
|
36
|
+
and exits 0, a false green. For example:
|
|
37
|
+
run -- bun --cwd=/absolute/repo run test tests/example.test.js
|
|
38
|
+
HOME means the canonical environment HOME at startup, not the account database.
|
|
39
|
+
With a fixture HOME, the caller must independently exclude the account's home.
|
|
40
|
+
Path components reject symlinks and world-writable directories without sticky
|
|
41
|
+
mode. Hostile concurrent path replacement remains the caller's responsibility.
|
|
42
|
+
`;
|
|
43
|
+
|
|
44
|
+
const normalize = (path) => path.replace(/\/+/g, '/').replace(/\/$/, '') || '/';
|
|
45
|
+
|
|
46
|
+
function options(argv) {
|
|
47
|
+
const mode = argv[0];
|
|
48
|
+
if (!['run', 'plan'].includes(mode)) throw Error('pass run or plan; see --help');
|
|
49
|
+
const separator = argv.indexOf('--');
|
|
50
|
+
const flags = argv.slice(1, separator < 0 ? undefined : separator);
|
|
51
|
+
const roots = [];
|
|
52
|
+
for (let i = 0; i < flags.length; i += 2) {
|
|
53
|
+
const path = flags[i + 1];
|
|
54
|
+
if (flags[i] !== '--root' || !path?.startsWith('/') || path.includes('\0') || path.split('/').some((p) => p === '..' || p === '.')) {
|
|
55
|
+
throw Error('pass --root <absolute-path> without dot components; see --help');
|
|
56
|
+
}
|
|
57
|
+
roots.push(normalize(path));
|
|
58
|
+
}
|
|
59
|
+
const command = separator < 0 ? [] : argv.slice(separator + 1);
|
|
60
|
+
if (mode === 'run' ? roots.length > 1 || !command.length : !roots.length || separator >= 0) {
|
|
61
|
+
throw Error('run needs one command and at most one parent; plan needs roots only; see --help');
|
|
62
|
+
}
|
|
63
|
+
return { mode, roots, command };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function unsafeComponent(path) {
|
|
67
|
+
let component = '';
|
|
68
|
+
for (const part of path.split('/').filter(Boolean)) {
|
|
69
|
+
component += `/${part}`;
|
|
70
|
+
const stat = lstatSync(component);
|
|
71
|
+
if (stat.isSymbolicLink()) return { component, reason: 'symlink; not followed' };
|
|
72
|
+
if ((stat.mode & 0o002) && !(stat.mode & 0o1000)) return { component, reason: 'world-writable without sticky mode' };
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function inspect(path, home, terms, systemParent = false) {
|
|
78
|
+
const add = (id, status, evidence) => terms.push({ root: path, id, status, evidence });
|
|
79
|
+
try {
|
|
80
|
+
if (!path.startsWith('/') || path.split('/').some((part) => part === '.' || part === '..')) {
|
|
81
|
+
add('path', 'fail', 'absolute path without dot components required');
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
const unsafe = unsafeComponent(path);
|
|
85
|
+
if (unsafe) {
|
|
86
|
+
add('path-components', 'fail', unsafe);
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
add('path-components', 'pass', 'no symlinks or world-writable non-sticky components');
|
|
90
|
+
const stat = lstatSync(path);
|
|
91
|
+
const actual = realpathSync(path);
|
|
92
|
+
const outside = actual !== home && !actual.startsWith(`${home === '/' ? '' : home}/`);
|
|
93
|
+
const owner = stat.uid === process.getuid() || (systemParent && stat.uid === 0);
|
|
94
|
+
const mode = stat.mode & 0o7777;
|
|
95
|
+
const permissions = systemParent ? (!(mode & 0o022) || !!(mode & 0o1000)) : mode === 0o700;
|
|
96
|
+
add('directory', stat.isDirectory() ? 'pass' : 'fail', { path });
|
|
97
|
+
add('owner', owner ? 'pass' : 'fail', { uid: stat.uid, expected: process.getuid(), systemParent });
|
|
98
|
+
add('mode', permissions ? 'pass' : 'fail', { mode: mode.toString(8), systemParent });
|
|
99
|
+
add('outside-home', outside ? 'pass' : 'fail', { home, path });
|
|
100
|
+
return stat.isDirectory() && owner && permissions && outside;
|
|
101
|
+
} catch (error) {
|
|
102
|
+
add('metadata', 'unknown', { code: error.code, message: error.message });
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function stampFor(root) {
|
|
108
|
+
return { version: 1, kind: 'axstack-scratch', uid: process.getuid(), root, cwd: `${root}/cwd`, tmp: `${root}/tmp` };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function inspectStamp(root, terms) {
|
|
112
|
+
const path = `${root}/owner.json`;
|
|
113
|
+
try {
|
|
114
|
+
const stat = lstatSync(path);
|
|
115
|
+
if (!stat.isFile() || stat.uid !== process.getuid() || (stat.mode & 0o7777) !== 0o600) {
|
|
116
|
+
terms.push({ root, id: 'stamp', status: 'fail', evidence: { path, reason: 'need owned regular 0600 stamp; links not followed' } });
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const expected = stampFor(root);
|
|
120
|
+
let stamp;
|
|
121
|
+
try { stamp = JSON.parse(readFileSync(path, 'utf8')); } catch (error) {
|
|
122
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
123
|
+
terms.push({ root, id: 'stamp', status: 'fail', evidence: { path, reason: 'malformed JSON' } });
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const matches = stamp && Object.entries(expected).every(([key, value]) => stamp[key] === value);
|
|
127
|
+
terms.push({ root, id: 'stamp', status: matches ? 'pass' : 'fail', evidence: { path, expected } });
|
|
128
|
+
} catch (error) {
|
|
129
|
+
terms.push({ root, id: 'stamp', status: 'unknown', evidence: { path, code: error.code, message: error.message } });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function main(argv) {
|
|
134
|
+
if (argv.length === 1 && argv[0] === '--help') { console.log(help); return 0; }
|
|
135
|
+
const report = { mode: null, roots: [], terms: [], child: null };
|
|
136
|
+
try {
|
|
137
|
+
const { mode, roots, command } = options(argv);
|
|
138
|
+
Object.assign(report, { mode, roots });
|
|
139
|
+
let home;
|
|
140
|
+
try {
|
|
141
|
+
if (!process.env.HOME) throw Error('HOME unavailable; cannot establish real HOME boundary');
|
|
142
|
+
home = realpathSync(process.env.HOME);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
report.terms.push({ id: 'home', status: 'unknown', evidence: error.message });
|
|
145
|
+
console.log(JSON.stringify(report));
|
|
146
|
+
return 2;
|
|
147
|
+
}
|
|
148
|
+
if (mode === 'plan') {
|
|
149
|
+
for (const root of roots) {
|
|
150
|
+
if (inspect(root, home, report.terms)) {
|
|
151
|
+
inspectStamp(root, report.terms);
|
|
152
|
+
inspect(`${root}/cwd`, home, report.terms);
|
|
153
|
+
inspect(`${root}/tmp`, home, report.terms);
|
|
154
|
+
} else {
|
|
155
|
+
report.terms.push({ root, id: 'stamp', status: 'n/a', evidence: 'root not safe to read' });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
} else {
|
|
159
|
+
let parent = roots[0];
|
|
160
|
+
if (!parent && process.env.TMPDIR) {
|
|
161
|
+
// Rejected environment candidates are facts, but do not prevent fallback.
|
|
162
|
+
const candidate = normalize(process.env.TMPDIR);
|
|
163
|
+
if (inspect(candidate, home, report.terms)) parent = candidate;
|
|
164
|
+
else report.terms.push({ id: 'fallback', status: 'pass', evidence: 'unsafe TMPDIR ignored; using /tmp' });
|
|
165
|
+
}
|
|
166
|
+
if (roots.length ? !inspect(parent, home, report.terms) : !parent && !inspect('/tmp', home, report.terms, true)) {
|
|
167
|
+
console.log(JSON.stringify(report));
|
|
168
|
+
return 2;
|
|
169
|
+
}
|
|
170
|
+
parent ??= '/tmp';
|
|
171
|
+
report.terms.push({ id: 'parent', status: 'pass', evidence: parent });
|
|
172
|
+
const root = mkdtempSync(`${parent}/axstack-scratch-`);
|
|
173
|
+
Object.assign(report, stampFor(root));
|
|
174
|
+
chmodSync(root, 0o700);
|
|
175
|
+
writeFileSync(`${root}/owner.json`, `${JSON.stringify(stampFor(root))}\n`, { mode: 0o600, flag: 'wx' });
|
|
176
|
+
mkdirSync(`${root}/cwd`, { mode: 0o700 });
|
|
177
|
+
mkdirSync(`${root}/tmp`, { mode: 0o700 });
|
|
178
|
+
// Check the actual filesystem rather than assuming creation preserved mode/owner.
|
|
179
|
+
const created = [];
|
|
180
|
+
const safe = [root, `${root}/cwd`, `${root}/tmp`].every((path) => inspect(path, home, created));
|
|
181
|
+
report.terms.push(...created);
|
|
182
|
+
if (!safe) { console.log(JSON.stringify(report)); return 2; }
|
|
183
|
+
const child = Bun.spawn(command, {
|
|
184
|
+
cwd: `${root}/cwd`, env: { ...process.env, TMPDIR: `${root}/tmp` },
|
|
185
|
+
stdin: 'inherit', stdout: 2, stderr: 'inherit',
|
|
186
|
+
});
|
|
187
|
+
report.child = { exitCode: await child.exited, signal: child.signalCode };
|
|
188
|
+
report.terms.push({ id: 'child', status: report.child.exitCode === 0 && !report.child.signal ? 'pass' : 'fail', evidence: report.child });
|
|
189
|
+
}
|
|
190
|
+
console.log(JSON.stringify(report));
|
|
191
|
+
// An observed unsafe inherited TMPDIR is complete once the safe fallback runs.
|
|
192
|
+
return report.child ? 0 : report.terms.some((term) => term.status === 'unknown') ? 2 : 0;
|
|
193
|
+
} catch (error) {
|
|
194
|
+
const permissionGap = ['EACCES', 'EPERM'].includes(error.code);
|
|
195
|
+
report.terms.push({ id: 'execution', status: permissionGap ? 'unknown' : 'fail', evidence: { message: error.message, code: error.code } });
|
|
196
|
+
console.log(JSON.stringify(report));
|
|
197
|
+
return permissionGap ? 2 : 1;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (import.meta.main) process.exitCode = await main(process.argv.slice(2));
|
|
@@ -60,6 +60,7 @@ async function main() {
|
|
|
60
60
|
try { history = JSON.parse(fs.readFileSync(options['--history-file'], 'utf8')); }
|
|
61
61
|
catch { history = { unavailable: 'history file unavailable or malformed' }; }
|
|
62
62
|
} else history = readHistory(path, now, options['--history-db']);
|
|
63
|
+
/** @type {ReturnType<typeof decide> & { mode?: string }} */
|
|
63
64
|
const result = decide(settings, usage, catalogs, now, history);
|
|
64
65
|
if (result.action === 'update' && options['--apply']) {
|
|
65
66
|
const status = commit(path, original, result.selection);
|