@codeledger/cli 0.10.80 → 0.10.82
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 +36 -2
- package/bin/codeledger.js +96 -53
- package/package.json +4 -3
- package/scripts/postinstall.js +131 -68
- package/scripts/runtime-pin.js +125 -0
package/README.md
CHANGED
|
@@ -72,8 +72,42 @@ runner situation to stabilize in a later release.
|
|
|
72
72
|
|
|
73
73
|
Other platforms fall through `postinstall` softly — `npm install`
|
|
74
74
|
succeeds, but running `codeledger` will either use a repo-local vendored
|
|
75
|
-
runtime if the
|
|
76
|
-
|
|
75
|
+
runtime if the selected repo has `.codeledger/bin/`, or report the unavailable
|
|
76
|
+
native route. Skipping postinstall does not create a runtime for a fresh repo;
|
|
77
|
+
`codeledger init` cannot bootstrap through that missing-runtime loop. Intel Macs
|
|
78
|
+
cannot run Apple Silicon binaries through Rosetta. Use a supported host or
|
|
79
|
+
review the source-build prerequisites, without assuming untested OS support.
|
|
80
|
+
|
|
81
|
+
## MCP First Use
|
|
82
|
+
|
|
83
|
+
```sh
|
|
84
|
+
codeledger ready --cwd /absolute/path/to/repo --task "Inspect this repository"
|
|
85
|
+
codeledger license status --cwd /absolute/path/to/repo
|
|
86
|
+
codeledger mcp status --cwd /absolute/path/to/repo --json
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Use the printed repository-bound config, for example
|
|
90
|
+
`npx -y @codeledger/cli@latest mcp start --cwd /absolute/path/to/repo`.
|
|
91
|
+
Launch forms that all start the same stdio server:
|
|
92
|
+
|
|
93
|
+
- `codeledger mcp start [--cwd <repo>] [--profile core|governance|panel|full]`
|
|
94
|
+
- `codeledger-mcp [--cwd <repo>] ...` — bin alias that always runs `mcp start`
|
|
95
|
+
with your arguments appended (for registries that cannot pass arguments;
|
|
96
|
+
`npx -y -p @codeledger/cli codeledger-mcp`)
|
|
97
|
+
- bare `codeledger` with stdin and stdout both piped (how MCP clients launch
|
|
98
|
+
it). A terminal still gets help; `CODELEDGER_NO_MCP_AUTOSTART=1` forces help.
|
|
99
|
+
|
|
100
|
+
Licensing is **free to list, licensed to call**: `initialize` and `tools/list`
|
|
101
|
+
always work (even before `codeledger ready`), and tool calls need an active
|
|
102
|
+
Team or Enterprise license. Without one, calls return a structured `locked`
|
|
103
|
+
result (`codeledger/feature-lock/v1`) with the pricing link and activation
|
|
104
|
+
steps; `get_activation_payload` stays free. In an uninitialized directory every
|
|
105
|
+
call returns `not_evaluable` with the exact `codeledger ready --cwd <path>` fix.
|
|
106
|
+
Install and configuration success do not establish a connection: reconnect, require
|
|
107
|
+
initialize and tools/list, then call `get_active_context` with `{}` to read the
|
|
108
|
+
prepared bundle. Missing activation is degraded context. Verify cold and warm
|
|
109
|
+
cache behavior; diagnostics must stay on stderr. See
|
|
110
|
+
[MCP First Use](https://github.com/codeledgerECF/codeledger/blob/main/docs/MCP.md).
|
|
77
111
|
|
|
78
112
|
## Usage
|
|
79
113
|
|
package/bin/codeledger.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
/*
|
|
3
3
|
* CodeLedger npm launcher — thin shim.
|
|
4
4
|
*
|
|
5
|
-
* This
|
|
5
|
+
* This launcher and its installation helpers ship to npm under @codeledger/cli.
|
|
6
6
|
* It contains no engine code, no scoring logic, no formulas. All CodeLedger
|
|
7
7
|
* functionality lives inside the hardened binary that is downloaded during
|
|
8
8
|
* `postinstall` from the GitHub Release for this exact version, verified
|
|
@@ -18,11 +18,22 @@
|
|
|
18
18
|
'use strict';
|
|
19
19
|
|
|
20
20
|
const { spawnSync } = require('node:child_process');
|
|
21
|
-
const
|
|
22
|
-
const
|
|
21
|
+
const fs = require('node:fs');
|
|
22
|
+
const path = require('node:path');
|
|
23
|
+
const crypto = require('node:crypto');
|
|
24
|
+
const { resolveRuntimePin, compareRuntimeVersions, isRuntimePinTrusted } = require('../scripts/runtime-pin.js');
|
|
25
|
+
const { existsSync, realpathSync, statSync } = require('node:fs');
|
|
26
|
+
const { basename, dirname, join, resolve } = require('node:path');
|
|
23
27
|
const { homedir, platform } = require('node:os');
|
|
24
28
|
|
|
25
|
-
const { version } = require('../package.json');
|
|
29
|
+
const { name: packageName, version } = require('../package.json');
|
|
30
|
+
|
|
31
|
+
// `codeledger-mcp` bin alias (same file, no extra JS): for MCP registries
|
|
32
|
+
// that cannot pass arguments, it always runs `mcp start` + the user's args.
|
|
33
|
+
// Every other invocation forwards argv unchanged, including a bare launch,
|
|
34
|
+
// so the CLI's own bare-launch MCP detection applies.
|
|
35
|
+
const MCP_ALIAS = /^codeledger-mcp(\.c?js)?$/i.test(basename(process.argv[1] || ''));
|
|
36
|
+
const ARGS = MCP_ALIAS ? ['mcp', 'start', ...process.argv.slice(2)] : process.argv.slice(2);
|
|
26
37
|
|
|
27
38
|
const CACHE_DIR =
|
|
28
39
|
process.env.CODELEDGER_CACHE_DIR ||
|
|
@@ -40,6 +51,34 @@ function die(msg, code = 1) {
|
|
|
40
51
|
process.exit(code);
|
|
41
52
|
}
|
|
42
53
|
|
|
54
|
+
// Repair commands use the installed version, so an old pin cannot trap an upgrade.
|
|
55
|
+
function repairing() {
|
|
56
|
+
const commands = [];
|
|
57
|
+
for (let i = 0; i < ARGS.length && ARGS[i] !== '--'; i++) {
|
|
58
|
+
if (ARGS[i] === '--cwd') { i++; continue; }
|
|
59
|
+
if (!ARGS[i].startsWith('-')) commands.push(ARGS[i]);
|
|
60
|
+
}
|
|
61
|
+
return ['vendor', 'upgrade', 'update', 'init'].includes(commands[0]);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function findPinnedRuntime(startDir) {
|
|
65
|
+
if (process.env.CODELEDGER_GLOBAL_VERSION_PROBE === '1' || repairing()) return null;
|
|
66
|
+
let root = resolve(startDir);
|
|
67
|
+
while (true) {
|
|
68
|
+
const pin = resolveRuntimePin(join(root, '.codeledger'), { fs, path, crypto }, compareRuntimeVersions);
|
|
69
|
+
if (pin) {
|
|
70
|
+
const trustDir = process.env.CODELEDGER_RUNTIME_TRUST_DIR || join(homedir(), '.cache', 'codeledger', 'runtime-trust');
|
|
71
|
+
if (isRuntimePinTrusted(root, pin.manifest, { fs, path, crypto }, trustDir)) return { kind: 'standalone', path: pin.path, repoRoot: root };
|
|
72
|
+
process.stderr.write('codeledger: repository runtime has no installed trust receipt; using the global installation. Run the installed codeledger vendor command to install and trust its verified runtime.\n');
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
if (existsSync(join(root, '.git'))) return null;
|
|
76
|
+
const parent = dirname(root);
|
|
77
|
+
if (parent === root) return null;
|
|
78
|
+
root = parent;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
43
82
|
// Repo-local fallback: an already-`codeledger init`'d repo vendors its own
|
|
44
83
|
// runtime under .codeledger/bin/. Checked before attempting a network
|
|
45
84
|
// download since it's instant and needs no connectivity — the global cache
|
|
@@ -49,10 +88,14 @@ function findRepoLocalRuntime(startDir) {
|
|
|
49
88
|
if (process.env.CODELEDGER_GLOBAL_VERSION_PROBE === '1') return null;
|
|
50
89
|
let current = resolve(startDir);
|
|
51
90
|
while (true) {
|
|
91
|
+
if (existsSync(join(current, '.codeledger', 'runtime.json'))) return null;
|
|
92
|
+
// Legacy scripts require an explicit environment-level repository trust decision.
|
|
93
|
+
if (process.env.CODELEDGER_TRUST_LEGACY_RUNTIME !== '1') return null;
|
|
52
94
|
const wrapper = join(current, '.codeledger', 'bin', 'codeledger');
|
|
53
95
|
const standalone = join(current, '.codeledger', 'bin', 'codeledger-standalone.cjs');
|
|
54
96
|
if (existsSync(wrapper)) return { kind: 'wrapper', path: wrapper, repoRoot: current };
|
|
55
97
|
if (existsSync(standalone)) return { kind: 'standalone', path: standalone, repoRoot: current };
|
|
98
|
+
if (existsSync(join(current, '.git'))) return null;
|
|
56
99
|
const parent = dirname(current);
|
|
57
100
|
if (parent === current) return null;
|
|
58
101
|
current = parent;
|
|
@@ -62,18 +105,18 @@ function findRepoLocalRuntime(startDir) {
|
|
|
62
105
|
function runRepoLocal(runtime) {
|
|
63
106
|
process.stderr.write(
|
|
64
107
|
[
|
|
65
|
-
`codeledger:
|
|
108
|
+
`codeledger: using the repository runtime instead of the global v${version} installation.`,
|
|
66
109
|
`codeledger: using repo-local runtime at ${runtime.path}`,
|
|
67
110
|
'',
|
|
68
111
|
].join('\n'),
|
|
69
112
|
);
|
|
70
113
|
const command = runtime.kind === 'standalone' ? process.execPath : runtime.path;
|
|
71
114
|
const args = runtime.kind === 'standalone'
|
|
72
|
-
? [runtime.path, ...
|
|
73
|
-
:
|
|
115
|
+
? [runtime.path, ...ARGS]
|
|
116
|
+
: ARGS;
|
|
74
117
|
const result = spawnSync(command, args, {
|
|
75
118
|
stdio: 'inherit',
|
|
76
|
-
cwd:
|
|
119
|
+
cwd: process.cwd(),
|
|
77
120
|
env: { ...process.env, CODELEDGER_DELEGATED: '1' },
|
|
78
121
|
});
|
|
79
122
|
if (result.error) {
|
|
@@ -88,9 +131,37 @@ function runRepoLocal(runtime) {
|
|
|
88
131
|
// install step.
|
|
89
132
|
const ON_DEMAND_DEADLINE_MS = 30_000;
|
|
90
133
|
|
|
134
|
+
function launchDirectory() {
|
|
135
|
+
const args = ARGS;
|
|
136
|
+
let target;
|
|
137
|
+
for (let i = 0; i < args.length && args[i] !== '--'; i++) {
|
|
138
|
+
if (args[i].startsWith('--cwd=')) target = args[i].slice(6);
|
|
139
|
+
else if (args[i] === '--cwd') {
|
|
140
|
+
target = args[++i];
|
|
141
|
+
if (!target || target.startsWith('--')) die('--cwd requires a repository directory.', 2);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (target === undefined && (args[0] === 'mcp' || (args.length === 0 && !process.stdin.isTTY))) target = process.env.CODELEDGER_REPO_ROOT;
|
|
145
|
+
if (target !== undefined && !target.trim()) die('Repository target cannot be empty.', 2);
|
|
146
|
+
try {
|
|
147
|
+
const root = realpathSync(resolve(target ?? process.cwd()));
|
|
148
|
+
if (!statSync(root).isDirectory()) throw new Error('Not a directory');
|
|
149
|
+
return root;
|
|
150
|
+
} catch { die('Repository target must be an existing directory. Check --cwd or CODELEDGER_REPO_ROOT.', 2); }
|
|
151
|
+
}
|
|
152
|
+
|
|
91
153
|
async function main() {
|
|
154
|
+
const pinned = findPinnedRuntime(launchDirectory());
|
|
155
|
+
if (pinned) runRepoLocal(pinned);
|
|
156
|
+
if (existsSync(BINARY_PATH)) {
|
|
157
|
+
const problem = require('../scripts/postinstall.js').verifyCachedBinary(BINARY_PATH);
|
|
158
|
+
if (problem) {
|
|
159
|
+
process.stderr.write(`codeledger: cached binary at ${BINARY_PATH} failed verification (${problem}); discarding it and downloading a verified copy.\n`);
|
|
160
|
+
try { fs.unlinkSync(BINARY_PATH); } catch (error) { die(`could not remove the unverified cached binary: ${error.message}. Delete ${BINARY_PATH} and retry.`); }
|
|
161
|
+
}
|
|
162
|
+
}
|
|
92
163
|
if (!existsSync(BINARY_PATH)) {
|
|
93
|
-
const repoLocal = findRepoLocalRuntime(
|
|
164
|
+
const repoLocal = repairing() ? null : findRepoLocalRuntime(launchDirectory());
|
|
94
165
|
if (repoLocal) {
|
|
95
166
|
runRepoLocal(repoLocal);
|
|
96
167
|
}
|
|
@@ -99,80 +170,52 @@ async function main() {
|
|
|
99
170
|
const platformKey = `${platform()}-${arch()}`;
|
|
100
171
|
const installerPath = join(__dirname, '..', 'scripts', 'postinstall.js');
|
|
101
172
|
|
|
102
|
-
|
|
103
|
-
die(
|
|
104
|
-
[
|
|
105
|
-
`ContextECF CodeLedger hardened binary for v${version} not found at ${BINARY_PATH}.`,
|
|
106
|
-
'',
|
|
107
|
-
'You are on an Intel Mac (darwin-x64). Pre-built binaries are',
|
|
108
|
-
'available for Apple Silicon (darwin-arm64) only.',
|
|
109
|
-
'',
|
|
110
|
-
'Options:',
|
|
111
|
-
' 1. Use Rosetta 2 (recommended):',
|
|
112
|
-
' arch -arm64 npm install -g @codeledger/cli@latest',
|
|
113
|
-
' 2. If this repo was already initialized, use the vendored CLI:',
|
|
114
|
-
' ./.codeledger/bin/codeledger ready',
|
|
115
|
-
' node .codeledger/bin/codeledger-standalone.cjs ready',
|
|
116
|
-
' 3. Update CodeLedger, then use the vendored standalone CLI:',
|
|
117
|
-
' npm install -g @codeledger/cli@latest',
|
|
118
|
-
' codeledger init # in your repo, sets up vendored Node.js-based CLI',
|
|
119
|
-
' ./.codeledger/bin/codeledger --version',
|
|
120
|
-
' 4. Download a binary manually from:',
|
|
121
|
-
` https://github.com/codeledgerECF/codeledger/releases/tag/v${version}`,
|
|
122
|
-
].join('\n'),
|
|
123
|
-
);
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
const { PLATFORM_MAP, downloadAndVerifyBinary } = require('../scripts/postinstall.js');
|
|
173
|
+
const { PLATFORM_MAP, downloadAndVerifyBinary, unsupportedPlatformMessage, readInstallFailure, unpublishedAssetsMessage } = require('../scripts/postinstall.js');
|
|
127
174
|
if (!PLATFORM_MAP[platformKey]) {
|
|
128
175
|
// Don't waste time on a download attempt that can only ever fail —
|
|
129
176
|
// getBinaryPaths() would reject this platformKey immediately anyway.
|
|
130
177
|
// See postinstall.js's matching message for why this is "no
|
|
131
178
|
// committed timeline", not "try again later".
|
|
132
|
-
die(
|
|
133
|
-
[
|
|
134
|
-
`${platformKey} is not currently supported by the hardened binary.`,
|
|
135
|
-
`Supported: ${Object.keys(PLATFORM_MAP).join(', ')}. No committed timeline for ${platformKey} support.`,
|
|
136
|
-
'',
|
|
137
|
-
'Use the vendored standalone CLI instead (pure Node.js, no native binary):',
|
|
138
|
-
' CODELEDGER_SKIP_POSTINSTALL=1 npm install -g @codeledger/cli@latest',
|
|
139
|
-
' codeledger init # sets up the vendored Node.js-based CLI',
|
|
140
|
-
' ./.codeledger/bin/codeledger --version',
|
|
141
|
-
'',
|
|
142
|
-
`Track or request ${platformKey} support: https://github.com/codeledgerECF/codeledger/issues`,
|
|
143
|
-
].join('\n'),
|
|
144
|
-
);
|
|
179
|
+
die(unsupportedPlatformMessage(platformKey));
|
|
145
180
|
}
|
|
146
181
|
|
|
182
|
+
const priorFailure = readInstallFailure();
|
|
183
|
+
if (priorFailure) {
|
|
184
|
+
process.stderr.write(`codeledger: the install step could not fetch the hardened binary (${priorFailure.at}): ${priorFailure.message}\n`);
|
|
185
|
+
}
|
|
147
186
|
process.stderr.write(
|
|
148
187
|
`codeledger: hardened binary for v${version} not cached locally — downloading now (one-time)...\n`,
|
|
149
188
|
);
|
|
150
189
|
try {
|
|
151
190
|
await downloadAndVerifyBinary({ deadlineMs: ON_DEMAND_DEADLINE_MS });
|
|
152
191
|
} catch (err) {
|
|
192
|
+
const unpublished = unpublishedAssetsMessage(err);
|
|
153
193
|
die(
|
|
154
194
|
[
|
|
155
195
|
`hardened binary for v${version} not found at ${BINARY_PATH}, and the on-demand download just failed: ${err.message}`,
|
|
156
|
-
'',
|
|
157
|
-
|
|
196
|
+
...(unpublished ? ['', unpublished,
|
|
197
|
+
'Retrying or reinstalling this version will not help until they are published.',
|
|
198
|
+
'To use a published version instead, list them with: npm view @codeledger/cli versions'] : [
|
|
199
|
+
'',
|
|
200
|
+
'The postinstall step may have been skipped (e.g. --ignore-scripts).']),
|
|
158
201
|
'Confirm the official scoped package is installed: @codeledger/cli.',
|
|
159
202
|
'Avoid the unrelated unscoped npm package: codeledger.',
|
|
160
203
|
'',
|
|
161
204
|
'Recover with one of:',
|
|
162
205
|
' 1. Retry: codeledger --version',
|
|
163
|
-
|
|
206
|
+
` 2. Reinstall this version: npm install -g ${packageName}@${version}`,
|
|
164
207
|
` 3. node "${installerPath}"`,
|
|
165
208
|
' 4. Re-run the install without --ignore-scripts',
|
|
166
209
|
' 5. In an initialized repo, use: ./.codeledger/bin/codeledger ready',
|
|
167
210
|
'',
|
|
168
|
-
|
|
211
|
+
`Release page for v${version} (it exists only once that release is published):`,
|
|
169
212
|
` https://github.com/codeledgerECF/codeledger/releases/tag/v${version}`,
|
|
170
213
|
].join('\n'),
|
|
171
214
|
);
|
|
172
215
|
}
|
|
173
216
|
}
|
|
174
217
|
|
|
175
|
-
const result = spawnSync(BINARY_PATH,
|
|
218
|
+
const result = spawnSync(BINARY_PATH, ARGS, {
|
|
176
219
|
stdio: 'inherit',
|
|
177
220
|
env: process.env,
|
|
178
221
|
});
|
|
@@ -184,4 +227,4 @@ async function main() {
|
|
|
184
227
|
process.exit(result.status ?? 1);
|
|
185
228
|
}
|
|
186
229
|
|
|
187
|
-
main();
|
|
230
|
+
main().catch((error) => die(error.message));
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codeledger/cli",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.82",
|
|
4
4
|
"mcpName": "io.github.codeledgerECF/codeledger",
|
|
5
5
|
"description": "Official ContextECF CodeLedger CLI wrapper. Installs the hardened binary from GitHub Releases; zero engine code ships in this package.",
|
|
6
6
|
"type": "commonjs",
|
|
7
7
|
"bin": {
|
|
8
|
-
"codeledger": "./bin/codeledger.js"
|
|
8
|
+
"codeledger": "./bin/codeledger.js",
|
|
9
|
+
"codeledger-mcp": "./bin/codeledger.js"
|
|
9
10
|
},
|
|
10
11
|
"files": [
|
|
11
12
|
"bin/",
|
|
@@ -17,7 +18,7 @@
|
|
|
17
18
|
],
|
|
18
19
|
"dependencies": {},
|
|
19
20
|
"devDependencies": {
|
|
20
|
-
"vitest": "^4.1.
|
|
21
|
+
"vitest": "^4.1.12"
|
|
21
22
|
},
|
|
22
23
|
"engines": {
|
|
23
24
|
"node": ">=18"
|
package/scripts/postinstall.js
CHANGED
|
@@ -42,6 +42,8 @@ const {
|
|
|
42
42
|
chmodSync,
|
|
43
43
|
existsSync,
|
|
44
44
|
unlinkSync,
|
|
45
|
+
readFileSync,
|
|
46
|
+
statSync,
|
|
45
47
|
} = require('node:fs');
|
|
46
48
|
const { join } = require('node:path');
|
|
47
49
|
const { homedir, platform, arch } = require('node:os');
|
|
@@ -50,14 +52,26 @@ const { version } = require('../package.json');
|
|
|
50
52
|
|
|
51
53
|
// ─── platform / path resolution (pure — no I/O, no process.exit) ──────────
|
|
52
54
|
|
|
53
|
-
//
|
|
54
|
-
// release CI plan as of 2026-04-09. Re-add when a working Intel Mac binary
|
|
55
|
-
// is available.
|
|
55
|
+
// Only these native asset names are wired into this installer.
|
|
56
56
|
const PLATFORM_MAP = {
|
|
57
57
|
'darwin-arm64': 'darwin-arm64',
|
|
58
58
|
'linux-x64': 'linux-x64',
|
|
59
59
|
};
|
|
60
60
|
|
|
61
|
+
function unsupportedPlatformMessage(platformKey) {
|
|
62
|
+
return [
|
|
63
|
+
`${platformKey} has no pre-built CodeLedger hardened binary.`,
|
|
64
|
+
`Supported native routes: ${Object.keys(PLATFORM_MAP).join(', ')}.`,
|
|
65
|
+
'A successful npm install does not establish a working runtime or MCP connection.',
|
|
66
|
+
'For an already initialized repository with a trusted vendored runtime:',
|
|
67
|
+
' node .codeledger/bin/codeledger-standalone.cjs ready',
|
|
68
|
+
'For a fresh repository, use a supported host or a supported linux-x64 environment.',
|
|
69
|
+
'Skipping postinstall does not bootstrap a missing runtime; codeledger init cannot fix that loop.',
|
|
70
|
+
'Intel Macs cannot run an Apple Silicon binary through Rosetta.',
|
|
71
|
+
'Source-build prerequisites and limitations: https://github.com/codeledgerECF/codeledger/blob/main/docs/security/ENTERPRISE_ASSURANCE.md',
|
|
72
|
+
].join('\n');
|
|
73
|
+
}
|
|
74
|
+
|
|
61
75
|
function getPlatformKey() {
|
|
62
76
|
return `${platform()}-${arch()}`;
|
|
63
77
|
}
|
|
@@ -89,20 +103,92 @@ function getBinaryPaths(platformKey) {
|
|
|
89
103
|
};
|
|
90
104
|
}
|
|
91
105
|
|
|
106
|
+
// The verified SHA-256 is recorded beside the cached binary so every launch can
|
|
107
|
+
// reject a truncated, replaced, or tampered cache before executing it.
|
|
108
|
+
function receiptPath(binaryPath) {
|
|
109
|
+
return `${binaryPath}.sha256.json`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function writeVerifiedReceipt(binaryPath, sha256) {
|
|
113
|
+
const stat = statSync(binaryPath);
|
|
114
|
+
writeFileSync(receiptPath(binaryPath), JSON.stringify({ schema: 1, version, sha256, size: stat.size }) + '\n');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Returns null when the cached binary matches its install receipt, else the reason it does not. */
|
|
118
|
+
function verifyCachedBinary(binaryPath) {
|
|
119
|
+
let receipt;
|
|
120
|
+
try {
|
|
121
|
+
receipt = JSON.parse(readFileSync(receiptPath(binaryPath), 'utf8'));
|
|
122
|
+
} catch {
|
|
123
|
+
return 'no install receipt';
|
|
124
|
+
}
|
|
125
|
+
if (!receipt || receipt.schema !== 1 || receipt.version !== version || !/^[a-f0-9]{64}$/.test(String(receipt.sha256))) return 'invalid install receipt';
|
|
126
|
+
let stat;
|
|
127
|
+
try {
|
|
128
|
+
stat = statSync(binaryPath);
|
|
129
|
+
} catch {
|
|
130
|
+
return 'binary missing';
|
|
131
|
+
}
|
|
132
|
+
if (!stat.isFile() || stat.size === 0) return 'binary is empty or not a file';
|
|
133
|
+
if (stat.size !== receipt.size) return 'binary size changed since install';
|
|
134
|
+
// Hashed on every launch: size or timestamps can be preserved by a same-size replacement.
|
|
135
|
+
const actual = createHash('sha256').update(readFileSync(binaryPath)).digest('hex');
|
|
136
|
+
return actual === receipt.sha256 ? null : 'SHA256 mismatch with install receipt';
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// npm hides postinstall output by default, so a soft failure is recorded where
|
|
140
|
+
// the first `codeledger` run can report it.
|
|
141
|
+
function installFailurePath() {
|
|
142
|
+
return join(getCacheDir(), `install-failure-v${version}.json`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function recordInstallFailure(err) {
|
|
146
|
+
try {
|
|
147
|
+
mkdirSync(getCacheDir(), { recursive: true });
|
|
148
|
+
writeFileSync(installFailurePath(), JSON.stringify({
|
|
149
|
+
schema: 1, version, at: new Date().toISOString(),
|
|
150
|
+
status: typeof err.statusCode === 'number' ? err.statusCode : null,
|
|
151
|
+
message: String(err.message).split('\n')[0].slice(0, 300),
|
|
152
|
+
}) + '\n');
|
|
153
|
+
} catch { /* Reporting is best effort; the install stays a soft failure. */ }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function readInstallFailure() {
|
|
157
|
+
try {
|
|
158
|
+
const record = JSON.parse(readFileSync(installFailurePath(), 'utf8'));
|
|
159
|
+
return record && record.schema === 1 && record.version === version ? record : null;
|
|
160
|
+
} catch {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function clearInstallFailure() {
|
|
166
|
+
try { unlinkSync(installFailurePath()); } catch { /* Nothing recorded. */ }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** A 404 after the propagation window means this version's release assets are not published. */
|
|
170
|
+
function unpublishedAssetsMessage(err) {
|
|
171
|
+
return err && err.statusCode === 404
|
|
172
|
+
? `The v${version} release assets were not found (HTTP 404): this version's hardened binaries are not published yet, or were withdrawn.`
|
|
173
|
+
: null;
|
|
174
|
+
}
|
|
175
|
+
|
|
92
176
|
function isBinaryCached() {
|
|
93
177
|
const paths = getBinaryPaths(getPlatformKey());
|
|
94
|
-
return Boolean(paths && existsSync(paths.binaryLocalPath));
|
|
178
|
+
return Boolean(paths && existsSync(paths.binaryLocalPath) && verifyCachedBinary(paths.binaryLocalPath) === null);
|
|
95
179
|
}
|
|
96
180
|
|
|
97
181
|
// ─── http ────────────────────────────────────────────────────────────────────
|
|
98
182
|
|
|
99
183
|
const FETCH_TIMEOUT_MS = 60_000;
|
|
100
184
|
|
|
101
|
-
function fetchBufferOnce(url, redirectDepth = 0) {
|
|
185
|
+
function fetchBufferOnce(url, redirectDepth = 0, expiresAt = Date.now() + FETCH_TIMEOUT_MS) {
|
|
102
186
|
if (redirectDepth > 5) {
|
|
103
187
|
return Promise.reject(new Error(`too many redirects fetching ${url}`));
|
|
104
188
|
}
|
|
105
189
|
return new Promise((resolve, reject) => {
|
|
190
|
+
const remaining = Math.min(FETCH_TIMEOUT_MS, expiresAt - Date.now());
|
|
191
|
+
if (remaining <= 0) { reject(new Error('Binary download deadline exceeded.')); return; }
|
|
106
192
|
const req = https.get(
|
|
107
193
|
url,
|
|
108
194
|
{
|
|
@@ -122,7 +208,7 @@ function fetchBufferOnce(url, redirectDepth = 0) {
|
|
|
122
208
|
) {
|
|
123
209
|
res.resume();
|
|
124
210
|
const next = new URL(res.headers.location, url).toString();
|
|
125
|
-
fetchBufferOnce(next, redirectDepth + 1).then(resolve, reject);
|
|
211
|
+
fetchBufferOnce(next, redirectDepth + 1, expiresAt).then(resolve, reject);
|
|
126
212
|
return;
|
|
127
213
|
}
|
|
128
214
|
if (res.statusCode !== 200) {
|
|
@@ -138,10 +224,13 @@ function fetchBufferOnce(url, redirectDepth = 0) {
|
|
|
138
224
|
res.on('error', reject);
|
|
139
225
|
},
|
|
140
226
|
);
|
|
227
|
+
const timer = setTimeout(() => {
|
|
228
|
+
const error = new Error('Binary download deadline exceeded.');
|
|
229
|
+
req.destroy(error);
|
|
230
|
+
reject(error);
|
|
231
|
+
}, remaining);
|
|
141
232
|
req.on('error', reject);
|
|
142
|
-
req.
|
|
143
|
-
req.destroy(new Error(`timeout fetching ${url}`));
|
|
144
|
-
});
|
|
233
|
+
req.once('close', () => clearTimeout(timer));
|
|
145
234
|
});
|
|
146
235
|
}
|
|
147
236
|
|
|
@@ -165,7 +254,7 @@ async function fetchBuffer(url, deadlineMs = DEFAULT_DEADLINE_MS) {
|
|
|
165
254
|
let lastErr;
|
|
166
255
|
for (;;) {
|
|
167
256
|
try {
|
|
168
|
-
return await fetchBufferOnce(url);
|
|
257
|
+
return await fetchBufferOnce(url, 0, start + deadlineMs);
|
|
169
258
|
} catch (err) {
|
|
170
259
|
lastErr = err;
|
|
171
260
|
// Only retry on 404 — everything else is a hard failure.
|
|
@@ -175,7 +264,7 @@ async function fetchBuffer(url, deadlineMs = DEFAULT_DEADLINE_MS) {
|
|
|
175
264
|
if (elapsed + wait >= deadlineMs) break;
|
|
176
265
|
attempt += 1;
|
|
177
266
|
const remainingSec = Math.round((deadlineMs - elapsed) / 1000);
|
|
178
|
-
console.
|
|
267
|
+
console.error(
|
|
179
268
|
`codeledger: Binary pending — retrying in ${Math.round(wait / 1000)}s ` +
|
|
180
269
|
`(${remainingSec}s left in propagation window).`,
|
|
181
270
|
);
|
|
@@ -219,8 +308,8 @@ async function downloadAndVerifyBinary({ deadlineMs = DEFAULT_DEADLINE_MS } = {}
|
|
|
219
308
|
throw new Error(`unsupported platform ${platformKey}`);
|
|
220
309
|
}
|
|
221
310
|
|
|
222
|
-
console.
|
|
223
|
-
console.
|
|
311
|
+
console.error(`codeledger: installing v${version} hardened binary for ${platformKey}`);
|
|
312
|
+
console.error(` source: ${paths.binaryUrl}`);
|
|
224
313
|
|
|
225
314
|
const [checksumsBuf, binary] = await Promise.all([
|
|
226
315
|
fetchBuffer(paths.checksumsUrl, deadlineMs),
|
|
@@ -251,9 +340,11 @@ async function downloadAndVerifyBinary({ deadlineMs = DEFAULT_DEADLINE_MS } = {}
|
|
|
251
340
|
chmodSync(tmpPath, 0o755);
|
|
252
341
|
if (existsSync(paths.binaryLocalPath)) unlinkSync(paths.binaryLocalPath);
|
|
253
342
|
require('node:fs').renameSync(tmpPath, paths.binaryLocalPath);
|
|
343
|
+
writeVerifiedReceipt(paths.binaryLocalPath, actualSha);
|
|
344
|
+
clearInstallFailure();
|
|
254
345
|
|
|
255
|
-
console.
|
|
256
|
-
console.
|
|
346
|
+
console.error(`codeledger: installed ${paths.binaryLocalPath}`);
|
|
347
|
+
console.error(` sha256: ${actualSha}`);
|
|
257
348
|
|
|
258
349
|
return paths.binaryLocalPath;
|
|
259
350
|
}
|
|
@@ -271,16 +362,16 @@ function maybeRunUpgrade() {
|
|
|
271
362
|
const homeCwd = process.env['HOME'] ?? process.env['USERPROFILE'] ?? process.cwd();
|
|
272
363
|
const upgradeCwd =
|
|
273
364
|
initCwd && fs.existsSync(path.join(initCwd, '.codeledger')) ? initCwd : homeCwd;
|
|
274
|
-
console.
|
|
365
|
+
console.error('codeledger: CODELEDGER_RUN_UPGRADE=1 set, running upgrade...');
|
|
275
366
|
const upgradeResult = spawnSync(process.execPath, [codeledgerBin, 'upgrade'], {
|
|
276
367
|
stdio: 'inherit',
|
|
277
368
|
cwd: upgradeCwd,
|
|
278
369
|
env: { ...process.env, CODELEDGER_SKIP_AMBIENT_ACTIVATION: '1' },
|
|
279
370
|
});
|
|
280
371
|
if ((upgradeResult.status ?? 0) !== 0) {
|
|
281
|
-
console.
|
|
282
|
-
console.
|
|
283
|
-
console.
|
|
372
|
+
console.error('');
|
|
373
|
+
console.error('codeledger: upgrade step encountered an issue. Run manually:');
|
|
374
|
+
console.error(' codeledger upgrade');
|
|
284
375
|
}
|
|
285
376
|
}
|
|
286
377
|
}
|
|
@@ -293,7 +384,7 @@ function maybeRunUpgrade() {
|
|
|
293
384
|
|
|
294
385
|
async function runPostinstall() {
|
|
295
386
|
if (process.env.CODELEDGER_SKIP_POSTINSTALL === '1') {
|
|
296
|
-
console.
|
|
387
|
+
console.error(
|
|
297
388
|
'codeledger: CODELEDGER_SKIP_POSTINSTALL=1 set, skipping ContextECF CodeLedger hardened binary download.',
|
|
298
389
|
);
|
|
299
390
|
return;
|
|
@@ -308,7 +399,7 @@ async function runPostinstall() {
|
|
|
308
399
|
const fs = require('node:fs');
|
|
309
400
|
const workspaceRoot = path.resolve(__dirname, '..', '..', '..');
|
|
310
401
|
if (fs.existsSync(path.join(workspaceRoot, 'pnpm-workspace.yaml'))) {
|
|
311
|
-
console.
|
|
402
|
+
console.error(
|
|
312
403
|
'codeledger: in-workspace dev install detected, skipping ContextECF CodeLedger hardened binary download.',
|
|
313
404
|
);
|
|
314
405
|
return;
|
|
@@ -319,56 +410,19 @@ async function runPostinstall() {
|
|
|
319
410
|
|
|
320
411
|
const platformKey = getPlatformKey();
|
|
321
412
|
|
|
322
|
-
if (platformKey === 'darwin-x64') {
|
|
323
|
-
console.log('');
|
|
324
|
-
console.log('codeledger: ContextECF CodeLedger Intel Mac (darwin-x64) detected.');
|
|
325
|
-
console.log('codeledger: Pre-built binaries are available for Apple Silicon (darwin-arm64) only.');
|
|
326
|
-
console.log('');
|
|
327
|
-
console.log('Options:');
|
|
328
|
-
console.log(' Official package: @codeledger/cli. Avoid unrelated unscoped package: codeledger.');
|
|
329
|
-
console.log(' 1. Use Rosetta 2 (recommended):');
|
|
330
|
-
console.log(' arch -arm64 npm install -g @codeledger/cli@latest');
|
|
331
|
-
console.log(' 2. If this repo was already initialized, use the vendored CLI:');
|
|
332
|
-
console.log(' ./.codeledger/bin/codeledger ready');
|
|
333
|
-
console.log(' node .codeledger/bin/codeledger-standalone.cjs ready');
|
|
334
|
-
console.log(' 3. Use the vendored standalone CLI after init:');
|
|
335
|
-
console.log(' CODELEDGER_SKIP_POSTINSTALL=1 npm install -g @codeledger/cli@latest');
|
|
336
|
-
console.log(' codeledger init # sets up vendored Node.js-based CLI');
|
|
337
|
-
console.log(' 4. Download a binary manually from:');
|
|
338
|
-
console.log(` https://github.com/codeledgerECF/codeledger/releases/tag/v${version}`);
|
|
339
|
-
console.log('');
|
|
340
|
-
return;
|
|
341
|
-
}
|
|
342
|
-
|
|
343
413
|
if (!PLATFORM_MAP[platformKey]) {
|
|
344
|
-
//
|
|
345
|
-
|
|
346
|
-
// in the release pipeline at all and no committed timeline to add one.
|
|
347
|
-
// Say that plainly rather than implying support is imminent — the
|
|
348
|
-
// vendored standalone CLI (pure Node.js, no native binary) works on any
|
|
349
|
-
// platform Node itself runs on, so there IS a real path forward, just
|
|
350
|
-
// not the hardened-binary one.
|
|
351
|
-
console.error('');
|
|
352
|
-
console.error(`codeledger: ${platformKey} is not currently supported by the hardened binary.`);
|
|
353
|
-
console.error(`codeledger: Supported: ${Object.keys(PLATFORM_MAP).join(', ')}. No committed timeline for ${platformKey} support.`);
|
|
354
|
-
console.error('codeledger: this installer is for ContextECF CodeLedger (@codeledger/cli).');
|
|
355
|
-
console.error('');
|
|
356
|
-
console.error('Use the vendored standalone CLI instead (pure Node.js, no native binary):');
|
|
357
|
-
console.error(' CODELEDGER_SKIP_POSTINSTALL=1 npm install -g @codeledger/cli@latest');
|
|
358
|
-
console.error(' codeledger init # sets up the vendored Node.js-based CLI');
|
|
359
|
-
console.error(' ./.codeledger/bin/codeledger --version');
|
|
360
|
-
console.error('');
|
|
361
|
-
console.error(`Track or request ${platformKey} support: https://github.com/codeledgerECF/codeledger/issues`);
|
|
414
|
+
// Soft install failure does not create a fresh runtime on this platform.
|
|
415
|
+
console.error(`codeledger: ${unsupportedPlatformMessage(platformKey)}`);
|
|
362
416
|
return;
|
|
363
417
|
}
|
|
364
418
|
|
|
365
419
|
try {
|
|
366
420
|
await downloadAndVerifyBinary();
|
|
367
|
-
console.
|
|
368
|
-
console.
|
|
369
|
-
console.
|
|
370
|
-
console.
|
|
371
|
-
console.
|
|
421
|
+
console.error('');
|
|
422
|
+
console.error('codeledger: install complete.');
|
|
423
|
+
console.error(' Next: cd your-repo && codeledger ready');
|
|
424
|
+
console.error(' Existing repos can refresh ambient hooks/runtime with: codeledger upgrade');
|
|
425
|
+
console.error('codeledger: ready initializes, scans, and prepares ambient task context.');
|
|
372
426
|
maybeRunUpgrade();
|
|
373
427
|
} catch (err) {
|
|
374
428
|
// Soft-fail, deliberately: exit 0 either way. A failed postinstall
|
|
@@ -376,9 +430,12 @@ async function runPostinstall() {
|
|
|
376
430
|
// existing working install (the exact incident this is designed
|
|
377
431
|
// around). bin/codeledger.js retries this same download on-demand,
|
|
378
432
|
// synchronously, the first time it's actually needed.
|
|
379
|
-
|
|
380
|
-
console.
|
|
381
|
-
|
|
433
|
+
recordInstallFailure(err);
|
|
434
|
+
console.error(`codeledger: could not pre-fetch the hardened binary — ${err.message}`);
|
|
435
|
+
const unpublished = unpublishedAssetsMessage(err);
|
|
436
|
+
if (unpublished) console.error(`codeledger: ${unpublished}`);
|
|
437
|
+
console.error('codeledger: not fatal — it will download automatically on first "codeledger" invocation.');
|
|
438
|
+
console.error('codeledger: or, in an initialized repo, use: ./.codeledger/bin/codeledger ready');
|
|
382
439
|
}
|
|
383
440
|
}
|
|
384
441
|
|
|
@@ -397,4 +454,10 @@ module.exports = {
|
|
|
397
454
|
getPlatformKey,
|
|
398
455
|
getBinaryPaths,
|
|
399
456
|
isBinaryCached,
|
|
457
|
+
unsupportedPlatformMessage,
|
|
458
|
+
verifyCachedBinary,
|
|
459
|
+
writeVerifiedReceipt,
|
|
460
|
+
readInstallFailure,
|
|
461
|
+
recordInstallFailure,
|
|
462
|
+
unpublishedAssetsMessage,
|
|
400
463
|
};
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/* Generated by scripts/generate-runtime-resolver.mjs. Public installation contract only. */
|
|
2
|
+
'use strict';
|
|
3
|
+
module.exports = (() => {
|
|
4
|
+
/** Strict SemVer 2.0, shared by pin validation and explicit installation. */
|
|
5
|
+
function parseRuntimeVersion(value) {
|
|
6
|
+
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(value);
|
|
7
|
+
if (!match || match[0] !== value) throw new Error(`Invalid runtime version: ${value}. Use an exact semantic version.`);
|
|
8
|
+
const core = match.slice(1, 4).map(Number);
|
|
9
|
+
const prerelease = match[4]?.split('.') ?? [];
|
|
10
|
+
if (core.some((n) => !Number.isSafeInteger(n)) || prerelease.some((p) => /^\d+$/.test(p) && (p.length > 1 && p.startsWith('0')))) {
|
|
11
|
+
throw new Error(`Invalid runtime version: ${value}`);
|
|
12
|
+
}
|
|
13
|
+
return { core, prerelease };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function compareRuntimeVersions(left, right) {
|
|
17
|
+
const a = parseRuntimeVersion(left);
|
|
18
|
+
const b = parseRuntimeVersion(right);
|
|
19
|
+
for (let i = 0; i < 3; i++) {
|
|
20
|
+
if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
|
|
21
|
+
}
|
|
22
|
+
if (!a.prerelease.length || !b.prerelease.length) {
|
|
23
|
+
return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length ? -1 : 1;
|
|
24
|
+
}
|
|
25
|
+
for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i++) {
|
|
26
|
+
const x = a.prerelease[i];
|
|
27
|
+
const y = b.prerelease[i];
|
|
28
|
+
if (x === y) continue;
|
|
29
|
+
if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
|
|
30
|
+
const xn = /^\d+$/.test(x);
|
|
31
|
+
const yn = /^\d+$/.test(y);
|
|
32
|
+
if (xn && yn) return x.length !== y.length ? (x.length < y.length ? -1 : 1) : x < y ? -1 : 1;
|
|
33
|
+
if (xn !== yn) return xn ? -1 : 1;
|
|
34
|
+
return x < y ? -1 : 1;
|
|
35
|
+
}
|
|
36
|
+
return 0;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function runtimeGenerationSha256(bytes, notices, crypto) {
|
|
40
|
+
return crypto.createHash('sha256').update(String(bytes.length) + ':').update(bytes).update(notices === null ? '-1:' : String(notices.length) + ':').update(notices || Buffer.alloc(0)).digest('hex');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function resolveRuntimePin(
|
|
44
|
+
codeledgerDir,
|
|
45
|
+
io,
|
|
46
|
+
compare,
|
|
47
|
+
) {
|
|
48
|
+
const manifestPath = io.path.join(codeledgerDir, 'runtime.json');
|
|
49
|
+
if (!io.fs.existsSync(manifestPath)) return null;
|
|
50
|
+
if (io.fs.lstatSync(codeledgerDir).isSymbolicLink() || io.fs.lstatSync(manifestPath).isSymbolicLink()) throw new Error('Runtime state must not be symlinked. Run codeledger vendor from the owning repository.');
|
|
51
|
+
if (io.fs.statSync(manifestPath).size > 65536) throw new Error('runtime.json exceeds its 64 KiB contract bound. Repair with codeledger vendor.');
|
|
52
|
+
let raw;
|
|
53
|
+
try { raw = JSON.parse(io.fs.readFileSync(manifestPath, 'utf8')); } catch (error) { throw new Error('.codeledger/runtime.json is not valid JSON (' + error.message + '). Restore it from version control, or repair with codeledger vendor.'); }
|
|
54
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Invalid runtime.json: expected an object. Repair with codeledger vendor.');
|
|
55
|
+
const m = raw;
|
|
56
|
+
if (m.schema_version !== 'codeledger/runtime/v1' || typeof m.installation_id !== 'string' || typeof m.version !== 'string' || typeof m.min_runtime !== 'string'
|
|
57
|
+
|| typeof m.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(m.sha256)
|
|
58
|
+
|| (m.distribution !== 'full' && m.distribution !== 'open') || !['fail-open-v1', 'legacy'].includes(m.hook_contract)
|
|
59
|
+
|| !m.source || typeof m.source.kind !== 'string' || typeof m.source.location !== 'string'
|
|
60
|
+
|| !m.build || m.build.content_sha256 !== m.sha256 || (m.build.revision !== null && typeof m.build.revision !== 'string')
|
|
61
|
+
|| (m.build.source_dirty !== undefined && m.build.source_dirty !== null && typeof m.build.source_dirty !== 'boolean')
|
|
62
|
+
|| (m.build.generation_sha256 === undefined && m.build.legal_sha256 !== undefined)
|
|
63
|
+
|| (m.build.generation_sha256 !== undefined && (typeof m.build.generation_sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(m.build.generation_sha256) || (m.build.legal_sha256 !== null && !/^[a-f0-9]{64}$/.test(m.build.legal_sha256))))
|
|
64
|
+
|| typeof m.entrypoint !== 'string' || m.entrypoint !== `bin/runtime/${m.version}-${m.build.generation_sha256 || m.sha256}/codeledger-standalone.cjs`) {
|
|
65
|
+
throw new Error('Invalid runtime.json contract. Repair with codeledger vendor.');
|
|
66
|
+
}
|
|
67
|
+
for (const reference of [m.previous, m.migration_fallback]) {
|
|
68
|
+
if (reference === undefined) continue;
|
|
69
|
+
if (!reference || typeof reference !== 'object' || !/^[a-f0-9]{64}$/.test(reference.sha256) || typeof reference.entrypoint !== 'string') throw new Error('Invalid previous runtime reference. Repair with codeledger vendor.');
|
|
70
|
+
if (reference.version !== null) compare(reference.version, reference.version);
|
|
71
|
+
const generation = reference.generation_sha256 || reference.sha256;
|
|
72
|
+
if (!/^[a-f0-9]{64}$/.test(generation) || (reference.entrypoint !== `bin/runtime/legacy-${reference.sha256}/codeledger-standalone.cjs` && (reference.version === null || reference.entrypoint !== `bin/runtime/${reference.version}-${generation}/codeledger-standalone.cjs`))) throw new Error('Invalid previous runtime path. Repair with codeledger vendor.');
|
|
73
|
+
}
|
|
74
|
+
if (compare(m.version, m.min_runtime) < 0) throw new Error('Pinned runtime is older than its configuration contract. Run codeledger upgrade.');
|
|
75
|
+
if (compare(m.version, '0.10.82-0') >= 0 && m.build.generation_sha256 === undefined) throw new Error('Runtime generation identity is missing. Repair with codeledger vendor.');
|
|
76
|
+
const root = io.fs.realpathSync(codeledgerDir);
|
|
77
|
+
if (!io.fs.existsSync(io.path.resolve(root, m.entrypoint))) throw new Error('Pinned runtime is missing: .codeledger/' + m.entrypoint + '. Restore it from version control (git checkout -- .codeledger/bin), or repair with codeledger vendor.');
|
|
78
|
+
const runtimePath = io.fs.realpathSync(io.path.resolve(root, m.entrypoint));
|
|
79
|
+
const rel = io.path.relative(root, runtimePath);
|
|
80
|
+
if (rel.startsWith('..') || io.path.isAbsolute(rel) || runtimePath !== io.path.resolve(root, m.entrypoint) || !io.fs.statSync(runtimePath).isFile()) {
|
|
81
|
+
throw new Error('Pinned runtime escapes the repository. Repair with codeledger vendor.');
|
|
82
|
+
}
|
|
83
|
+
const bytes = io.fs.readFileSync(runtimePath);
|
|
84
|
+
if (io.crypto.createHash('sha256').update(bytes).digest('hex') !== m.sha256) {
|
|
85
|
+
throw new Error('Pinned runtime checksum mismatch. Repair with codeledger vendor; do not execute the modified artifact.');
|
|
86
|
+
}
|
|
87
|
+
if (m.build.generation_sha256 !== undefined) {
|
|
88
|
+
let notices = null;
|
|
89
|
+
if (m.build.legal_sha256 !== null) {
|
|
90
|
+
const legal = runtimePath + '.LEGAL.txt';
|
|
91
|
+
if (!io.fs.existsSync(legal)) throw new Error('Pinned notices are missing: ' + legal + '. Restore them from version control, or repair with codeledger vendor.');
|
|
92
|
+
if (io.fs.lstatSync(legal).isSymbolicLink()) throw new Error('Pinned notices must not be symlinked. Repair with codeledger vendor.');
|
|
93
|
+
notices = io.fs.readFileSync(legal);
|
|
94
|
+
if (io.crypto.createHash('sha256').update(notices).digest('hex') !== m.build.legal_sha256) throw new Error('Pinned notices checksum mismatch. Repair with codeledger vendor.');
|
|
95
|
+
}
|
|
96
|
+
if (runtimeGenerationSha256(bytes, notices, io.crypto) !== m.build.generation_sha256) throw new Error('Pinned generation checksum mismatch. Repair with codeledger vendor.');
|
|
97
|
+
}
|
|
98
|
+
const header = bytes.subarray(0, 65536).toString('utf8');
|
|
99
|
+
const version = /^\/\* CODELEDGER_STANDALONE_VERSION:([^\s*]+) \*\//m.exec(header)?.[1];
|
|
100
|
+
const flavor = header.includes('/* CodeLedger Open CLI') ? 'open' : header.includes('/* CodeLedger Standalone CLI') ? 'full' : null;
|
|
101
|
+
if (version !== m.version || flavor !== m.distribution) throw new Error('Pinned runtime version or distribution does not match runtime.json.');
|
|
102
|
+
return { manifest: m, path: runtimePath };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
function runtimeTrustKey(root, manifest, io) {
|
|
107
|
+
return io.crypto.createHash('sha256').update(JSON.stringify([io.fs.realpathSync(root), manifest])).digest('hex');
|
|
108
|
+
}
|
|
109
|
+
function isRuntimePinTrusted(root, manifest, io, trustDir) {
|
|
110
|
+
if (!trustDir || trustDir === 'disabled') return false;
|
|
111
|
+
try {
|
|
112
|
+
const directory = io.fs.realpathSync(trustDir);
|
|
113
|
+
const repo = io.fs.realpathSync(root);
|
|
114
|
+
const relative = io.path.relative(repo, directory);
|
|
115
|
+
if (!relative || (!relative.startsWith('..' + io.path.sep) && relative !== '..' && !io.path.isAbsolute(relative))) return false;
|
|
116
|
+
const key = runtimeTrustKey(root, manifest, io);
|
|
117
|
+
const file = io.path.join(directory, key + '.json');
|
|
118
|
+
const stat = io.fs.lstatSync(file);
|
|
119
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4096) return false;
|
|
120
|
+
const receipt = JSON.parse(io.fs.readFileSync(file, 'utf8'));
|
|
121
|
+
return receipt.schema === 1 && receipt.key === key;
|
|
122
|
+
} catch { return false; }
|
|
123
|
+
}
|
|
124
|
+
return {parseRuntimeVersion, compareRuntimeVersions, resolveRuntimePin, runtimeGenerationSha256, runtimeTrustKey, isRuntimePinTrusted};
|
|
125
|
+
})();
|