@runeditrun/rer 0.2.45 → 0.2.47
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 +80 -0
- package/cli/companion/api.mjs +27 -0
- package/cli/companion/auth.mjs +34 -0
- package/cli/companion/command.mjs +73 -0
- package/cli/companion/commands.mjs +22 -0
- package/cli/companion/event-payload.mjs +7 -0
- package/cli/companion/grants.mjs +30 -0
- package/cli/companion/no-turn-evidence.mjs +49 -0
- package/cli/companion/providers/claude.mjs +31 -0
- package/cli/companion/providers/codex.mjs +55 -0
- package/cli/companion/providers/jsonl-rpc.mjs +95 -0
- package/cli/companion/providers/sandbox.mjs +58 -0
- package/cli/companion/providers/secrets.mjs +36 -0
- package/cli/companion/recovery.mjs +67 -0
- package/cli/companion/runner.mjs +121 -0
- package/cli/companion/setup.mjs +71 -0
- package/cli/companion/state.mjs +10 -0
- package/cli/companion/workspace.mjs +101 -0
- package/cli/main.mjs +1 -0
- package/global/CHANGELOG.md +10 -0
- package/global/README.md +80 -0
- package/global/main.mjs +3 -0
- package/global/run.mjs +2 -1
- package/modules/demo-host/native/visitor.mjs +20 -7
- package/modules/demo-host/worker.mjs +3 -2
- package/onboarding/operator-installer.mjs +1 -1
- package/onboarding/queue.mjs +8 -8
- package/package.json +1 -1
- package/scripts/publish-check/README.md +5 -1
- package/scripts/publish-check/github_refs.py +83 -12
- package/scripts/publish-check/history_scan.py +18 -6
- package/scripts/publish-check/public_hygiene.py +22 -12
- package/scripts/publish-check/tree_scan.py +5 -4
package/README.md
CHANGED
|
@@ -432,3 +432,83 @@ The four deterministic adapter implementations and their native output formats
|
|
|
432
432
|
are described in [the adapter guide](cli/business/vendors/README.md). Their
|
|
433
433
|
presence does not enable export until the seed import authority and remaining
|
|
434
434
|
transport contracts are connected.
|
|
435
|
+
|
|
436
|
+
## Local engineering companion
|
|
437
|
+
|
|
438
|
+
`rer companion` pairs your own computer with a Run Edit Run app, then runs the
|
|
439
|
+
change requests the app sends it with your own Codex or Claude, here. It makes
|
|
440
|
+
outbound HTTPS requests to the app only and opens no local server. It needs
|
|
441
|
+
Node 22 or later; `run` needs macOS, because each provider runs inside a macOS
|
|
442
|
+
`sandbox-exec` boundary. On other systems `run` refuses before it asks the app
|
|
443
|
+
for work: it never runs a provider without that boundary.
|
|
444
|
+
|
|
445
|
+
```sh
|
|
446
|
+
npx -y @runeditrun/rer companion map PROJECT_ID <owner>/<repo> /path/to/your/checkout
|
|
447
|
+
npx -y @runeditrun/rer companion pair https://app.runeditrun.com ABCD-2345
|
|
448
|
+
npx -y @runeditrun/rer companion codex-auth # or: claude-auth
|
|
449
|
+
npx -y @runeditrun/rer companion run
|
|
450
|
+
```
|
|
451
|
+
|
|
452
|
+
With `rer` installed, drop `npx -y @runeditrun/rer`. Run `rer companion --help`
|
|
453
|
+
for every verb.
|
|
454
|
+
|
|
455
|
+
- `map PROJECT_ID <owner>/<repo> CHECKOUT` approves one local Git checkout for an
|
|
456
|
+
app. Its `origin` must be exactly that GitHub repository. `PROJECT_ID` is the
|
|
457
|
+
app's id, shown in the command on its Devices page. On a Managed app, if you
|
|
458
|
+
cloned with the temporary clone URL the app gives you, reset `origin` first
|
|
459
|
+
with `git remote set-url origin https://github.com/<owner>/<repo>.git`: `map`
|
|
460
|
+
refuses a URL that carries a token, and the reset keeps the expired token out
|
|
461
|
+
of your `.git/config`.
|
|
462
|
+
- `pair URL CODE` redeems the one-use code from the app's Devices page (the
|
|
463
|
+
8-character code or the full code; both expire after 10 minutes). The app
|
|
464
|
+
must name the repository you mapped, or this computer stays unpaired.
|
|
465
|
+
`--project ID`, `--provider codex|claude` and `--name NAME` set the rest; in
|
|
466
|
+
a terminal it asks for a missing project (and offers to map it) and provider.
|
|
467
|
+
With exactly one mapped project it uses that one, and the provider defaults
|
|
468
|
+
to `codex`. The earlier form `pair URL CODE PROJECT_ID [PROVIDER] [NAME]`
|
|
469
|
+
still works.
|
|
470
|
+
- `codex-auth [AUTH_FILE]` copies only Codex's `auth.json`
|
|
471
|
+
(`$CODEX_HOME/auth.json`, else `~/.codex/auth.json`) into a dedicated
|
|
472
|
+
executor home. Codex configuration and MCP servers are not imported.
|
|
473
|
+
- `claude-auth` runs Claude Code's own sign-in with the dedicated executor home
|
|
474
|
+
(add `--console` for a Console account). Host Claude configuration and
|
|
475
|
+
history are not copied. To use API billing instead, set
|
|
476
|
+
`RER_COMPANION_ANTHROPIC_API_KEY`; a host-wide `ANTHROPIC_API_KEY` is never
|
|
477
|
+
passed to the provider.
|
|
478
|
+
- `commands PROJECT_ID FILE` approves argv lists for setup and verification,
|
|
479
|
+
for example `{"setup":[["pnpm","install","--frozen-lockfile"]],"verify":[["pnpm","verify"]]}`.
|
|
480
|
+
They run in the same boundary, with network access, a home of their own and
|
|
481
|
+
no provider or deployment credentials. A job from the browser cannot change
|
|
482
|
+
them.
|
|
483
|
+
- `run [--once]` takes jobs from the app and runs them. `status` prints the
|
|
484
|
+
paired device, mapped projects, the active job and pending events, never the
|
|
485
|
+
device key.
|
|
486
|
+
|
|
487
|
+
How a job runs: each job starts from the exact commit the app names, fetched
|
|
488
|
+
into a separate detached checkout with its own Git metadata. Fetch that commit
|
|
489
|
+
into your checkout first. Your branch, index, dirty and untracked files stay
|
|
490
|
+
untouched. Git runs without global or system configuration, hooks or
|
|
491
|
+
templates. The provider (Codex `app-server`, or `claude`) can write only that
|
|
492
|
+
checkout and the dedicated home, and read only them, its own installation and
|
|
493
|
+
the system runtime; other files, including through symlinks, are denied. Its
|
|
494
|
+
environment has no GitHub, Cloudflare or MCP credentials. A request to widen
|
|
495
|
+
that boundary can only be declined from the app; it is never approved
|
|
496
|
+
remotely. Known provider credentials are redacted from relayed progress and
|
|
497
|
+
block a result that contains them. Events wait on disk and are retried with the
|
|
498
|
+
same ids until the app accepts them. A job that was running when the companion
|
|
499
|
+
stopped is never restarted on its own: resume or cancel it from the app. The
|
|
500
|
+
provider's own network access is not fenced.
|
|
501
|
+
|
|
502
|
+
State lives in `~/.rer-local` (`RER_LOCAL_HOME` picks another private folder).
|
|
503
|
+
The device key is stored there in a 0600 file; the app keeps only its hash.
|
|
504
|
+
|
|
505
|
+
**Revoke a device** in the app: Settings › Devices › Revoke. A running
|
|
506
|
+
companion stops at its next request to the app. Then delete the state folder
|
|
507
|
+
on that computer.
|
|
508
|
+
|
|
509
|
+
If setup failed before any provider turn and you have confirmed no provider or
|
|
510
|
+
setup process is still running, `confirm-no-turn-started JOB_ID
|
|
511
|
+
--confirm-no-provider-turn-started` lets the app resume it. It refuses if the
|
|
512
|
+
checkout changed or the provider recorded a session for it. It reads the
|
|
513
|
+
checkout with Git inside the same boundary, because setup could have changed
|
|
514
|
+
the checkout's Git configuration.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// The companion's only network path: outbound HTTPS requests to the management
|
|
2
|
+
// service named at pairing. It listens on nothing.
|
|
3
|
+
import { isIP } from 'node:net';
|
|
4
|
+
// Plain HTTP only to a loopback address literal: a DNS name such as
|
|
5
|
+
// 127.attacker.example is not loopback.
|
|
6
|
+
function loopback(hostname) {
|
|
7
|
+
const host = hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
8
|
+
return host === 'localhost' || host === '::1' || (isIP(host) === 4 && host.startsWith('127.'));
|
|
9
|
+
}
|
|
10
|
+
export function assertServerUrl(raw) {
|
|
11
|
+
let url;
|
|
12
|
+
try { url = new URL(raw); } catch { throw new Error('Server must be an absolute HTTPS URL (or loopback HTTP for local testing).'); }
|
|
13
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback(url.hostname))) throw new Error('Server must use HTTPS. HTTP is allowed only for localhost test servers.');
|
|
14
|
+
if (url.username || url.password || url.hash) throw new Error('Server URL must not include credentials or a fragment.');
|
|
15
|
+
return url.toString().replace(/\/$/, '');
|
|
16
|
+
}
|
|
17
|
+
export class Api {
|
|
18
|
+
constructor(server,token) {this.server=assertServerUrl(server);this.token=token;}
|
|
19
|
+
// A redirect is refused, never followed: the server URL is checked once, here, and a
|
|
20
|
+
// followed redirect would carry the request body to another origin.
|
|
21
|
+
async post(path,body) {
|
|
22
|
+
const response=await fetch(`${this.server}${path}`,{method:'POST',headers:{'content-type':'application/json',...(this.token?{authorization:`Bearer ${this.token}`}:{})},body:JSON.stringify(body),signal:AbortSignal.timeout(30000),redirect:'error'});
|
|
23
|
+
const result=await response.json();
|
|
24
|
+
if(!response.ok) throw Object.assign(new Error(result.error?.message||result.error||`HTTP ${response.status}`),{status:response.status});
|
|
25
|
+
return Object.hasOwn(result,'data') ? result.data : result;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { resolve, join, isAbsolute } from 'node:path';
|
|
3
|
+
import { mkdir, copyFile, chmod } from 'node:fs/promises';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
|
|
6
|
+
function configuredCodexAuthPath() {
|
|
7
|
+
const configured=process.env.CODEX_HOME;
|
|
8
|
+
if(configured!==undefined&&!isAbsolute(configured)) throw new Error('CODEX_HOME must be an absolute path.');
|
|
9
|
+
return join(resolve(configured||join(homedir(),'.codex')),'auth.json');
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Only the chosen authentication file enters the dedicated executor home;
|
|
13
|
+
// Codex configuration and MCP servers are never imported.
|
|
14
|
+
export async function codexAuth(root,args) {
|
|
15
|
+
const source=resolve(args[0]||configuredCodexAuthPath());const dir=join(root,'executor-home','.codex');await mkdir(dir,{recursive:true,mode:0o700});await copyFile(source,join(dir,'auth.json'));await chmod(join(dir,'auth.json'),0o600);console.log('Copied Codex authentication into the dedicated executor home. Configuration and MCP servers were not imported.');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function claudeAuth(root,args) {
|
|
19
|
+
const dir=join(root,'executor-home');await mkdir(dir,{recursive:true,mode:0o700});
|
|
20
|
+
// Login runs with only the dedicated HOME and harmless process settings.
|
|
21
|
+
// Host Claude config, MCP/project history, API keys and gateway credentials
|
|
22
|
+
// are never inherited into the supported OAuth flow.
|
|
23
|
+
const env={PATH:process.env.PATH||'',HOME:dir,TMPDIR:process.env.TMPDIR||'/tmp',LANG:process.env.LANG||'en_US.UTF-8'};
|
|
24
|
+
const loginMode=args.some(value=>value==='--console'||value==='--claudeai')?[]:['--claudeai'];
|
|
25
|
+
const login=spawnSync('claude',['auth','login',...loginMode,...args],{stdio:'inherit',env});
|
|
26
|
+
if(login.error) throw login.error;
|
|
27
|
+
if(login.status!==0) throw new Error(`Claude subscription login exited with status ${login.status??'unknown'}.`);
|
|
28
|
+
const status=spawnSync('claude',['auth','status','--json'],{encoding:'utf8',env});
|
|
29
|
+
if(status.error) throw status.error;
|
|
30
|
+
if(status.status!==0) throw new Error('Claude subscription login did not produce a usable dedicated authentication state.');
|
|
31
|
+
let authenticated=false;try{authenticated=Boolean(JSON.parse(status.stdout).loggedIn)}catch{}
|
|
32
|
+
if(!authenticated) throw new Error('Claude subscription login did not produce a usable dedicated authentication state.');
|
|
33
|
+
console.log('Claude subscription authentication verified in the dedicated executor home.');
|
|
34
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { resolve, join } from 'node:path';
|
|
3
|
+
import { open, unlink } from 'node:fs/promises';
|
|
4
|
+
import { loadState, saveState } from './state.mjs';
|
|
5
|
+
import { map, commands, pair, pairUsage } from './setup.mjs';
|
|
6
|
+
import { codexAuth, claudeAuth } from './auth.mjs';
|
|
7
|
+
import { assertSandboxPlatform } from './providers/sandbox.mjs';
|
|
8
|
+
|
|
9
|
+
export const usage = `Usage: rer companion VERB
|
|
10
|
+
Pairs this computer with a Run Edit Run app, then runs the app's change
|
|
11
|
+
requests here with your own Codex or Claude, in isolated checkouts. It makes
|
|
12
|
+
outbound HTTPS requests only and opens no local server. Needs Node 22 or later;
|
|
13
|
+
run needs macOS (sandbox-exec), and refuses on other systems.
|
|
14
|
+
|
|
15
|
+
map PROJECT_ID OWNER/REPO CHECKOUT
|
|
16
|
+
Approve one local Git checkout for an app; its origin must be OWNER/REPO.
|
|
17
|
+
${pairUsage.replace('rer companion ', '')}
|
|
18
|
+
Redeem the one-use code from the app's Devices page. Asks for a
|
|
19
|
+
missing project or provider in a terminal (default provider codex).
|
|
20
|
+
The legacy form pair URL CODE PROJECT_ID [PROVIDER] [NAME] still works.
|
|
21
|
+
codex-auth [AUTH_FILE]
|
|
22
|
+
Copy only Codex's auth.json into the dedicated executor home.
|
|
23
|
+
claude-auth [--console]
|
|
24
|
+
Sign in to Claude with the dedicated executor home.
|
|
25
|
+
commands PROJECT_ID FILE
|
|
26
|
+
Approve setup and verify argv lists, for example
|
|
27
|
+
{"setup":[["pnpm","install","--frozen-lockfile"]],"verify":[["pnpm","verify"]]}
|
|
28
|
+
run [--once] Take jobs from the app and run them; --once stops after one pass.
|
|
29
|
+
status The paired device, mapped projects, active job and pending events.
|
|
30
|
+
confirm-no-turn-started JOB_ID --confirm-no-provider-turn-started
|
|
31
|
+
confirm-unstarted JOB_ID --confirm-no-executor-started
|
|
32
|
+
Attest a setup failure that happened before any provider turn.
|
|
33
|
+
|
|
34
|
+
State: ~/.rer-local (RER_LOCAL_HOME picks another private folder). The device key
|
|
35
|
+
is kept there (0600); the app keeps only its hash.
|
|
36
|
+
Revoke: in the app, Settings > Devices > Revoke. A running companion stops at its
|
|
37
|
+
next request. Then delete the state folder on this computer.
|
|
38
|
+
`;
|
|
39
|
+
|
|
40
|
+
async function locked(root,work) {
|
|
41
|
+
const lockPath=join(root,'runner.lock');let lock;
|
|
42
|
+
try {lock=await open(lockPath,'wx',0o600);}catch(error){throw new Error('A runner lock exists. Stop the other runner, or verify it is gone before removing runner.lock and reconciling the active job.');}
|
|
43
|
+
try{await lock.writeFile(String(process.pid));await work();}finally{await lock.close();await unlink(lockPath);}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function companionCommand(argv) {
|
|
47
|
+
const [command,...args]=argv;
|
|
48
|
+
if(!command||['--help','-h','help'].includes(command)||argv.includes('--help')) { process.stdout.write(usage); return 0; }
|
|
49
|
+
const root=resolve(process.env.RER_LOCAL_HOME||join(homedir(),'.rer-local'));
|
|
50
|
+
try {
|
|
51
|
+
const state=await loadState(root);
|
|
52
|
+
if(command==='map') await map(root,state,args);
|
|
53
|
+
else if(command==='commands') await commands(root,state,args);
|
|
54
|
+
else if(command==='pair') await pair(root,state,args);
|
|
55
|
+
else if(command==='codex-auth') await codexAuth(root,args);
|
|
56
|
+
else if(command==='claude-auth') await claudeAuth(root,args);
|
|
57
|
+
else if(command==='run') {
|
|
58
|
+
if(!state.token) throw new Error('Pair this computer first.');
|
|
59
|
+
assertSandboxPlatform();
|
|
60
|
+
const { run }=await import('./runner.mjs');
|
|
61
|
+
await locked(root,()=>run(root,state,{once:args.includes('--once')}));
|
|
62
|
+
} else if(command==='confirm-unstarted') {
|
|
63
|
+
const { confirmUnstarted }=await import('./recovery.mjs');
|
|
64
|
+
await locked(root,async()=>{const fresh=await loadState(root);await confirmUnstarted(root,fresh,args[0],args.includes('--confirm-no-executor-started'));await saveState(root,fresh);console.log('Preparation failure attested. Start the companion and use the normal Resume or Cancel control; no job was started.');});
|
|
65
|
+
} else if(command==='confirm-no-turn-started') {
|
|
66
|
+
const { confirmNoTurnStarted }=await import('./recovery.mjs');
|
|
67
|
+
await locked(root,async()=>{const fresh=await loadState(root);await confirmNoTurnStarted(root,fresh,args[0],args.includes('--confirm-no-provider-turn-started'));await saveState(root,fresh);console.log('No-turn setup failure attested; retained checkout and dependencies preserved. Start the companion and use normal UI Resume. No job was started.');});
|
|
68
|
+
} else if(command==='status') {
|
|
69
|
+
console.log(JSON.stringify({device:state.device,projects:Object.keys(state.mappings),active:state.active?{job:state.active.job.id,status:state.active.status,identity:state.active.identity}:null,pendingEvents:state.outbox.length},null,2));
|
|
70
|
+
} else { process.stderr.write(usage); return 2; }
|
|
71
|
+
return 0;
|
|
72
|
+
} catch(error) {process.stderr.write(`${error.message}\n`);return 1;}
|
|
73
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {execFile} from 'node:child_process';
|
|
2
|
+
import {promisify} from 'node:util';
|
|
3
|
+
import {sandboxCommand} from './providers/sandbox.mjs';
|
|
4
|
+
const exec=promisify(execFile);
|
|
5
|
+
// These argv lists are approved at the local terminal, never supplied by browser jobs.
|
|
6
|
+
export function validateCommands(value) {
|
|
7
|
+
if(!value||!Object.keys(value).every(k=>['setup','verify'].includes(k)))throw new Error('Expected setup and verify argv lists.');
|
|
8
|
+
for(const commands of Object.values(value)) if(!Array.isArray(commands)||commands.length>10||!commands.every(argv=>Array.isArray(argv)&&argv.length>0&&argv.length<50&&argv.every(a=>typeof a==='string'&&a.length<2000)))throw new Error('Invalid command argv lists.');
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
export async function runCommands(commands,cwd,env) {
|
|
12
|
+
if(!commands?.length)return [];
|
|
13
|
+
const results=[];
|
|
14
|
+
for(const argv of commands) {
|
|
15
|
+
const sandbox=sandboxCommand(argv[0],cwd,env);
|
|
16
|
+
let exit_code=0;
|
|
17
|
+
try{await exec(sandbox.command,[...sandbox.args,...argv.slice(1)],{cwd,env:sandbox.env,timeout:300000,maxBuffer:1024*1024});}catch(error){exit_code=Number.isInteger(error.code)?error.code:1;}
|
|
18
|
+
results.push({command:argv.join(' '),exit_code});
|
|
19
|
+
if(exit_code!==0)break;
|
|
20
|
+
}
|
|
21
|
+
return results;
|
|
22
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Truncation text is JSON-escaped again in transit. Bound the resulting payload,
|
|
2
|
+
// not just its source string, so one progress event cannot block the outbox.
|
|
3
|
+
export function boundedEventPayload(payload) {
|
|
4
|
+
const encoded=JSON.stringify(payload);
|
|
5
|
+
if(encoded.length<60000)return payload;
|
|
6
|
+
return {truncated:true,originalCharacters:encoded.length,text:encoded.slice(0,24000)};
|
|
7
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A local execution grant is issued by the management service for one job,
|
|
3
|
+
* device, provider, and request. The companion never creates or broadens a
|
|
4
|
+
* grant; it only validates the signed-by-storage scope that arrived with the
|
|
5
|
+
* claimed job and echoes its id on relay writes.
|
|
6
|
+
*/
|
|
7
|
+
export function executionGrant(job, state) {
|
|
8
|
+
const value = job?.execution_grant;
|
|
9
|
+
if (value === undefined || value === null) throw new Error('Claimed local job is missing its scoped execution grant. Reconcile with the management service.');
|
|
10
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid scoped local execution grant.');
|
|
11
|
+
const strings = ['id', 'installationId', 'deviceId', 'userId', 'jobId', 'requestId', 'projectId', 'issuedAt'];
|
|
12
|
+
if (strings.some(key => typeof value[key] !== 'string' || value[key].length === 0)) throw new Error('Invalid scoped local execution grant.');
|
|
13
|
+
if (!['codex', 'claude'].includes(value.provider) || value.executor !== 'local') throw new Error('Invalid scoped local execution grant provider.');
|
|
14
|
+
if (value.managementReservationId !== null && typeof value.managementReservationId !== 'string') throw new Error('Invalid local management reservation binding.');
|
|
15
|
+
if (value.runId !== job.run_id) throw new Error('Scoped local execution grant run differs from the claimed run.');
|
|
16
|
+
if (value.jobId !== job.id || value.requestId !== job.request_id || value.projectId !== job.project_id || value.deviceId !== job.device_id || value.installationId !== job.installation_id) {
|
|
17
|
+
throw new Error('Scoped local execution grant does not match this job.');
|
|
18
|
+
}
|
|
19
|
+
if (state?.provider && value.provider !== state.provider) throw new Error('Scoped local execution grant provider differs from the paired provider.');
|
|
20
|
+
if (state?.device?.id && value.deviceId !== state.device.id) throw new Error('Scoped local execution grant device differs from the paired device.');
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function grantId(job, state) {
|
|
25
|
+
return executionGrant(job, state)?.id ?? null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function safeGrantId(job, state) {
|
|
29
|
+
try { return grantId(job, state); } catch { return null; }
|
|
30
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { readdir, lstat, realpath, open } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
+
|
|
5
|
+
async function canonical(path) {
|
|
6
|
+
if(typeof path!=='string'||!path.startsWith('/')) throw new Error('Provider evidence cannot be attributed to a workspace.');
|
|
7
|
+
try { return await realpath(path); } catch(error) { if(error.code==='ENOENT')return resolve(path);throw error; }
|
|
8
|
+
}
|
|
9
|
+
async function inspectSessions(directory, worktree) {
|
|
10
|
+
for(const entry of await readdir(directory,{withFileTypes:true})) {
|
|
11
|
+
const path=join(directory,entry.name);
|
|
12
|
+
if(entry.isSymbolicLink())throw new Error('Provider session evidence must not be a symlink.');
|
|
13
|
+
if(entry.isDirectory()){await inspectSessions(path,worktree);continue;}
|
|
14
|
+
if(!entry.isFile())throw new Error('Unknown provider session evidence.');
|
|
15
|
+
const file=await open(path,'r'),buffer=Buffer.alloc(65536);
|
|
16
|
+
let header;
|
|
17
|
+
try {const {bytesRead}=await file.read(buffer,0,buffer.length,0);header=JSON.parse(buffer.subarray(0,bytesRead).toString('utf8').split('\n')[0]);}
|
|
18
|
+
finally {await file.close();}
|
|
19
|
+
if(header.type!=='session_meta')throw new Error('Provider session evidence cannot be attributed to a workspace.');
|
|
20
|
+
if(await canonical(header.payload?.cwd)===worktree)throw new Error('Recorded provider sessions prevent no-turn attestation.');
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Recorded work for another mapped checkout is unrelated. Unknown evidence fails
|
|
25
|
+
// closed; absence of an in-memory identity never overrides provider history.
|
|
26
|
+
export async function assertNoTurnEvidence(root, state) {
|
|
27
|
+
if (state.provider && state.provider !== 'codex') throw new Error('No-turn attestation supports only the inspected Codex state format.');
|
|
28
|
+
if (state.outbox?.length) throw new Error('Pending relay events must be reconciled before no-turn attestation.');
|
|
29
|
+
const worktree=await canonical(state.active?.workspace?.worktree);
|
|
30
|
+
const home = join(root, 'executor-home', '.codex');
|
|
31
|
+
let entries;
|
|
32
|
+
try { entries = await readdir(home); } catch (error) { if (error.code === 'ENOENT') return; throw error; }
|
|
33
|
+
for (const directory of ['sessions','archived_sessions']) {
|
|
34
|
+
if (!entries.includes(directory)) continue;
|
|
35
|
+
const path=join(home,directory),info=await lstat(path);
|
|
36
|
+
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error('Recorded provider sessions prevent no-turn attestation.');
|
|
37
|
+
await inspectSessions(path,worktree);
|
|
38
|
+
}
|
|
39
|
+
for (const name of entries.filter(name => /^state(?:_.*)?\.sqlite$/.test(name))) {
|
|
40
|
+
const path=join(home,name),info=await lstat(path);
|
|
41
|
+
if (!info.isFile() || info.isSymbolicLink()) throw new Error('Provider state must be a regular database.');
|
|
42
|
+
const database=new DatabaseSync(path,{readOnly:true});
|
|
43
|
+
try {
|
|
44
|
+
for(const row of database.prepare('SELECT cwd FROM threads').all()) {
|
|
45
|
+
if(await canonical(row.cwd)===worktree) throw new Error('Recorded provider threads prevent no-turn attestation.');
|
|
46
|
+
}
|
|
47
|
+
} finally { database.close(); }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { sandboxCommand } from './sandbox.mjs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { mkdirSync } from 'node:fs';
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
export class ClaudeSession {
|
|
6
|
+
constructor({cwd,env,onEvent,onIdentity}) { const scratch=join(env.HOME,'tmp');mkdirSync(scratch,{recursive:true,mode:0o700});Object.assign(this,{cwd,env:{...env,TMPDIR:scratch,CLAUDE_CODE_TMPDIR:scratch},onEvent,onIdentity}); }
|
|
7
|
+
async open(sessionId) { this.sessionId = sessionId; }
|
|
8
|
+
start(text) {
|
|
9
|
+
this.cancelDelivered = false;
|
|
10
|
+
return new Promise((resolve,reject) => {
|
|
11
|
+
const args = ['-p', text, '--output-format', 'stream-json', '--verbose', '--permission-mode', 'acceptEdits', '--allowedTools', 'Read,Edit,Write,Grep,Glob,Bash', '--tools', 'Read,Edit,Write,Grep,Glob,Bash', '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}'];
|
|
12
|
+
if (this.sessionId) args.push('--resume',this.sessionId);
|
|
13
|
+
const sandbox = sandboxCommand('claude',this.cwd,this.env);
|
|
14
|
+
this.child = spawn(sandbox.command, [...sandbox.args, ...args], { cwd:this.cwd,env:sandbox.env,stdio:['ignore','pipe','pipe'] });
|
|
15
|
+
let buffer='',result;
|
|
16
|
+
this.child.stdout.on('data', chunk => { buffer+=chunk; let end; while ((end=buffer.indexOf('\n'))>=0) { const line=buffer.slice(0,end);buffer=buffer.slice(end+1); if(!line.trim()) continue; try { const event=JSON.parse(line);if(event.session_id) {this.sessionId=event.session_id;this.onIdentity({thread_id:this.sessionId,provider:'claude'});}this.onEvent({kind:'progress',payload:event});if(event.type==='result') result=event; } catch(error) {reject(error);} } });
|
|
17
|
+
this.child.once('error',reject);
|
|
18
|
+
this.child.once('exit',(code,signal) => { try { resolve(this.resultOnExit(code,signal,result)); } catch(error) { reject(error); } });
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
resultOnExit(code,signal,result) {
|
|
22
|
+
if(signal || this.cancelDelivered) return {status:'interrupted'};
|
|
23
|
+
if(code===0 && result) return {status:result.is_error?'failed':'completed',result};
|
|
24
|
+
throw new Error(`Claude exited ${code} without confirmed result`);
|
|
25
|
+
}
|
|
26
|
+
async control(control) { if(control.kind==='cancel') {if (!this.child || this.child.exitCode !== null || this.child.signalCode !== null) throw new Error('Claude has no running process to interrupt.');
|
|
27
|
+
this.cancelDelivered = this.child.kill('SIGINT');
|
|
28
|
+
if (!this.cancelDelivered) throw new Error('Claude interrupt signal was not delivered.');
|
|
29
|
+
return;} throw new Error('Claude API adapter supports interrupt and resumed follow-up after completion; active steering is unavailable.'); }
|
|
30
|
+
async close() { if(this.child?.exitCode===null) this.child.kill('SIGTERM'); }
|
|
31
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { sandboxCommand } from './sandbox.mjs';
|
|
2
|
+
import { JsonlRpc } from './jsonl-rpc.mjs';
|
|
3
|
+
export class CodexSession {
|
|
4
|
+
constructor({ cwd, env, onEvent, onIdentity }) {
|
|
5
|
+
this.cwd = cwd; this.onEvent = onEvent; this.onIdentity = onIdentity;
|
|
6
|
+
const sandbox = sandboxCommand('codex', cwd, env);
|
|
7
|
+
this.rpc = new JsonlRpc(sandbox.command, [...sandbox.args, 'app-server', '-c', 'features.apps=false'], { cwd, env:sandbox.env });
|
|
8
|
+
this.requests = new Map();
|
|
9
|
+
this.rpc.onNotification(message => this.handleNotification(message));
|
|
10
|
+
this.rpc.child.once('exit', () => this.reject?.(new Error('Codex disconnected; reconcile the saved session before resuming.')));
|
|
11
|
+
}
|
|
12
|
+
handleNotification(message) {
|
|
13
|
+
if (message.id !== undefined) this.requests.set(String(message.id), message);
|
|
14
|
+
if (message.method === 'turn/completed' && message.params?.threadId === this.thread && (!this.turn || message.params?.turn?.id === this.turn)) { this.turn = null; this.resolve?.(message.params.turn); }
|
|
15
|
+
this.onEvent({ kind: message.id !== undefined ? ((message.method.includes('requestUserInput') || message.method==='item/tool/call') ? 'question' : 'approval') : 'progress', payload: message });
|
|
16
|
+
}
|
|
17
|
+
async open(threadId) {
|
|
18
|
+
await this.rpc.request('initialize', { clientInfo: { name: 'rer-local', version: '0.1.0' }, capabilities: { experimentalApi: true } });
|
|
19
|
+
this.rpc.notify('initialized', {});
|
|
20
|
+
const params = { cwd: this.cwd, approvalPolicy: 'on-request', sandbox: 'danger-full-access' };
|
|
21
|
+
if(!threadId)params.dynamicTools=[{type:'function',name:'rer_question',description:'Ask the installation owner a question and wait for their response before proceeding.',inputSchema:{type:'object',properties:{question:{type:'string'}},required:['question'],additionalProperties:false}}];
|
|
22
|
+
const response = await this.rpc.request(threadId ? 'thread/resume' : 'thread/start', { ...params, ...(threadId ? { threadId } : {}) });
|
|
23
|
+
this.thread = response.thread.id;
|
|
24
|
+
await this.onIdentity({ thread_id: this.thread, provider: 'codex' });
|
|
25
|
+
}
|
|
26
|
+
async start(text) {
|
|
27
|
+
const done = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; });
|
|
28
|
+
const response = await this.rpc.request('turn/start', { threadId: this.thread, input: [{ type: 'text', text }], cwd: this.cwd, approvalPolicy: 'on-request', sandboxPolicy: { type: 'externalSandbox', networkAccess: 'enabled' } });
|
|
29
|
+
this.turn = response.turn.id;
|
|
30
|
+
if(this.cancelRequested)await this.rpc.request('turn/interrupt',{threadId:this.thread,turnId:this.turn});
|
|
31
|
+
const result = await done;
|
|
32
|
+
return result;
|
|
33
|
+
}
|
|
34
|
+
async control(control) {
|
|
35
|
+
if (control.kind === 'message') return this.rpc.request('turn/steer', { threadId: this.thread, expectedTurnId: this.turn, input: [{ type: 'text', text: control.payload.text }] });
|
|
36
|
+
if (control.kind === 'cancel') { this.cancelRequested=true; if(!this.turn)return; return this.rpc.request('turn/interrupt', { threadId: this.thread, turnId: this.turn }); }
|
|
37
|
+
if (control.kind === 'respond') {
|
|
38
|
+
const request = this.requests.get(String(control.payload.request_id));
|
|
39
|
+
const id = request?.id ?? request;
|
|
40
|
+
if (id === undefined) throw new Error('Unknown or already answered provider request.');
|
|
41
|
+
// Escalation changes the filesystem boundary, so it requires action at the local terminal.
|
|
42
|
+
let original = control.payload.response;
|
|
43
|
+
if(typeof original==='string') {
|
|
44
|
+
if(request.method==='item/tool/call') original={contentItems:[{type:'inputText',text:original}],success:true};
|
|
45
|
+
else if(request.method==='item/tool/requestUserInput' && request.params?.questions?.length===1) original={answers:{[request.params.questions[0].id]:{answers:[original]}}};
|
|
46
|
+
else if(['decline','cancel'].includes(original)) original={decision:original};
|
|
47
|
+
else throw new Error('A structured provider response is required.');
|
|
48
|
+
}
|
|
49
|
+
if (original?.decision && !['decline', 'cancel'].includes(original.decision)) throw new Error('Command/file escalation must be approved locally, outside the remote relay.');
|
|
50
|
+
this.rpc.send({ id, result: original }); this.requests.delete(String(id)); return;
|
|
51
|
+
}
|
|
52
|
+
throw new Error(`Unsupported active control ${control.kind}`);
|
|
53
|
+
}
|
|
54
|
+
close() { return this.rpc.close(); }
|
|
55
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
// JSONL stdio transport for `codex app-server`. Server requests that reuse a
|
|
4
|
+
// client request id stay distinct from that request's response.
|
|
5
|
+
function waitForExit(child, timeoutMs) {
|
|
6
|
+
return new Promise((resolve) => {
|
|
7
|
+
if (child.exitCode !== null || child.signalCode !== null) { resolve(); return; }
|
|
8
|
+
const timer = setTimeout(resolve, timeoutMs);
|
|
9
|
+
child.once('exit', () => { clearTimeout(timer); resolve(); });
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
function stopChild(child, signal = 'SIGTERM') {
|
|
13
|
+
if (child.exitCode === null && child.signalCode === null) child.kill(signal);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export class JsonlRpc {
|
|
17
|
+
constructor(command, args, { env, cwd } = {}) {
|
|
18
|
+
this.nextId = 1;
|
|
19
|
+
this.pending = new Map();
|
|
20
|
+
this.handlers = new Set();
|
|
21
|
+
this.buffer = '';
|
|
22
|
+
this.stderr = '';
|
|
23
|
+
this.child = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'], env, cwd });
|
|
24
|
+
this.child.once('error', (error) => this.failAll(error));
|
|
25
|
+
this.child.once('exit', (code, signal) => this.failAll(new Error(`app-server exited (${code ?? signal ?? 'unknown'}).`)));
|
|
26
|
+
this.child.stdout.on('data', (chunk) => this.consume(chunk));
|
|
27
|
+
this.child.stderr.on('data', (chunk) => { this.stderr = `${this.stderr}${chunk.toString('utf8')}`.slice(-8_000); });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
consume(chunk) {
|
|
31
|
+
this.buffer += chunk.toString('utf8');
|
|
32
|
+
const lines = this.buffer.split('\n');
|
|
33
|
+
this.buffer = lines.pop() || '';
|
|
34
|
+
for (const line of lines) {
|
|
35
|
+
if (!line.trim()) continue;
|
|
36
|
+
let message;
|
|
37
|
+
try {
|
|
38
|
+
message = JSON.parse(line);
|
|
39
|
+
} catch {
|
|
40
|
+
this.failAll(new Error('Codex app-server emitted invalid JSONL.'));
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (!message.method && message.id !== undefined && this.pending.has(message.id)) {
|
|
44
|
+
const pending = this.pending.get(message.id);
|
|
45
|
+
this.pending.delete(message.id);
|
|
46
|
+
clearTimeout(pending.timer);
|
|
47
|
+
if (message.error) pending.reject(new Error(message.error.message || 'Codex app-server request failed.'));
|
|
48
|
+
else pending.resolve(message.result);
|
|
49
|
+
} else if (message.method) {
|
|
50
|
+
for (const handler of this.handlers) handler(message);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
request(method, params, timeoutMs = 30_000) {
|
|
56
|
+
const id = this.nextId++;
|
|
57
|
+
return new Promise((resolve, reject) => {
|
|
58
|
+
const timer = setTimeout(() => {
|
|
59
|
+
this.pending.delete(id);
|
|
60
|
+
reject(new Error(`${method} timed out.`));
|
|
61
|
+
}, timeoutMs);
|
|
62
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
63
|
+
this.send({ method, id, params });
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
notify(method, params) { this.send({ method, params }); }
|
|
68
|
+
|
|
69
|
+
send(message) {
|
|
70
|
+
if (!this.child.stdin.writable) throw new Error('Codex app-server stdin is closed.');
|
|
71
|
+
this.child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
onNotification(handler) {
|
|
75
|
+
this.handlers.add(handler);
|
|
76
|
+
return () => this.handlers.delete(handler);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
failAll(error) {
|
|
80
|
+
for (const [id, pending] of this.pending) {
|
|
81
|
+
this.pending.delete(id);
|
|
82
|
+
clearTimeout(pending.timer);
|
|
83
|
+
pending.reject(error);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async close() {
|
|
88
|
+
stopChild(this.child);
|
|
89
|
+
await waitForExit(this.child, 1_000);
|
|
90
|
+
if (this.child.exitCode === null && this.child.signalCode === null) {
|
|
91
|
+
stopChild(this.child, 'SIGKILL');
|
|
92
|
+
await waitForExit(this.child, 1_000);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { existsSync, realpathSync, mkdirSync } from 'node:fs';
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { dirname, join, delimiter, resolve } from 'node:path';
|
|
4
|
+
|
|
5
|
+
function executable(name, env, cwd) {
|
|
6
|
+
const path = name.includes('/') ? resolve(cwd,name) : env.PATH.split(delimiter).map(dir => join(dir, name)).find(existsSync);
|
|
7
|
+
if (!path) throw new Error(`Required local executable missing: ${name}`);
|
|
8
|
+
return realpathSync(path);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// The boundary wraps the provider itself: built-in reads and subprocesses both inherit it.
|
|
12
|
+
// Do not replace this with a provider workspace-write setting (which permits global reads).
|
|
13
|
+
// Other platforms refuse before any job is claimed; nothing runs unconfined.
|
|
14
|
+
export function assertSandboxPlatform() {
|
|
15
|
+
if (process.platform !== 'darwin' || !existsSync('/usr/bin/sandbox-exec')) throw new Error('Local engineering requires the supported macOS sandbox-exec boundary. rer companion run works only on macOS; it never runs a provider without that boundary.');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function sandboxCommand(provider, cwd, env) {
|
|
19
|
+
assertSandboxPlatform();
|
|
20
|
+
const home = realpathSync(env.HOME), workspace = realpathSync(cwd);
|
|
21
|
+
if (home === '/' || workspace === '/' || home === process.env.HOME || workspace === process.env.HOME) throw new Error('An isolated provider home and selected workspace are required.');
|
|
22
|
+
const tmp = join(home, 'tmp'); mkdirSync(tmp, {recursive:true,mode:0o700});
|
|
23
|
+
const cli = executable(provider,env,cwd), node = realpathSync(process.execPath), git = executable('git',env,cwd);
|
|
24
|
+
const roots = [workspace,home,'/System/Library','/private/var/db/timezone','/usr/lib','/usr/share','/usr/bin','/bin','/sbin','/usr/sbin','/Library/Apple/System/Library','/Library/Developer/CommandLineTools',...[node,git].map(path=>dirname(dirname(path))).filter(path=>!['/','/usr'].includes(path))];
|
|
25
|
+
// npm Codex's launcher loads its own package and platform binary package.
|
|
26
|
+
if (/\.(?:mjs|cjs|js)$/.test(cli)) roots.push(dirname(dirname(cli)));
|
|
27
|
+
const libraries = new Set();
|
|
28
|
+
const inspected = new Set();
|
|
29
|
+
const inspect = binary => {
|
|
30
|
+
const canonical=realpathSync(binary);
|
|
31
|
+
if (inspected.has(canonical)) return; inspected.add(canonical); libraries.add(binary); libraries.add(canonical);
|
|
32
|
+
const output = execFileSync('/Library/Developer/CommandLineTools/usr/bin/otool',['-L',binary],{encoding:'utf8'});
|
|
33
|
+
for (const line of output.split('\n').slice(1)) {
|
|
34
|
+
const dependency=line.trim().split(' (')[0];
|
|
35
|
+
let resolved=dependency;
|
|
36
|
+
if (dependency.startsWith('@loader_path/')) resolved=join(dirname(binary),dependency.slice('@loader_path/'.length));
|
|
37
|
+
else if (dependency.startsWith('@rpath/')) resolved=join(dirname(binary),dependency.slice('@rpath/'.length));
|
|
38
|
+
if (resolved.startsWith('/') && !resolved.startsWith('/System/') && !resolved.startsWith('/usr/lib/') && existsSync(resolved)) { libraries.add(resolved); inspect(realpathSync(resolved)); }
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
inspect(node); inspect(git);
|
|
42
|
+
if (!/\.(?:mjs|cjs|js)$/.test(cli)) inspect(cli);
|
|
43
|
+
const literals = ['/',...libraries,cli,node,'/dev/null','/dev/urandom','/dev/random','/private/etc/resolv.conf','/private/etc/hosts','/private/etc/localtime','/private/etc/services','/private/etc/protocols','/private/var/run/resolv.conf','/private/var/db/timezone/zoneinfo'];
|
|
44
|
+
const quote = JSON.stringify;
|
|
45
|
+
// Codex 0.163+ loads macOS managed preferences at thread start and fails
|
|
46
|
+
// without read access to the preferences daemon's two shared pages (change
|
|
47
|
+
// counters, no preference values): the daemon's and this user's. No file opens.
|
|
48
|
+
const cfprefs = ['daemonv1', `${process.getuid()}v1`].map(name => `(ipc-posix-name ${quote(`apple.cfprefs.${name}`)})`).join(' ');
|
|
49
|
+
// Network stays open: providers and package managers need outbound access and
|
|
50
|
+
// dev servers need to listen. sandbox-exec cannot confine listening to
|
|
51
|
+
// loopback (a "localhost" network-inbound rule still allows 0.0.0.0).
|
|
52
|
+
// Keep the loader spelling for libraries as well as their canonical targets:
|
|
53
|
+
// macOS may resolve an @loader_path dependency through a versioned symlink,
|
|
54
|
+
// then ask the sandbox for that symlink path during dyld startup.
|
|
55
|
+
const reads = roots.filter(existsSync).map(path => `(subpath ${quote(realpathSync(path))})`).concat(literals.filter(existsSync).map(path => `(literal ${quote(path)})`));
|
|
56
|
+
const profile = `(version 1)(deny default)(allow process-exec)(allow process-fork)(allow signal (target same-sandbox))(allow process-info* (target same-sandbox))(allow sysctl-read)(allow mach-lookup)(allow ipc-posix-shm-read-data ${cfprefs})(allow network*)(allow file-read-metadata)(allow file-read* file-map-executable ${reads.join(' ')})(allow file-write* (subpath ${quote(workspace)}) (subpath ${quote(home)}) (literal "/dev/null"))`;
|
|
57
|
+
return {command:'/usr/bin/sandbox-exec',args:['-p',profile,...(/\.(?:mjs|cjs|js)$/.test(cli)?[node,cli]:[cli])],env:{...env,GIT_CONFIG_NOSYSTEM:'1',OPENSSL_CONF:'/dev/null',TMPDIR:tmp,CLAUDE_CODE_TMPDIR:tmp},profile};
|
|
58
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import {readFileSync,existsSync} from 'node:fs';
|
|
2
|
+
import {join} from 'node:path';
|
|
3
|
+
// Trusted adapter only. Values never leave this closure or enter a provider prompt.
|
|
4
|
+
export function providerSecretGuard(env) {
|
|
5
|
+
const values=[env.ANTHROPIC_API_KEY,env.ANTHROPIC_AUTH_TOKEN].filter(Boolean);
|
|
6
|
+
const auth=join(env.HOME,'.codex','auth.json');
|
|
7
|
+
if(existsSync(auth)) {
|
|
8
|
+
const data=JSON.parse(readFileSync(auth,'utf8'));
|
|
9
|
+
for(const [key,value] of Object.entries({...data,...data.tokens})) if(/token|api_key/i.test(key)&&typeof value==='string'&&value.length>8)values.push(value);
|
|
10
|
+
}
|
|
11
|
+
// OAuth credentials may be persisted by Claude Code in its dedicated
|
|
12
|
+
// executor home. Read only credential-shaped fields there; never inspect the
|
|
13
|
+
// host HOME or macOS Keychain to construct this guard.
|
|
14
|
+
for (const path of [join(env.HOME,'.claude','.credentials.json'),join(env.HOME,'.claude.json')]) {
|
|
15
|
+
if (!existsSync(path)) continue;
|
|
16
|
+
try {
|
|
17
|
+
const data=JSON.parse(readFileSync(path,'utf8'));
|
|
18
|
+
const collect=(value,key='')=>{
|
|
19
|
+
if (value&&typeof value==='object') for (const [name,item] of Object.entries(value)) collect(item,name);
|
|
20
|
+
else if (typeof value==='string'&&value.length>8&&/(token|secret|credential|api.?key|access.?token|refresh.?token)/i.test(key)) values.push(value);
|
|
21
|
+
};
|
|
22
|
+
collect(data);
|
|
23
|
+
} catch { /* Invalid provider state is handled by the provider itself. */ }
|
|
24
|
+
}
|
|
25
|
+
const variants=[...new Set(values.flatMap(value=>[value,encodeURIComponent(value),Buffer.from(value).toString('base64')]))];
|
|
26
|
+
const clean=value=>{
|
|
27
|
+
if(typeof value==='string')return variants.reduce((text,secret)=>text.split(secret).join('[REDACTED PROVIDER CREDENTIAL]'),value);
|
|
28
|
+
if(Array.isArray(value))return value.map(clean);
|
|
29
|
+
if(value&&typeof value==='object')return Object.fromEntries(Object.entries(value).map(([key,item])=>[key,clean(item)]));
|
|
30
|
+
return value;
|
|
31
|
+
};
|
|
32
|
+
return {redact:clean,assertPublishable(result){
|
|
33
|
+
const source=JSON.stringify(result)+'\n'+(result.files||[]).filter(file=>file.contentBase64).map(file=>Buffer.from(file.contentBase64,'base64').toString('utf8')).join('\n');
|
|
34
|
+
if(variants.some(secret=>source.includes(secret)))throw new Error('Provider credential detected in proposed result; publication blocked. Inspect the retained worktree locally.');
|
|
35
|
+
}};
|
|
36
|
+
}
|