@dev-zero/mcp-agent 0.0.1 → 0.0.3

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 CHANGED
@@ -13,6 +13,14 @@ npx @dev-zero/mcp-agent remote
13
13
 
14
14
  This Agent connects to the Zero_SERVER gateway and securely restores its per-user local identity when available. Run `npx @dev-zero/mcp-agent --help` for the available commands.
15
15
 
16
+ On a brand-new Windows user/Chrome installation, select or create a Chrome profile
17
+ and sign in at `https://chatgpt.com/` when the Agent reports a missing local
18
+ session. During first Device Code enrollment the Agent keeps polling and rechecks
19
+ the Chrome session without generating another code or requiring a restart; it
20
+ never claims successful authorization until real local ChatGPT proof passes.
21
+ If the Device Code expires, start a new enrollment. No Remote connection to the
22
+ new machine is needed for the local Chrome sign-in step.
23
+
16
24
  For a source checkout:
17
25
 
18
26
  ```powershell
@@ -59,4 +67,16 @@ that still supports `system.info` for existing live users. A real new-user
59
67
  ChatGPT OAuth callback, production Agent replacement and reconnect remain
60
68
  unverified acceptance gates.
61
69
 
70
+ ## Publishing with EOTP on MiruZero
71
+
72
+ The Agent's **source-only** release helper follows the validated `M:\\Zero_ChatGPT` release workflow. It calls the installed `zgpt eotp npm --json`, passes the resulting 6-digit TOTP only to the child npm process through `npm_config_otp`, and never logs or stores the code. The helper is excluded from the published Agent tarball.
73
+
74
+ ```powershell
75
+ Set-Location M:\\Zero_SERVER\\source\\agent\\zero-agent
76
+ npm run release:eotp:check # Tests, pack audit, public-registry version check; NO publish
77
+ npm run release:eotp # Verify npm login, obtain new EOTP, publish, verify registry
78
+ ```
79
+
80
+ This needs a **normal online PowerShell session** running as the Windows user who configured `zgpt eotp npm`; the Remote Desktop Commander execution environment may enforce `npm_config_offline=true` and cannot perform npm registry mutations. The helper reports `NPM_OFFLINE_ENV` without attempting a false publish in that environment. The npm account token needs permission to publish `@dev-zero/mcp-agent`; possessing a valid OTP alone does not grant package permissions. An OTP error (`EOTP`) is distinct from Registry HTTP404 (version absent, permissions, or package access). A release is VERIFIED only when the registry serves the exact published version; no automatic version bump, process restart, or npm global install occurs.
81
+
62
82
  **Publish metadata:** `@dev-zero/mcp-agent` is configured for public npm distribution with `publishConfig.access=public`. Packaging readiness is not proof of a successful registry publication. Project runtime and credentials remain on the local machine; do not include them in an npm archive.
@@ -100,6 +100,17 @@ async function start(){
100
100
  console.log(' - 🔌 Connected to Local Zero MCP');
101
101
  console.log('⏳ Connecting to Remote MCP '+gateway);
102
102
  await bootstrapAgent({gatewayUrl:gateway,vaultFile:vault,
103
+ onAuthRequired:({reason})=>{
104
+ console.log(' - ChatGPT session is not ready ('+reason+').');
105
+ if(reason==='ambiguous')
106
+ console.log(' - Multiple signed-in Chrome profiles found; use one ChatGPT account.');
107
+ else if(reason==='browser_busy'){
108
+ console.log(' - Close all Chrome windows for a few seconds so Zero can verify this signed-in profile locally.');
109
+ console.log(' - Zero will not kill Chrome or extract browser cookies.');
110
+ }else
111
+ console.log(' - Open Chrome, select or create your profile, and sign in at https://chatgpt.com/');
112
+ console.log(' - Waiting with the same Device Code (no restart needed).');
113
+ },
103
114
  onCode:({user_code,verification_uri_complete,expires_in})=>{
104
115
  console.log(' - 🔌 Connected to Remote MCP');
105
116
  console.log('');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dev-zero/mcp-agent",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -15,8 +15,10 @@
15
15
  "start": "node bin/zero-agent.mjs remote",
16
16
  "status": "node bin/zero-agent.mjs status",
17
17
  "doctor": "node bin/zero-agent.mjs remote --help",
18
- "test": "node --test tests/*.test.mjs",
19
- "packcheck": "npm pack --dry-run"
18
+ "test": "node --test --test-concurrency=1 tests/*.test.mjs",
19
+ "packcheck": "npm pack --dry-run",
20
+ "release:eotp": "node scripts/release-eotp.mjs",
21
+ "release:eotp:check": "node scripts/release-eotp.mjs --check"
20
22
  },
21
23
  "files": [
22
24
  "bin",
@@ -0,0 +1,121 @@
1
+ import {existsSync,readFileSync,readdirSync} from 'node:fs';
2
+ import {homedir} from 'node:os';
3
+ import {join} from 'node:path';
4
+ import {spawnSync,execFileSync} from 'node:child_process';
5
+
6
+ const CHATGPT_SESSION='https://chatgpt.com/api/auth/session';
7
+ const PROFILE=/^(?:Default|Profile \d+)$/;
8
+
9
+ const chromeRoot=(env=process.env)=>env.ZERO_CHATGPT_CHROME_DATA_ROOT||
10
+ join(env.LOCALAPPDATA||join(homedir(),'AppData','Local'),'Google','Chrome','User Data');
11
+
12
+ const preferredProfile=(root)=>{
13
+ try{
14
+ const state=JSON.parse(readFileSync(join(root,'Local State'),'utf8'));
15
+ const name=state.profile?.last_used;
16
+ if(typeof name==='string'&&PROFILE.test(name))return name;
17
+ }catch{}
18
+ return 'Default';
19
+ };
20
+
21
+ const profileCandidates=(root)=>{
22
+ const preferred=preferredProfile(root);
23
+ const others=[];
24
+ try{
25
+ for(const entry of readdirSync(root,{withFileTypes:true}))
26
+ if(entry.isDirectory()&&entry.name!==preferred&&PROFILE.test(entry.name))
27
+ others.push(entry.name);
28
+ }catch{}
29
+ return [preferred,...others.sort((a,b)=>a.localeCompare(b,undefined,{numeric:true}))];
30
+ };
31
+
32
+ export function resolveChromeExecutable(env=process.env){
33
+ const custom=env.ZERO_CHATGPT_CHROME_EXE;
34
+ const candidates=[
35
+ custom,
36
+ env.PROGRAMFILES&&join(env.PROGRAMFILES,'Google','Chrome','Application','chrome.exe'),
37
+ env['PROGRAMFILES(X86)']&&join(env['PROGRAMFILES(X86)'],'Google','Chrome','Application','chrome.exe'),
38
+ env.LOCALAPPDATA&&join(env.LOCALAPPDATA,'Google','Chrome','Application','chrome.exe')
39
+ ].filter(Boolean);
40
+ return candidates.find(existsSync)||null;
41
+ }
42
+
43
+ export function isChromeRunning({run=execFileSync}={}){
44
+ if(process.platform!=='win32')return false;
45
+ try{
46
+ const output=run('tasklist.exe',['/FI','IMAGENAME eq chrome.exe','/NH'],{
47
+ encoding:'utf8',windowsHide:true,timeout:3000,stdio:['ignore','pipe','ignore']
48
+ });
49
+ return /(^|\r?\n)chrome\.exe\s/i.test(String(output));
50
+ }catch{return false}
51
+ }
52
+
53
+ const decodeEntities=value=>String(value)
54
+ .replace(/"/g,'"').replace(/'|'/g,"'")
55
+ .replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');
56
+
57
+ const authenticatedDump=stdout=>{
58
+ const raw=Buffer.isBuffer(stdout)?stdout.toString('utf8'):String(stdout||'');
59
+ const match=/<pre[^>]*>([\s\S]*?)<\/pre>/i.exec(raw)||
60
+ /<body[^>]*>([\s\S]*?)<\/body>/i.exec(raw);
61
+ if(!match)return false;
62
+ const text=decodeEntities(match[1].replace(/<[^>]+>/g,'')).trim();
63
+ let body;
64
+ try{body=JSON.parse(text)}catch{return false}
65
+ return Boolean(body&&typeof body==='object'&&!Array.isArray(body)&&
66
+ (body.user||body.account||body.accessToken||body.sessionToken));
67
+ };
68
+
69
+ export function probeChromeProfile({chrome,root,profile,run=spawnSync}){
70
+ if(!chrome||!existsSync(root)||!PROFILE.test(profile))return false;
71
+ // This runs only when no Chrome process owns the real profile. Chrome itself
72
+ // decrypts/uses its cookies; Zero never extracts or logs them. stdout stays
73
+ // in memory and is reduced to a boolean authenticated/not-authenticated.
74
+ const args=[
75
+ '--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check',
76
+ '--disable-background-networking','--disable-component-update','--disable-sync',
77
+ '--disable-default-apps','--disable-features=MediaRouter',
78
+ '--virtual-time-budget=7000','--user-data-dir='+root,'--profile-directory='+profile,
79
+ '--dump-dom',CHATGPT_SESSION
80
+ ];
81
+ try{
82
+ const result=run(chrome,args,{
83
+ windowsHide:true,encoding:null,timeout:20000,maxBuffer:2*1024*1024,
84
+ stdio:['ignore','pipe','ignore']
85
+ });
86
+ return !result?.error&&authenticatedDump(result?.stdout);
87
+ }catch{return false}
88
+ }
89
+
90
+ export async function verifyChromeBrowserSession({
91
+ env=process.env,browserRunning=isChromeRunning,probeProfile=probeChromeProfile
92
+ }={}){
93
+ const root=chromeRoot(env);
94
+ if(!existsSync(root))
95
+ return {state:'auth_required',runtime:'ready',auth:'missing',redacted:true};
96
+ if(browserRunning())
97
+ return {state:'auth_required',runtime:'ready',auth:'browser_busy',redacted:true};
98
+ const chrome=resolveChromeExecutable(env);
99
+ if(!chrome)
100
+ return {state:'auth_required',runtime:'ready',auth:'missing',redacted:true};
101
+
102
+ const profiles=profileCandidates(root);
103
+ if(profiles.length===0)
104
+ return {state:'auth_required',runtime:'ready',auth:'missing',redacted:true};
105
+
106
+ const preferred=profiles[0];
107
+ if(await probeProfile({chrome,root,profile:preferred}))
108
+ return {state:'auth_valid',runtime:'ready',auth:'valid',redacted:true};
109
+
110
+ let found=0;
111
+ for(const profile of profiles.slice(1)){
112
+ if(await probeProfile({chrome,root,profile})){
113
+ found++;
114
+ if(found>1)
115
+ return {state:'auth_required',runtime:'ready',auth:'ambiguous',redacted:true};
116
+ }
117
+ }
118
+ return found===1
119
+ ?{state:'auth_valid',runtime:'ready',auth:'valid',redacted:true}
120
+ :{state:'auth_required',runtime:'ready',auth:'invalid',redacted:true};
121
+ }
@@ -3,6 +3,7 @@ import https from 'node:https';
3
3
  import { mkdtempSync,existsSync,readdirSync,readFileSync,copyFileSync,mkdirSync,rmSync } from 'node:fs';
4
4
  import { tmpdir,homedir } from 'node:os';
5
5
  import { join } from 'node:path';
6
+ import {verifyChromeBrowserSession} from './browser-session-proof.mjs';
6
7
 
7
8
  const CHATGPT_SESSION='https://chatgpt.com/api/auth/session';
8
9
  const SESSION_STORAGE_KEY='oai/apps/accountSwitchSessions';
@@ -123,10 +124,18 @@ function directRequest(url,options) {
123
124
  });
124
125
  }
125
126
 
126
- export async function ensureLocalChatGPTSession({env=process.env,request=directRequest,findMarker}={}){
127
+ export async function ensureLocalChatGPTSession({env=process.env,request=directRequest,findMarker,browserProof=verifyChromeBrowserSession}={}){
127
128
  const found=await findLocalChatGPTSession({env,...(findMarker?{findMarker}:{})});
128
- if(!found.marker)return {state:'auth_required',runtime:'ready',
129
- auth:found.auth||'missing',redacted:true};
129
+ if(!found.marker){
130
+ if(found.auth==='ambiguous')return {state:'auth_required',runtime:'ready',auth:'ambiguous',redacted:true};
131
+ const proof=await browserProof({env});
132
+ if(proof?.state==='auth_valid'&&proof.auth==='valid'&&proof.redacted===true)
133
+ return {state:'auth_valid',runtime:'ready',auth:'valid',redacted:true};
134
+ if(proof?.state==='auth_required'&&proof.redacted===true&&
135
+ ['missing','expired','invalid','ambiguous','browser_busy'].includes(proof.auth))
136
+ return {state:'auth_required',runtime:'ready',auth:proof.auth,redacted:true};
137
+ throw new Error('CHATGPT_BROWSER_PROOF_INVALID');
138
+ }
130
139
  // The marker stays in memory and is sent only to chatgpt.com over HTTPS.
131
140
  // No token is included in returned Agent status, logs or persisted state.
132
141
  let cookie='__Secure-next-auth.session-token='+encodeURIComponent(found.marker);
package/src/first-run.mjs CHANGED
@@ -13,7 +13,7 @@ const json=async response=>{try{return await response.json()}catch{return {error
13
13
  // and the local ChatGPT session check have completed.
14
14
  export async function bootstrapAgent({gatewayUrl,vaultFile,ensure=ensureLocalChatGPTSession,
15
15
  request=fetch,save=saveAgentCredential,wait=sleep,
16
- onCode=()=>{},onConnected=()=>{},signal}={}){
16
+ onCode=()=>{},onConnected=()=>{},onAuthRequired=()=>{},signal}={}){
17
17
  const base=validateAgentGateway(gatewayUrl);
18
18
  const secret=randomBytes(32).toString('base64url');
19
19
  const verifier=randomBytes(32).toString('base64url');
@@ -42,6 +42,7 @@ export async function bootstrapAgent({gatewayUrl,vaultFile,ensure=ensureLocalCha
42
42
  verification_uri_complete:code.verification_uri_complete,expires_in:code.expires_in});
43
43
  const until=Date.now()+Math.min(Math.max(1,Number(code.expires_in||900)),900)*1000;
44
44
  let submitted=false,finalized=false;
45
+ const reportedAuthReasons=new Set();
45
46
  while(Date.now()<until){
46
47
  if(signal?.aborted)throw new Error('DEVICE_AUTH_ABORTED');
47
48
  const interval=Math.max(250,Math.min(15000,Number(code.interval||5)*1000));
@@ -72,8 +73,20 @@ export async function bootstrapAgent({gatewayUrl,vaultFile,ensure=ensureLocalCha
72
73
  if(polled.status===400&&polled.body?.error==='authorization_pending'){
73
74
  if(polled.body.action==='zero.chatgpt.auth.ensure'&&!submitted){
74
75
  const local=await ensure();
75
- if(local?.state!=='auth_valid'||local?.auth!=='valid'||local?.redacted!==true)
76
- throw new Error('CHATGPT_LOCAL_SESSION_REQUIRED');
76
+ if(local?.state!=='auth_valid'||local?.auth!=='valid'||local?.redacted!==true){
77
+ // A fresh Windows user may have Chrome but no signed-in ChatGPT profile.
78
+ // Keep the original Device Code alive while they sign in; never send
79
+ // a positive proof, register an Agent, or switch Chrome profiles here.
80
+ const reason=local?.auth;
81
+ if(local?.state!=='auth_required'||local?.redacted!==true||
82
+ !['missing','expired','invalid','ambiguous','browser_busy'].includes(reason))
83
+ throw new Error('CHATGPT_LOCAL_SESSION_REQUIRED');
84
+ if(!reportedAuthReasons.has(reason)){
85
+ reportedAuthReasons.add(reason);
86
+ await onAuthRequired({reason});
87
+ }
88
+ continue;
89
+ }
77
90
  const confirm=await invoke('/device/auth-result',{device_code:code.device_code,
78
91
  code_verifier:verifier,device_secret:secret,
79
92
  result:{state:'auth_valid',auth:'valid',runtime:'ready',redacted:true}});
@@ -44,6 +44,8 @@ export function isOwnedZeroAgent(info){
44
44
  const legacy=(script==='source/agent/main.mjs'||script.endsWith('/zero_server/source/agent/main.mjs'))&&!match[5]&&!match[6];
45
45
  const standalone=(script==='bin/zero-agent.mjs'||script==='./bin/zero-agent.mjs'||
46
46
  script.endsWith('/zero-agent/bin/zero-agent.mjs')||
47
+ // Exact published package path. Do not accept lookalike package names.
48
+ script.endsWith('/@dev-zero/mcp-agent/bin/zero-agent.mjs')||
47
49
  script.endsWith('/zero-server-agent/bin/zero-agent.mjs'))&&
48
50
  ['start','remote'].includes((match[5]||'').toLowerCase());
49
51
  return legacy||standalone;