dsh-github-studio 0.6.0 → 0.6.2
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/lib/client.js +402 -486
- package/lib/core.js +89 -93
- package/lib/core.mjs +89 -93
- package/lib/diagnostics.js +22 -22
- package/lib/diagnostics.mjs +22 -22
- package/lib/gh.js +15 -15
- package/lib/gh.mjs +15 -15
- package/lib/http.js +47 -50
- package/lib/http.mjs +47 -50
- package/lib/index.js +21 -23
- package/lib/program-inspect.js +24 -50
- package/lib/program-inspect.mjs +24 -50
- package/lib/release-copy.js +59 -62
- package/lib/release-copy.mjs +59 -62
- package/lib/repository-name.js +8 -8
- package/lib/repository-name.mjs +8 -8
- package/lib/search.js +28 -28
- package/lib/search.mjs +28 -28
- package/lib/tools.js +22 -22
- package/lib/tools.mjs +22 -22
- package/package.json +1 -1
- package/lib/drafts.js +0 -20
- package/lib/drafts.mjs +0 -20
package/lib/gh.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import {spawn} from 'node:child_process';
|
|
2
|
-
import {mkdir,readFile,writeFile,unlink} from 'node:fs/promises';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
export function command(exe,args,{input='',timeout=30000}={}){return new Promise((resolve,reject)=>{const child=spawn(exe,args,{windowsHide:true,stdio:['pipe','pipe','pipe']});let stdout='';const timer=setTimeout(()=>{child.kill();reject(Error('凭据操作超时。'));},timeout);child.on('error',e=>{clearTimeout(timer);reject(e);});child.stdout.on('data',b=>stdout+=b);child.stderr.resume();child.on('close',code=>{clearTimeout(timer);resolve({code,stdout});});child.stdin.on('error',()=>{});child.stdin.end(input);});}
|
|
5
|
-
export async function windowsSeal(action,value){if(process.platform!=='win32')throw Error('本版凭据保护仅支持 Windows。');const operation=action==='protect'?'Protect':'Unprotect';const script=`Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim()); $r=[Security.Cryptography.ProtectedData]::${operation}($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Write([Convert]::ToBase64String($r))`;const r=await command('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{input:action==='protect'?Buffer.from(value,'utf8').toString('base64'):value});if(r.code!==0)throw Error('Windows 凭据加密失败。');return action==='protect'?r.stdout.trim():Buffer.from(r.stdout.trim(),'base64').toString('utf8');}
|
|
6
|
-
export class GhAuth{
|
|
7
|
-
constructor(root,{fetchImpl=fetch,seal=windowsSeal,sleep=ms=>new Promise(r=>setTimeout(r,ms)),diagnostics=()=>{}}={}){this.root=root;this.fetch=fetchImpl;this.seal=seal;this.sleep=sleep;this.diagnostics=diagnostics;this.login={state:'idle'};}
|
|
8
|
-
async clientId(){try{return JSON.parse(await readFile(path.join(this.root,'oauth.json'),'utf8')).clientId;}catch{if(process.env.DSH_GITHUB_CLIENT_ID)return process.env.DSH_GITHUB_CLIENT_ID;try{return JSON.parse(await readFile(new URL('./publisher.json',import.meta.url),'utf8')).clientId??'';}catch{return '';}}}
|
|
9
|
-
async configure(clientId){if(!/^[A-Za-z0-9_.-]{5,120}$/.test(clientId))throw Error('请输入有效的 OAuth App Client ID。');if(['preparing','waiting'].includes(this.login.state))throw Error('请先完成当前登录。');await mkdir(this.root,{recursive:true});await writeFile(path.join(this.root,'oauth.json'),JSON.stringify({clientId}));}
|
|
10
|
-
async hasCredential(){try{await readFile(path.join(this.root,'credential.dpapi'));return true;}catch{return false;}}
|
|
11
|
-
async token(){let encrypted;try{encrypted=await readFile(path.join(this.root,'credential.dpapi'),'utf8');}catch(e){this.diagnostics('credential_read',{reason:e.code==='ENOENT'?'missing':'read_failed',hasCredential:false});throw Error('请先在设置 → GitHub 中登录。');}let token;try{token=await this.seal('unprotect',encrypted);}catch{this.diagnostics('credential_read',{reason:'decrypt_failed',hasCredential:true});throw Error('本机 GitHub 凭据无法解密,请在设置 → GitHub 重新连接。');}if(typeof token!=='string'||!token.trim()){this.diagnostics('credential_read',{reason:'invalid_local',hasCredential:true});throw Error('本机 GitHub 凭据为空,请重新连接。');}this.diagnostics('credential_read',{reason:'ok',hasCredential:true});return token;}
|
|
12
|
-
async request(url,fields){const r=await this.fetch(url,{method:'POST',headers:{Accept:'application/json','Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams(fields),signal:AbortSignal.timeout(30000),redirect:'error'});if(!r.ok)throw Error(`GitHub 授权请求失败(${r.status})。`);return r.json();}
|
|
13
|
-
async start(){if(['preparing','waiting'].includes(this.login.state))return this.login;this.login={state:'preparing'};let clientId;try{clientId=await this.clientId();if(!clientId)throw Error('请先配置插件发布者的 GitHub OAuth App Client ID,并启用 Device Flow。');}catch(e){this.login={state:'error',message:e.message};throw e;}this.diagnostics('oauth_started',{category:'authorization'});
|
|
14
|
-
this.task=(async()=>{try{const d=await this.request('https://github.com/login/device/code',{client_id:clientId,scope:'repo'});if(d.error||!d.device_code||!d.user_code)throw Object.assign(Error(d.error_description??'设备授权未启用,请检查 OAuth App 配置。'),{reason:d.error});this.diagnostics('oauth_waiting',{category:'authorization'});this.login={state:'waiting',code:d.user_code,url:'https://github.com/login/device'};let interval=Math.max(5,Number(d.interval)||5),deadline=Date.now()+Math.min(900,Number(d.expires_in)||900)*1000;while(Date.now()<deadline){await this.sleep(interval*1000);const r=await this.request('https://github.com/login/oauth/access_token',{client_id:clientId,device_code:d.device_code,grant_type:'urn:ietf:params:oauth:grant-type:device_code'});if(r.access_token){await mkdir(this.root,{recursive:true});await writeFile(path.join(this.root,'credential.dpapi'),await this.seal('protect',r.access_token),{mode:0o600});this.diagnostics('credential_saved',{reason:'ok',hasCredential:true});this.login={state:'complete'};return;}if(r.error==='authorization_pending')continue;if(r.error==='slow_down'){interval+=5;continue;}throw Object.assign(Error(r.error_description??'授权已取消或过期,请重新登录。'),{reason:r.error});}throw Object.assign(Error('授权已过期,请重新登录。'),{reason:'expired_token'});}catch(e){this.diagnostics('oauth_failed',{category:'authorization',reason:e.reason??'authorization_failed'});this.login={state:'error',message:e.message};}})();return this.login;}
|
|
15
|
-
async logout(){if(['preparing','waiting'].includes(this.login.state))throw Error('请先完成或取消浏览器中的登录。');await unlink(path.join(this.root,'credential.dpapi')).catch(e=>{if(e.code!=='ENOENT')throw e;});this.diagnostics('logout',{reason:'local_disconnect',hasCredential:false});this.login={state:'idle'};}
|
|
1
|
+
import {spawn} from 'node:child_process';
|
|
2
|
+
import {mkdir,readFile,writeFile,unlink} from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
export function command(exe,args,{input='',timeout=30000}={}){return new Promise((resolve,reject)=>{const child=spawn(exe,args,{windowsHide:true,stdio:['pipe','pipe','pipe']});let stdout='';const timer=setTimeout(()=>{child.kill();reject(Error('凭据操作超时。'));},timeout);child.on('error',e=>{clearTimeout(timer);reject(e);});child.stdout.on('data',b=>stdout+=b);child.stderr.resume();child.on('close',code=>{clearTimeout(timer);resolve({code,stdout});});child.stdin.on('error',()=>{});child.stdin.end(input);});}
|
|
5
|
+
export async function windowsSeal(action,value){if(process.platform!=='win32')throw Error('本版凭据保护仅支持 Windows。');const operation=action==='protect'?'Protect':'Unprotect';const script=`Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim()); $r=[Security.Cryptography.ProtectedData]::${operation}($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Write([Convert]::ToBase64String($r))`;const r=await command('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{input:action==='protect'?Buffer.from(value,'utf8').toString('base64'):value});if(r.code!==0)throw Error('Windows 凭据加密失败。');return action==='protect'?r.stdout.trim():Buffer.from(r.stdout.trim(),'base64').toString('utf8');}
|
|
6
|
+
export class GhAuth{
|
|
7
|
+
constructor(root,{fetchImpl=fetch,seal=windowsSeal,sleep=ms=>new Promise(r=>setTimeout(r,ms)),diagnostics=()=>{}}={}){this.root=root;this.fetch=fetchImpl;this.seal=seal;this.sleep=sleep;this.diagnostics=diagnostics;this.login={state:'idle'};}
|
|
8
|
+
async clientId(){try{return JSON.parse(await readFile(path.join(this.root,'oauth.json'),'utf8')).clientId;}catch{if(process.env.DSH_GITHUB_CLIENT_ID)return process.env.DSH_GITHUB_CLIENT_ID;try{return JSON.parse(await readFile(new URL('./publisher.json',import.meta.url),'utf8')).clientId??'';}catch{return '';}}}
|
|
9
|
+
async configure(clientId){if(!/^[A-Za-z0-9_.-]{5,120}$/.test(clientId))throw Error('请输入有效的 OAuth App Client ID。');if(['preparing','waiting'].includes(this.login.state))throw Error('请先完成当前登录。');await mkdir(this.root,{recursive:true});await writeFile(path.join(this.root,'oauth.json'),JSON.stringify({clientId}));}
|
|
10
|
+
async hasCredential(){try{await readFile(path.join(this.root,'credential.dpapi'));return true;}catch{return false;}}
|
|
11
|
+
async token(){let encrypted;try{encrypted=await readFile(path.join(this.root,'credential.dpapi'),'utf8');}catch(e){this.diagnostics('credential_read',{reason:e.code==='ENOENT'?'missing':'read_failed',hasCredential:false});throw Error('请先在设置 → GitHub 中登录。');}let token;try{token=await this.seal('unprotect',encrypted);}catch{this.diagnostics('credential_read',{reason:'decrypt_failed',hasCredential:true});throw Error('本机 GitHub 凭据无法解密,请在设置 → GitHub 重新连接。');}if(typeof token!=='string'||!token.trim()){this.diagnostics('credential_read',{reason:'invalid_local',hasCredential:true});throw Error('本机 GitHub 凭据为空,请重新连接。');}this.diagnostics('credential_read',{reason:'ok',hasCredential:true});return token;}
|
|
12
|
+
async request(url,fields){const r=await this.fetch(url,{method:'POST',headers:{Accept:'application/json','Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams(fields),signal:AbortSignal.timeout(30000),redirect:'error'});if(!r.ok)throw Error(`GitHub 授权请求失败(${r.status})。`);return r.json();}
|
|
13
|
+
async start(){if(['preparing','waiting'].includes(this.login.state))return this.login;this.login={state:'preparing'};let clientId;try{clientId=await this.clientId();if(!clientId)throw Error('请先配置插件发布者的 GitHub OAuth App Client ID,并启用 Device Flow。');}catch(e){this.login={state:'error',message:e.message};throw e;}this.diagnostics('oauth_started',{category:'authorization'});
|
|
14
|
+
this.task=(async()=>{try{const d=await this.request('https://github.com/login/device/code',{client_id:clientId,scope:'repo'});if(d.error||!d.device_code||!d.user_code)throw Object.assign(Error(d.error_description??'设备授权未启用,请检查 OAuth App 配置。'),{reason:d.error});this.diagnostics('oauth_waiting',{category:'authorization'});this.login={state:'waiting',code:d.user_code,url:'https://github.com/login/device'};let interval=Math.max(5,Number(d.interval)||5),deadline=Date.now()+Math.min(900,Number(d.expires_in)||900)*1000;while(Date.now()<deadline){await this.sleep(interval*1000);const r=await this.request('https://github.com/login/oauth/access_token',{client_id:clientId,device_code:d.device_code,grant_type:'urn:ietf:params:oauth:grant-type:device_code'});if(r.access_token){await mkdir(this.root,{recursive:true});await writeFile(path.join(this.root,'credential.dpapi'),await this.seal('protect',r.access_token),{mode:0o600});this.diagnostics('credential_saved',{reason:'ok',hasCredential:true});this.login={state:'complete'};return;}if(r.error==='authorization_pending')continue;if(r.error==='slow_down'){interval+=5;continue;}throw Object.assign(Error(r.error_description??'授权已取消或过期,请重新登录。'),{reason:r.error});}throw Object.assign(Error('授权已过期,请重新登录。'),{reason:'expired_token'});}catch(e){this.diagnostics('oauth_failed',{category:'authorization',reason:e.reason??'authorization_failed'});this.login={state:'error',message:e.message};}})();return this.login;}
|
|
15
|
+
async logout(){if(['preparing','waiting'].includes(this.login.state))throw Error('请先完成或取消浏览器中的登录。');await unlink(path.join(this.root,'credential.dpapi')).catch(e=>{if(e.code!=='ENOENT')throw e;});this.diagnostics('logout',{reason:'local_disconnect',hasCredential:false});this.login={state:'idle'};}
|
|
16
16
|
}
|
package/lib/gh.mjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import {spawn} from 'node:child_process';
|
|
2
|
-
import {mkdir,readFile,writeFile,unlink} from 'node:fs/promises';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
export function command(exe,args,{input='',timeout=30000}={}){return new Promise((resolve,reject)=>{const child=spawn(exe,args,{windowsHide:true,stdio:['pipe','pipe','pipe']});let stdout='';const timer=setTimeout(()=>{child.kill();reject(Error('凭据操作超时。'));},timeout);child.on('error',e=>{clearTimeout(timer);reject(e);});child.stdout.on('data',b=>stdout+=b);child.stderr.resume();child.on('close',code=>{clearTimeout(timer);resolve({code,stdout});});child.stdin.on('error',()=>{});child.stdin.end(input);});}
|
|
5
|
-
export async function windowsSeal(action,value){if(process.platform!=='win32')throw Error('本版凭据保护仅支持 Windows。');const operation=action==='protect'?'Protect':'Unprotect';const script=`Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim()); $r=[Security.Cryptography.ProtectedData]::${operation}($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Write([Convert]::ToBase64String($r))`;const r=await command('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{input:action==='protect'?Buffer.from(value,'utf8').toString('base64'):value});if(r.code!==0)throw Error('Windows 凭据加密失败。');return action==='protect'?r.stdout.trim():Buffer.from(r.stdout.trim(),'base64').toString('utf8');}
|
|
6
|
-
export class GhAuth{
|
|
7
|
-
constructor(root,{fetchImpl=fetch,seal=windowsSeal,sleep=ms=>new Promise(r=>setTimeout(r,ms)),diagnostics=()=>{}}={}){this.root=root;this.fetch=fetchImpl;this.seal=seal;this.sleep=sleep;this.diagnostics=diagnostics;this.login={state:'idle'};}
|
|
8
|
-
async clientId(){try{return JSON.parse(await readFile(path.join(this.root,'oauth.json'),'utf8')).clientId;}catch{if(process.env.DSH_GITHUB_CLIENT_ID)return process.env.DSH_GITHUB_CLIENT_ID;try{return JSON.parse(await readFile(new URL('./publisher.json',import.meta.url),'utf8')).clientId??'';}catch{return '';}}}
|
|
9
|
-
async configure(clientId){if(!/^[A-Za-z0-9_.-]{5,120}$/.test(clientId))throw Error('请输入有效的 OAuth App Client ID。');if(['preparing','waiting'].includes(this.login.state))throw Error('请先完成当前登录。');await mkdir(this.root,{recursive:true});await writeFile(path.join(this.root,'oauth.json'),JSON.stringify({clientId}));}
|
|
10
|
-
async hasCredential(){try{await readFile(path.join(this.root,'credential.dpapi'));return true;}catch{return false;}}
|
|
11
|
-
async token(){let encrypted;try{encrypted=await readFile(path.join(this.root,'credential.dpapi'),'utf8');}catch(e){this.diagnostics('credential_read',{reason:e.code==='ENOENT'?'missing':'read_failed',hasCredential:false});throw Error('请先在设置 → GitHub 中登录。');}let token;try{token=await this.seal('unprotect',encrypted);}catch{this.diagnostics('credential_read',{reason:'decrypt_failed',hasCredential:true});throw Error('本机 GitHub 凭据无法解密,请在设置 → GitHub 重新连接。');}if(typeof token!=='string'||!token.trim()){this.diagnostics('credential_read',{reason:'invalid_local',hasCredential:true});throw Error('本机 GitHub 凭据为空,请重新连接。');}this.diagnostics('credential_read',{reason:'ok',hasCredential:true});return token;}
|
|
12
|
-
async request(url,fields){const r=await this.fetch(url,{method:'POST',headers:{Accept:'application/json','Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams(fields),signal:AbortSignal.timeout(30000),redirect:'error'});if(!r.ok)throw Error(`GitHub 授权请求失败(${r.status})。`);return r.json();}
|
|
13
|
-
async start(){if(['preparing','waiting'].includes(this.login.state))return this.login;this.login={state:'preparing'};let clientId;try{clientId=await this.clientId();if(!clientId)throw Error('请先配置插件发布者的 GitHub OAuth App Client ID,并启用 Device Flow。');}catch(e){this.login={state:'error',message:e.message};throw e;}this.diagnostics('oauth_started',{category:'authorization'});
|
|
14
|
-
this.task=(async()=>{try{const d=await this.request('https://github.com/login/device/code',{client_id:clientId,scope:'repo'});if(d.error||!d.device_code||!d.user_code)throw Object.assign(Error(d.error_description??'设备授权未启用,请检查 OAuth App 配置。'),{reason:d.error});this.diagnostics('oauth_waiting',{category:'authorization'});this.login={state:'waiting',code:d.user_code,url:'https://github.com/login/device'};let interval=Math.max(5,Number(d.interval)||5),deadline=Date.now()+Math.min(900,Number(d.expires_in)||900)*1000;while(Date.now()<deadline){await this.sleep(interval*1000);const r=await this.request('https://github.com/login/oauth/access_token',{client_id:clientId,device_code:d.device_code,grant_type:'urn:ietf:params:oauth:grant-type:device_code'});if(r.access_token){await mkdir(this.root,{recursive:true});await writeFile(path.join(this.root,'credential.dpapi'),await this.seal('protect',r.access_token),{mode:0o600});this.diagnostics('credential_saved',{reason:'ok',hasCredential:true});this.login={state:'complete'};return;}if(r.error==='authorization_pending')continue;if(r.error==='slow_down'){interval+=5;continue;}throw Object.assign(Error(r.error_description??'授权已取消或过期,请重新登录。'),{reason:r.error});}throw Object.assign(Error('授权已过期,请重新登录。'),{reason:'expired_token'});}catch(e){this.diagnostics('oauth_failed',{category:'authorization',reason:e.reason??'authorization_failed'});this.login={state:'error',message:e.message};}})();return this.login;}
|
|
15
|
-
async logout(){if(['preparing','waiting'].includes(this.login.state))throw Error('请先完成或取消浏览器中的登录。');await unlink(path.join(this.root,'credential.dpapi')).catch(e=>{if(e.code!=='ENOENT')throw e;});this.diagnostics('logout',{reason:'local_disconnect',hasCredential:false});this.login={state:'idle'};}
|
|
1
|
+
import {spawn} from 'node:child_process';
|
|
2
|
+
import {mkdir,readFile,writeFile,unlink} from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
export function command(exe,args,{input='',timeout=30000}={}){return new Promise((resolve,reject)=>{const child=spawn(exe,args,{windowsHide:true,stdio:['pipe','pipe','pipe']});let stdout='';const timer=setTimeout(()=>{child.kill();reject(Error('凭据操作超时。'));},timeout);child.on('error',e=>{clearTimeout(timer);reject(e);});child.stdout.on('data',b=>stdout+=b);child.stderr.resume();child.on('close',code=>{clearTimeout(timer);resolve({code,stdout});});child.stdin.on('error',()=>{});child.stdin.end(input);});}
|
|
5
|
+
export async function windowsSeal(action,value){if(process.platform!=='win32')throw Error('本版凭据保护仅支持 Windows。');const operation=action==='protect'?'Protect':'Unprotect';const script=`Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim()); $r=[Security.Cryptography.ProtectedData]::${operation}($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Write([Convert]::ToBase64String($r))`;const r=await command('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{input:action==='protect'?Buffer.from(value,'utf8').toString('base64'):value});if(r.code!==0)throw Error('Windows 凭据加密失败。');return action==='protect'?r.stdout.trim():Buffer.from(r.stdout.trim(),'base64').toString('utf8');}
|
|
6
|
+
export class GhAuth{
|
|
7
|
+
constructor(root,{fetchImpl=fetch,seal=windowsSeal,sleep=ms=>new Promise(r=>setTimeout(r,ms)),diagnostics=()=>{}}={}){this.root=root;this.fetch=fetchImpl;this.seal=seal;this.sleep=sleep;this.diagnostics=diagnostics;this.login={state:'idle'};}
|
|
8
|
+
async clientId(){try{return JSON.parse(await readFile(path.join(this.root,'oauth.json'),'utf8')).clientId;}catch{if(process.env.DSH_GITHUB_CLIENT_ID)return process.env.DSH_GITHUB_CLIENT_ID;try{return JSON.parse(await readFile(new URL('./publisher.json',import.meta.url),'utf8')).clientId??'';}catch{return '';}}}
|
|
9
|
+
async configure(clientId){if(!/^[A-Za-z0-9_.-]{5,120}$/.test(clientId))throw Error('请输入有效的 OAuth App Client ID。');if(['preparing','waiting'].includes(this.login.state))throw Error('请先完成当前登录。');await mkdir(this.root,{recursive:true});await writeFile(path.join(this.root,'oauth.json'),JSON.stringify({clientId}));}
|
|
10
|
+
async hasCredential(){try{await readFile(path.join(this.root,'credential.dpapi'));return true;}catch{return false;}}
|
|
11
|
+
async token(){let encrypted;try{encrypted=await readFile(path.join(this.root,'credential.dpapi'),'utf8');}catch(e){this.diagnostics('credential_read',{reason:e.code==='ENOENT'?'missing':'read_failed',hasCredential:false});throw Error('请先在设置 → GitHub 中登录。');}let token;try{token=await this.seal('unprotect',encrypted);}catch{this.diagnostics('credential_read',{reason:'decrypt_failed',hasCredential:true});throw Error('本机 GitHub 凭据无法解密,请在设置 → GitHub 重新连接。');}if(typeof token!=='string'||!token.trim()){this.diagnostics('credential_read',{reason:'invalid_local',hasCredential:true});throw Error('本机 GitHub 凭据为空,请重新连接。');}this.diagnostics('credential_read',{reason:'ok',hasCredential:true});return token;}
|
|
12
|
+
async request(url,fields){const r=await this.fetch(url,{method:'POST',headers:{Accept:'application/json','Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams(fields),signal:AbortSignal.timeout(30000),redirect:'error'});if(!r.ok)throw Error(`GitHub 授权请求失败(${r.status})。`);return r.json();}
|
|
13
|
+
async start(){if(['preparing','waiting'].includes(this.login.state))return this.login;this.login={state:'preparing'};let clientId;try{clientId=await this.clientId();if(!clientId)throw Error('请先配置插件发布者的 GitHub OAuth App Client ID,并启用 Device Flow。');}catch(e){this.login={state:'error',message:e.message};throw e;}this.diagnostics('oauth_started',{category:'authorization'});
|
|
14
|
+
this.task=(async()=>{try{const d=await this.request('https://github.com/login/device/code',{client_id:clientId,scope:'repo'});if(d.error||!d.device_code||!d.user_code)throw Object.assign(Error(d.error_description??'设备授权未启用,请检查 OAuth App 配置。'),{reason:d.error});this.diagnostics('oauth_waiting',{category:'authorization'});this.login={state:'waiting',code:d.user_code,url:'https://github.com/login/device'};let interval=Math.max(5,Number(d.interval)||5),deadline=Date.now()+Math.min(900,Number(d.expires_in)||900)*1000;while(Date.now()<deadline){await this.sleep(interval*1000);const r=await this.request('https://github.com/login/oauth/access_token',{client_id:clientId,device_code:d.device_code,grant_type:'urn:ietf:params:oauth:grant-type:device_code'});if(r.access_token){await mkdir(this.root,{recursive:true});await writeFile(path.join(this.root,'credential.dpapi'),await this.seal('protect',r.access_token),{mode:0o600});this.diagnostics('credential_saved',{reason:'ok',hasCredential:true});this.login={state:'complete'};return;}if(r.error==='authorization_pending')continue;if(r.error==='slow_down'){interval+=5;continue;}throw Object.assign(Error(r.error_description??'授权已取消或过期,请重新登录。'),{reason:r.error});}throw Object.assign(Error('授权已过期,请重新登录。'),{reason:'expired_token'});}catch(e){this.diagnostics('oauth_failed',{category:'authorization',reason:e.reason??'authorization_failed'});this.login={state:'error',message:e.message};}})();return this.login;}
|
|
15
|
+
async logout(){if(['preparing','waiting'].includes(this.login.state))throw Error('请先完成或取消浏览器中的登录。');await unlink(path.join(this.root,'credential.dpapi')).catch(e=>{if(e.code!=='ENOENT')throw e;});this.diagnostics('logout',{reason:'local_disconnect',hasCredential:false});this.login={state:'idle'};}
|
|
16
16
|
}
|
package/lib/http.js
CHANGED
|
@@ -1,50 +1,47 @@
|
|
|
1
|
-
import {randomUUID} from 'node:crypto';
|
|
2
|
-
import {createWriteStream} from 'node:fs';
|
|
3
|
-
import {unlink} from 'node:fs/promises';
|
|
4
|
-
import {pipeline} from 'node:stream/promises';
|
|
5
|
-
import {Transform} from 'node:stream';
|
|
6
|
-
import path from 'node:path';
|
|
7
|
-
|
|
8
|
-
export const API='/dsh-github/api/';
|
|
9
|
-
const ROUTES={state:'GET',repos:'GET',contents:'GET',releases:'GET','auth/start':'POST','auth/configure':'POST','auth/logout':'POST',prepare:'POST',confirm:'POST',reject:'POST',upload:'POST','attachment/remove':'POST','ai/copy':'POST','ai/program':'POST'
|
|
10
|
-
const json=(res,status,value)=>{res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});res.end(JSON.stringify(value));};
|
|
11
|
-
async function body(req){let size=0;const parts=[];for await(const b of req){size+=b.length;if(size>3*1024*1024)throw Error('请求内容过大。');parts.push(b);}return JSON.parse(Buffer.concat(parts).toString('utf8')||'{}');}
|
|
12
|
-
export function admitted(req,connection){
|
|
13
|
-
if(!connection||typeof connection.admit!=='function'||!connection.browserPeer)return false;
|
|
14
|
-
try{if(connection.admit(req).peer!==connection.browserPeer)return false;}catch{return false;}
|
|
15
|
-
const remote=req.socket?.remoteAddress;if(remote&&!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(remote))return false;
|
|
16
|
-
const origin=req.headers.origin;if(origin&&origin!=='null'){try{if(new URL(origin).host!==req.headers.host)return false;}catch{return false;}}
|
|
17
|
-
if(req.headers['sec-fetch-site']==='cross-site')return false;
|
|
18
|
-
return true;
|
|
19
|
-
}
|
|
20
|
-
export function routes({api,ops,auth,root,connection,releaseCopy
|
|
21
|
-
return Object.entries(ROUTES).map(([name,method])=>({kind:'exact',path:API+name,handler:async(req,res)=>{
|
|
22
|
-
if(!admitted(req,connection()))return json(res,403,{error:'需要本机已认证的 DeepSeek Harness 页面。'});
|
|
23
|
-
if(req.method!==method)return json(res,405,{error:'请求方法不正确。'});
|
|
24
|
-
try{const url=new URL(req.url,'http://localhost');const q=Object.fromEntries(url.searchParams);let result;
|
|
25
|
-
if(name==='state'){let user=null,error=null;try{user=await api.me();}catch(e){error=e.message;}result={user,error,clientId:await auth.clientId(),hasCredential:await auth.hasCredential(),login:auth.login,operations:ops.list(),attachments:ops.assetList()};}
|
|
26
|
-
else if(name==='repos')result=await api.repos(q.page??1);
|
|
27
|
-
else if(name==='contents')result=await api.contents(q);
|
|
28
|
-
else if(name==='releases')result=await api.releaseList(q);
|
|
29
|
-
else if(name==='upload'){
|
|
30
|
-
const raw=req.headers['x-file-name'];if(typeof raw!=='string')throw Error('缺少附件名称。');const fileName=decodeURIComponent(raw);const
|
|
31
|
-
const limit=new Transform({transform(chunk,encoding,done){size+=chunk.length;if(size>=2*1024**3)done(Error('附件必须小于 2 GiB。'));else done(null,chunk);}});
|
|
32
|
-
try{await pipeline(req,limit,createWriteStream(disk,{flags:'wx',mode:0o600}));result=await ops.addAsset(fileName,disk,id
|
|
33
|
-
}else{const a=await body(req);
|
|
34
|
-
if(name==='ai/program'){if(!releaseCopy)throw Error('AI介绍服务未就绪。');result=await releaseCopy.describeProgram(a);}
|
|
35
|
-
else if(name==='ai/copy'){if(!releaseCopy)throw Error('AI文案服务尚未就绪。');result=await releaseCopy.create(a);}
|
|
36
|
-
else if(name==='
|
|
37
|
-
else if(name==='
|
|
38
|
-
else if(name==='
|
|
39
|
-
else if(name==='
|
|
40
|
-
else if(name==='
|
|
41
|
-
else if(name==='
|
|
42
|
-
else if(name==='
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}catch(e){if(!res.destroyed&&!res.writableEnded)json(res,e.status??400,{error:e.message});}
|
|
49
|
-
}}));
|
|
50
|
-
}
|
|
1
|
+
import {randomUUID} from 'node:crypto';
|
|
2
|
+
import {createWriteStream} from 'node:fs';
|
|
3
|
+
import {unlink} from 'node:fs/promises';
|
|
4
|
+
import {pipeline} from 'node:stream/promises';
|
|
5
|
+
import {Transform} from 'node:stream';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
export const API='/dsh-github/api/';
|
|
9
|
+
const ROUTES={state:'GET',repos:'GET',contents:'GET',releases:'GET','auth/start':'POST','auth/configure':'POST','auth/logout':'POST',prepare:'POST',confirm:'POST',reject:'POST',upload:'POST','attachment/remove':'POST','ai/copy':'POST','ai/program':'POST'};
|
|
10
|
+
const json=(res,status,value)=>{res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});res.end(JSON.stringify(value));};
|
|
11
|
+
async function body(req){let size=0;const parts=[];for await(const b of req){size+=b.length;if(size>3*1024*1024)throw Error('请求内容过大。');parts.push(b);}return JSON.parse(Buffer.concat(parts).toString('utf8')||'{}');}
|
|
12
|
+
export function admitted(req,connection){
|
|
13
|
+
if(!connection||typeof connection.admit!=='function'||!connection.browserPeer)return false;
|
|
14
|
+
try{if(connection.admit(req).peer!==connection.browserPeer)return false;}catch{return false;}
|
|
15
|
+
const remote=req.socket?.remoteAddress;if(remote&&!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(remote))return false;
|
|
16
|
+
const origin=req.headers.origin;if(origin&&origin!=='null'){try{if(new URL(origin).host!==req.headers.host)return false;}catch{return false;}}
|
|
17
|
+
if(req.headers['sec-fetch-site']==='cross-site')return false;
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
export function routes({api,ops,auth,root,connection,releaseCopy}){
|
|
21
|
+
return Object.entries(ROUTES).map(([name,method])=>({kind:'exact',path:API+name,handler:async(req,res)=>{
|
|
22
|
+
if(!admitted(req,connection()))return json(res,403,{error:'需要本机已认证的 DeepSeek Harness 页面。'});
|
|
23
|
+
if(req.method!==method)return json(res,405,{error:'请求方法不正确。'});
|
|
24
|
+
try{const url=new URL(req.url,'http://localhost');const q=Object.fromEntries(url.searchParams);let result;
|
|
25
|
+
if(name==='state'){let user=null,error=null,errorKind=null;try{user=await api.me();}catch(e){error=e.message;errorKind=!e.status?'network':e.status===401?'auth':e.status===403||e.status===429?'rate-limit':e.status>=500?'server':'other';}result={user,error,errorKind,clientId:await auth.clientId(),hasCredential:await auth.hasCredential(),login:auth.login,operations:ops.list(),attachments:ops.assetList()};}
|
|
26
|
+
else if(name==='repos')result=await api.repos(q.page??1);
|
|
27
|
+
else if(name==='contents')result=await api.contents(q);
|
|
28
|
+
else if(name==='releases')result=await api.releaseList(q);
|
|
29
|
+
else if(name==='upload'){
|
|
30
|
+
const raw=req.headers['x-file-name'];if(typeof raw!=='string')throw Error('缺少附件名称。');const fileName=decodeURIComponent(raw);const id=randomUUID(),disk=path.join(root,'attachments',id);let size=0;
|
|
31
|
+
const limit=new Transform({transform(chunk,encoding,done){size+=chunk.length;if(size>=2*1024**3)done(Error('附件必须小于 2 GiB。'));else done(null,chunk);}});
|
|
32
|
+
try{await pipeline(req,limit,createWriteStream(disk,{flags:'wx',mode:0o600}));result=await ops.addAsset(fileName,disk,id);}catch(e){await unlink(disk).catch(()=>{});throw e;}
|
|
33
|
+
}else{const a=await body(req);
|
|
34
|
+
if(name==='ai/program'){if(!releaseCopy)throw Error('AI介绍服务未就绪。');result=await releaseCopy.describeProgram(a);}
|
|
35
|
+
else if(name==='ai/copy'){if(!releaseCopy)throw Error('AI文案服务尚未就绪。');result=await releaseCopy.create(a);}
|
|
36
|
+
else if(name==='auth/start')result=await auth.start();
|
|
37
|
+
else if(name==='auth/configure'){await auth.configure(a.clientId);result={ok:true};}
|
|
38
|
+
else if(name==='auth/logout'){await auth.logout();ops.clearPending();result={ok:true};}
|
|
39
|
+
else if(name==='prepare')result=await ops.prepare(a.kind,a.args);
|
|
40
|
+
else if(name==='confirm')result=await ops.confirm(a.id);
|
|
41
|
+
else if(name==='reject')result=ops.reject(a.id);
|
|
42
|
+
else if(name==='attachment/remove'){await ops.removeAsset(a.id);result={ok:true};}
|
|
43
|
+
}
|
|
44
|
+
json(res,200,result);
|
|
45
|
+
}catch(e){if(!res.destroyed&&!res.writableEnded)json(res,e.status??400,{error:e.message});}
|
|
46
|
+
}}));
|
|
47
|
+
}
|
package/lib/http.mjs
CHANGED
|
@@ -1,50 +1,47 @@
|
|
|
1
|
-
import {randomUUID} from 'node:crypto';
|
|
2
|
-
import {createWriteStream} from 'node:fs';
|
|
3
|
-
import {unlink} from 'node:fs/promises';
|
|
4
|
-
import {pipeline} from 'node:stream/promises';
|
|
5
|
-
import {Transform} from 'node:stream';
|
|
6
|
-
import path from 'node:path';
|
|
7
|
-
|
|
8
|
-
export const API='/dsh-github/api/';
|
|
9
|
-
const ROUTES={state:'GET',repos:'GET',contents:'GET',releases:'GET','auth/start':'POST','auth/configure':'POST','auth/logout':'POST',prepare:'POST',confirm:'POST',reject:'POST',upload:'POST','attachment/remove':'POST','ai/copy':'POST','ai/program':'POST'
|
|
10
|
-
const json=(res,status,value)=>{res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});res.end(JSON.stringify(value));};
|
|
11
|
-
async function body(req){let size=0;const parts=[];for await(const b of req){size+=b.length;if(size>3*1024*1024)throw Error('请求内容过大。');parts.push(b);}return JSON.parse(Buffer.concat(parts).toString('utf8')||'{}');}
|
|
12
|
-
export function admitted(req,connection){
|
|
13
|
-
if(!connection||typeof connection.admit!=='function'||!connection.browserPeer)return false;
|
|
14
|
-
try{if(connection.admit(req).peer!==connection.browserPeer)return false;}catch{return false;}
|
|
15
|
-
const remote=req.socket?.remoteAddress;if(remote&&!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(remote))return false;
|
|
16
|
-
const origin=req.headers.origin;if(origin&&origin!=='null'){try{if(new URL(origin).host!==req.headers.host)return false;}catch{return false;}}
|
|
17
|
-
if(req.headers['sec-fetch-site']==='cross-site')return false;
|
|
18
|
-
return true;
|
|
19
|
-
}
|
|
20
|
-
export function routes({api,ops,auth,root,connection,releaseCopy
|
|
21
|
-
return Object.entries(ROUTES).map(([name,method])=>({kind:'exact',path:API+name,handler:async(req,res)=>{
|
|
22
|
-
if(!admitted(req,connection()))return json(res,403,{error:'需要本机已认证的 DeepSeek Harness 页面。'});
|
|
23
|
-
if(req.method!==method)return json(res,405,{error:'请求方法不正确。'});
|
|
24
|
-
try{const url=new URL(req.url,'http://localhost');const q=Object.fromEntries(url.searchParams);let result;
|
|
25
|
-
if(name==='state'){let user=null,error=null;try{user=await api.me();}catch(e){error=e.message;}result={user,error,clientId:await auth.clientId(),hasCredential:await auth.hasCredential(),login:auth.login,operations:ops.list(),attachments:ops.assetList()};}
|
|
26
|
-
else if(name==='repos')result=await api.repos(q.page??1);
|
|
27
|
-
else if(name==='contents')result=await api.contents(q);
|
|
28
|
-
else if(name==='releases')result=await api.releaseList(q);
|
|
29
|
-
else if(name==='upload'){
|
|
30
|
-
const raw=req.headers['x-file-name'];if(typeof raw!=='string')throw Error('缺少附件名称。');const fileName=decodeURIComponent(raw);const
|
|
31
|
-
const limit=new Transform({transform(chunk,encoding,done){size+=chunk.length;if(size>=2*1024**3)done(Error('附件必须小于 2 GiB。'));else done(null,chunk);}});
|
|
32
|
-
try{await pipeline(req,limit,createWriteStream(disk,{flags:'wx',mode:0o600}));result=await ops.addAsset(fileName,disk,id
|
|
33
|
-
}else{const a=await body(req);
|
|
34
|
-
if(name==='ai/program'){if(!releaseCopy)throw Error('AI介绍服务未就绪。');result=await releaseCopy.describeProgram(a);}
|
|
35
|
-
else if(name==='ai/copy'){if(!releaseCopy)throw Error('AI文案服务尚未就绪。');result=await releaseCopy.create(a);}
|
|
36
|
-
else if(name==='
|
|
37
|
-
else if(name==='
|
|
38
|
-
else if(name==='
|
|
39
|
-
else if(name==='
|
|
40
|
-
else if(name==='
|
|
41
|
-
else if(name==='
|
|
42
|
-
else if(name==='
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}catch(e){if(!res.destroyed&&!res.writableEnded)json(res,e.status??400,{error:e.message});}
|
|
49
|
-
}}));
|
|
50
|
-
}
|
|
1
|
+
import {randomUUID} from 'node:crypto';
|
|
2
|
+
import {createWriteStream} from 'node:fs';
|
|
3
|
+
import {unlink} from 'node:fs/promises';
|
|
4
|
+
import {pipeline} from 'node:stream/promises';
|
|
5
|
+
import {Transform} from 'node:stream';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
export const API='/dsh-github/api/';
|
|
9
|
+
const ROUTES={state:'GET',repos:'GET',contents:'GET',releases:'GET','auth/start':'POST','auth/configure':'POST','auth/logout':'POST',prepare:'POST',confirm:'POST',reject:'POST',upload:'POST','attachment/remove':'POST','ai/copy':'POST','ai/program':'POST'};
|
|
10
|
+
const json=(res,status,value)=>{res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});res.end(JSON.stringify(value));};
|
|
11
|
+
async function body(req){let size=0;const parts=[];for await(const b of req){size+=b.length;if(size>3*1024*1024)throw Error('请求内容过大。');parts.push(b);}return JSON.parse(Buffer.concat(parts).toString('utf8')||'{}');}
|
|
12
|
+
export function admitted(req,connection){
|
|
13
|
+
if(!connection||typeof connection.admit!=='function'||!connection.browserPeer)return false;
|
|
14
|
+
try{if(connection.admit(req).peer!==connection.browserPeer)return false;}catch{return false;}
|
|
15
|
+
const remote=req.socket?.remoteAddress;if(remote&&!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(remote))return false;
|
|
16
|
+
const origin=req.headers.origin;if(origin&&origin!=='null'){try{if(new URL(origin).host!==req.headers.host)return false;}catch{return false;}}
|
|
17
|
+
if(req.headers['sec-fetch-site']==='cross-site')return false;
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
export function routes({api,ops,auth,root,connection,releaseCopy}){
|
|
21
|
+
return Object.entries(ROUTES).map(([name,method])=>({kind:'exact',path:API+name,handler:async(req,res)=>{
|
|
22
|
+
if(!admitted(req,connection()))return json(res,403,{error:'需要本机已认证的 DeepSeek Harness 页面。'});
|
|
23
|
+
if(req.method!==method)return json(res,405,{error:'请求方法不正确。'});
|
|
24
|
+
try{const url=new URL(req.url,'http://localhost');const q=Object.fromEntries(url.searchParams);let result;
|
|
25
|
+
if(name==='state'){let user=null,error=null,errorKind=null;try{user=await api.me();}catch(e){error=e.message;errorKind=!e.status?'network':e.status===401?'auth':e.status===403||e.status===429?'rate-limit':e.status>=500?'server':'other';}result={user,error,errorKind,clientId:await auth.clientId(),hasCredential:await auth.hasCredential(),login:auth.login,operations:ops.list(),attachments:ops.assetList()};}
|
|
26
|
+
else if(name==='repos')result=await api.repos(q.page??1);
|
|
27
|
+
else if(name==='contents')result=await api.contents(q);
|
|
28
|
+
else if(name==='releases')result=await api.releaseList(q);
|
|
29
|
+
else if(name==='upload'){
|
|
30
|
+
const raw=req.headers['x-file-name'];if(typeof raw!=='string')throw Error('缺少附件名称。');const fileName=decodeURIComponent(raw);const id=randomUUID(),disk=path.join(root,'attachments',id);let size=0;
|
|
31
|
+
const limit=new Transform({transform(chunk,encoding,done){size+=chunk.length;if(size>=2*1024**3)done(Error('附件必须小于 2 GiB。'));else done(null,chunk);}});
|
|
32
|
+
try{await pipeline(req,limit,createWriteStream(disk,{flags:'wx',mode:0o600}));result=await ops.addAsset(fileName,disk,id);}catch(e){await unlink(disk).catch(()=>{});throw e;}
|
|
33
|
+
}else{const a=await body(req);
|
|
34
|
+
if(name==='ai/program'){if(!releaseCopy)throw Error('AI介绍服务未就绪。');result=await releaseCopy.describeProgram(a);}
|
|
35
|
+
else if(name==='ai/copy'){if(!releaseCopy)throw Error('AI文案服务尚未就绪。');result=await releaseCopy.create(a);}
|
|
36
|
+
else if(name==='auth/start')result=await auth.start();
|
|
37
|
+
else if(name==='auth/configure'){await auth.configure(a.clientId);result={ok:true};}
|
|
38
|
+
else if(name==='auth/logout'){await auth.logout();ops.clearPending();result={ok:true};}
|
|
39
|
+
else if(name==='prepare')result=await ops.prepare(a.kind,a.args);
|
|
40
|
+
else if(name==='confirm')result=await ops.confirm(a.id);
|
|
41
|
+
else if(name==='reject')result=ops.reject(a.id);
|
|
42
|
+
else if(name==='attachment/remove'){await ops.removeAsset(a.id);result={ok:true};}
|
|
43
|
+
}
|
|
44
|
+
json(res,200,result);
|
|
45
|
+
}catch(e){if(!res.destroyed&&!res.writableEnded)json(res,e.status??400,{error:e.message});}
|
|
46
|
+
}}));
|
|
47
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -1,23 +1,21 @@
|
|
|
1
|
-
import os from 'node:os';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import {GhAuth} from './gh.mjs';
|
|
4
|
-
import {GitHub,Operations} from './core.mjs';
|
|
5
|
-
import {routes} from './http.mjs';
|
|
6
|
-
import {definitions,localAgent} from './tools.mjs';
|
|
7
|
-
import {createDiagnostics} from './diagnostics.mjs';
|
|
8
|
-
import {ReleaseCopy} from './release-copy.mjs';
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
export
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const
|
|
15
|
-
const diagnostics=
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
});
|
|
23
|
-
}
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {GhAuth} from './gh.mjs';
|
|
4
|
+
import {GitHub,Operations} from './core.mjs';
|
|
5
|
+
import {routes} from './http.mjs';
|
|
6
|
+
import {definitions,localAgent} from './tools.mjs';
|
|
7
|
+
import {createDiagnostics} from './diagnostics.mjs';
|
|
8
|
+
import {ReleaseCopy} from './release-copy.mjs';
|
|
9
|
+
|
|
10
|
+
export const name='github-connect';
|
|
11
|
+
export function apply(ctx){
|
|
12
|
+
ctx.inject(['webServer','tools','connection'],async host=>{
|
|
13
|
+
const root=path.join(process.env.DSH_HOME??path.join(os.homedir(),'.dsh'),'github-connect');
|
|
14
|
+
const diagnostics=createDiagnostics(root);diagnostics('plugin_started');
|
|
15
|
+
const auth=new GhAuth(root,{diagnostics}),api=new GitHub({auth,diagnostics}),ops=new Operations(api,{root});await ops.init();
|
|
16
|
+
const releaseCopy=new ReleaseCopy({api,ctx:host,root,ops});
|
|
17
|
+
for(const route of routes({api,ops,auth,root,releaseCopy,connection:()=>host.get('connection')}))host.effect(()=>host.webServer.register(route));
|
|
18
|
+
for(const definition of definitions(api,ops))host.effect(()=>host.tools.register(definition,{when:({agent})=>localAgent(agent)}));
|
|
19
|
+
host.on('dispose',()=>{diagnostics('plugin_stopped');ops.clearPending();});
|
|
20
|
+
});
|
|
21
|
+
}
|
package/lib/program-inspect.js
CHANGED
|
@@ -1,50 +1,24 @@
|
|
|
1
|
-
import yauzl from 'yauzl';import{readFile,stat}from'node:fs/promises';import path from'node:path';
|
|
2
|
-
|
|
3
|
-
const
|
|
4
|
-
const
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
let size=0;const chunks=[];
|
|
26
|
-
stream.on('data',chunk=>{size+=chunk.length;if(size>MAX_ENTRY||total+size>MAX_TOTAL){stream.destroy();finish(Error('ZIP 条目超出读取上限,请提供精简源码。'));}else chunks.push(chunk);});
|
|
27
|
-
stream.on('error',()=>finish(Error('ZIP 文本读取失败。')));
|
|
28
|
-
stream.on('end',()=>{if(done)return;const text=decode(Buffer.concat(chunks));if(text?.trim()){total+=size;files.push({path:name,text});}zip.readEntry();});
|
|
29
|
-
});
|
|
30
|
-
});zip.readEntry();
|
|
31
|
-
});
|
|
32
|
-
});}
|
|
33
|
-
export async function inspectProgram(ops,assetIds){
|
|
34
|
-
if(!Array.isArray(assetIds)||assetIds.length<1||assetIds.length>10||assetIds.some(x=>typeof x!=='string'))throw Error('请先传入 1~10 个程序或代码文件。');
|
|
35
|
-
const uploadedFiles=[],sources=[];let bytes=0;
|
|
36
|
-
for(const id of new Set(assetIds)){
|
|
37
|
-
const asset=ops.assets.get(id);if(!asset)throw Error('传入文件已不存在,请重新传入。');const info=await stat(asset.diskPath);if(info.size!==asset.size)throw Error('暂存文件已变化,请重新传入。');
|
|
38
|
-
uploadedFiles.push({name:asset.name,size:asset.size});
|
|
39
|
-
if(/\.zip$/i.test(asset.name)){
|
|
40
|
-
if(asset.size>MAX_ZIP)throw Error('用于 AI 读取的 ZIP 不能超过 32 MiB,请提供精简源码或 README。');
|
|
41
|
-
for(const file of (await zipTexts(await readFile(asset.diskPath))).files){const size=Buffer.byteLength(file.text);if(sources.length>=MAX_SOURCES||bytes+size>MAX_TOTAL)break;sources.push({path:asset.name+'/'+file.path,text:file.text});bytes+=size;}
|
|
42
|
-
}else if(readable(asset.name)&&asset.size<=MAX_ENTRY){
|
|
43
|
-
const text=decode(await readFile(asset.diskPath));if(text?.trim()&&sources.length<MAX_SOURCES&&bytes+Buffer.byteLength(text)<=MAX_TOTAL){sources.push({path:safeName(asset.name),text});bytes+=Buffer.byteLength(text);}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
if(!sources.length)throw Error('没有可供 AI 阅读的源码或说明文件。仅凭 exe、msi、apk 等安装包无法可靠判断功能,请补充源码 ZIP、代码文件或 README。');
|
|
47
|
-
// Explicitly bounded model context; archive metadata and binary names are not functional evidence.
|
|
48
|
-
let remaining=28000;const files=sources.map(f=>{const text=f.text.slice(0,Math.min(6000,remaining));remaining-=text.length;return {path:f.path,text};}).filter(f=>f.text);
|
|
49
|
-
return {uploadedFiles,files,readFiles:files.map(f=>f.path),notice:'只读取了列出的文本,没有运行程序;不要根据文件名推断未验证功能。'};
|
|
50
|
-
}
|
|
1
|
+
import yauzl from 'yauzl';import{readFile,stat}from'node:fs/promises';import path from'node:path';
|
|
2
|
+
const textTypes=/\.(md|txt|py|js|ts|jsx|tsx|java|kt|go|rs|c|cpp|h|cs|swift|rb|php|sh|bat|ps1|html|css|json|ya?ml|toml|xml|gradle|properties|ini)$/i;
|
|
3
|
+
const readable=n=>textTypes.test(n)&&!/(^|\/)(node_modules|\.git|vendor|build|dist|\.venv)\//i.test(n)&&!/(^|\/)(\.env[^/]*|id_rsa|credentials[^/]*|package-lock\.json|pnpm-lock\.yaml)$/i.test(n);
|
|
4
|
+
const decode=b=>{if(b.includes(0))return null;try{const s=new TextDecoder('utf-8',{fatal:true}).decode(b);if(/gh[pousr]_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9_-]{20,}|-----BEGIN .*PRIVATE KEY-----/.test(s))return null;return s;}catch{return null;}};
|
|
5
|
+
function zipTexts(buffer){return new Promise((resolve,reject)=>{yauzl.fromBuffer(buffer,{lazyEntries:true,validateEntrySizes:true},(error,zip)=>{
|
|
6
|
+
if(error)return reject(Error('ZIP无法读取或已损坏,请重新打包为ZIP。'));const files=[],names=[];let total=0,count=0,done=false;
|
|
7
|
+
const finish=(error)=>{if(done)return;done=true;zip.close();error?reject(error):resolve({files,names,truncated:count>=2000||files.length>=24});};
|
|
8
|
+
zip.on('error',()=>finish(Error('ZIP解压读取失败。')));zip.on('end',()=>finish());zip.on('entry',e=>{if(++count>2000)return finish();if(names.length<120)names.push(e.fileName);if(files.length>=24||total>=512*1024)return finish();
|
|
9
|
+
if(!readable(e.fileName)||e.uncompressedSize>200*1024||e.uncompressedSize+total>512*1024||(e.generalPurposeBitFlag&1)){zip.readEntry();return;}
|
|
10
|
+
zip.openReadStream(e,(err,stream)=>{if(err)return finish(Error('ZIP文本条目无法读取。'));let size=0;const chunks=[];stream.on('data',chunk=>{size+=chunk.length;if(size>200*1024||total+size>512*1024){stream.destroy();finish(Error('ZIP条目超出读取上限。'));}else chunks.push(chunk);});stream.on('error',()=>finish(Error('ZIP文本读取失败。')));stream.on('end',()=>{if(done)return;total+=size;const text=decode(Buffer.concat(chunks));if(text?.trim()){files.push({path:e.fileName,text});}zip.readEntry();});});
|
|
11
|
+
});zip.readEntry();
|
|
12
|
+
});});}
|
|
13
|
+
export async function inspectProgram(ops,assetIds){
|
|
14
|
+
if(!Array.isArray(assetIds)||assetIds.length<1||assetIds.length>10||assetIds.some(x=>typeof x!=='string'))throw Error('请先传入1~10个程序或代码文件。');
|
|
15
|
+
const sources=[],names=[];let bytes=0;
|
|
16
|
+
for(const id of new Set(assetIds)){const asset=ops.assets.get(id);if(!asset)throw Error('传入文件已不存在,请重新传入。');const info=await stat(asset.diskPath);if(info.size!==asset.size)throw Error('暂存文件已变化,请重新传入。');names.push({name:asset.name,size:asset.size});
|
|
17
|
+
if(/\.zip$/i.test(asset.name)){if(asset.size>32*1024*1024)throw Error('用于AI读取的ZIP不能超过32MiB,请提供精简源码或README。');const data=await zipTexts(await readFile(asset.diskPath));for(const f of data.files){const n=Buffer.byteLength(f.text);if(sources.length>=24||bytes+n>512*1024)break;sources.push({path:asset.name+'/'+f.path,text:f.text});bytes+=n;}}
|
|
18
|
+
else if(readable(path.basename(asset.name))&&asset.size<=200*1024){const text=decode(await readFile(asset.diskPath));if(text?.trim()&&sources.length<24&&bytes+Buffer.byteLength(text)<=512*1024){sources.push({path:asset.name,text});bytes+=Buffer.byteLength(text);}}
|
|
19
|
+
}
|
|
20
|
+
if(!sources.length)throw Error('没有可供AI阅读的源码或说明文件。仅凭exe、msi、apk等安装包无法可靠判断功能,请补充源码ZIP、代码文件或README。');
|
|
21
|
+
// Explicitly bounded model context; archive metadata and binary names are not functional evidence.
|
|
22
|
+
let remaining=28000;const files=sources.map(f=>{const text=f.text.slice(0,Math.min(6000,remaining));remaining-=text.length;return {path:f.path,text};}).filter(f=>f.text);
|
|
23
|
+
return {uploadedFiles:names,files,readFiles:files.map(f=>f.path),notice:'只读取了列出的文本,没有运行程序;不要根据文件名推断未验证功能。'};
|
|
24
|
+
}
|
package/lib/program-inspect.mjs
CHANGED
|
@@ -1,50 +1,24 @@
|
|
|
1
|
-
import yauzl from 'yauzl';import{readFile,stat}from'node:fs/promises';import path from'node:path';
|
|
2
|
-
|
|
3
|
-
const
|
|
4
|
-
const
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
let size=0;const chunks=[];
|
|
26
|
-
stream.on('data',chunk=>{size+=chunk.length;if(size>MAX_ENTRY||total+size>MAX_TOTAL){stream.destroy();finish(Error('ZIP 条目超出读取上限,请提供精简源码。'));}else chunks.push(chunk);});
|
|
27
|
-
stream.on('error',()=>finish(Error('ZIP 文本读取失败。')));
|
|
28
|
-
stream.on('end',()=>{if(done)return;const text=decode(Buffer.concat(chunks));if(text?.trim()){total+=size;files.push({path:name,text});}zip.readEntry();});
|
|
29
|
-
});
|
|
30
|
-
});zip.readEntry();
|
|
31
|
-
});
|
|
32
|
-
});}
|
|
33
|
-
export async function inspectProgram(ops,assetIds){
|
|
34
|
-
if(!Array.isArray(assetIds)||assetIds.length<1||assetIds.length>10||assetIds.some(x=>typeof x!=='string'))throw Error('请先传入 1~10 个程序或代码文件。');
|
|
35
|
-
const uploadedFiles=[],sources=[];let bytes=0;
|
|
36
|
-
for(const id of new Set(assetIds)){
|
|
37
|
-
const asset=ops.assets.get(id);if(!asset)throw Error('传入文件已不存在,请重新传入。');const info=await stat(asset.diskPath);if(info.size!==asset.size)throw Error('暂存文件已变化,请重新传入。');
|
|
38
|
-
uploadedFiles.push({name:asset.name,size:asset.size});
|
|
39
|
-
if(/\.zip$/i.test(asset.name)){
|
|
40
|
-
if(asset.size>MAX_ZIP)throw Error('用于 AI 读取的 ZIP 不能超过 32 MiB,请提供精简源码或 README。');
|
|
41
|
-
for(const file of (await zipTexts(await readFile(asset.diskPath))).files){const size=Buffer.byteLength(file.text);if(sources.length>=MAX_SOURCES||bytes+size>MAX_TOTAL)break;sources.push({path:asset.name+'/'+file.path,text:file.text});bytes+=size;}
|
|
42
|
-
}else if(readable(asset.name)&&asset.size<=MAX_ENTRY){
|
|
43
|
-
const text=decode(await readFile(asset.diskPath));if(text?.trim()&&sources.length<MAX_SOURCES&&bytes+Buffer.byteLength(text)<=MAX_TOTAL){sources.push({path:safeName(asset.name),text});bytes+=Buffer.byteLength(text);}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
if(!sources.length)throw Error('没有可供 AI 阅读的源码或说明文件。仅凭 exe、msi、apk 等安装包无法可靠判断功能,请补充源码 ZIP、代码文件或 README。');
|
|
47
|
-
// Explicitly bounded model context; archive metadata and binary names are not functional evidence.
|
|
48
|
-
let remaining=28000;const files=sources.map(f=>{const text=f.text.slice(0,Math.min(6000,remaining));remaining-=text.length;return {path:f.path,text};}).filter(f=>f.text);
|
|
49
|
-
return {uploadedFiles,files,readFiles:files.map(f=>f.path),notice:'只读取了列出的文本,没有运行程序;不要根据文件名推断未验证功能。'};
|
|
50
|
-
}
|
|
1
|
+
import yauzl from 'yauzl';import{readFile,stat}from'node:fs/promises';import path from'node:path';
|
|
2
|
+
const textTypes=/\.(md|txt|py|js|ts|jsx|tsx|java|kt|go|rs|c|cpp|h|cs|swift|rb|php|sh|bat|ps1|html|css|json|ya?ml|toml|xml|gradle|properties|ini)$/i;
|
|
3
|
+
const readable=n=>textTypes.test(n)&&!/(^|\/)(node_modules|\.git|vendor|build|dist|\.venv)\//i.test(n)&&!/(^|\/)(\.env[^/]*|id_rsa|credentials[^/]*|package-lock\.json|pnpm-lock\.yaml)$/i.test(n);
|
|
4
|
+
const decode=b=>{if(b.includes(0))return null;try{const s=new TextDecoder('utf-8',{fatal:true}).decode(b);if(/gh[pousr]_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9_-]{20,}|-----BEGIN .*PRIVATE KEY-----/.test(s))return null;return s;}catch{return null;}};
|
|
5
|
+
function zipTexts(buffer){return new Promise((resolve,reject)=>{yauzl.fromBuffer(buffer,{lazyEntries:true,validateEntrySizes:true},(error,zip)=>{
|
|
6
|
+
if(error)return reject(Error('ZIP无法读取或已损坏,请重新打包为ZIP。'));const files=[],names=[];let total=0,count=0,done=false;
|
|
7
|
+
const finish=(error)=>{if(done)return;done=true;zip.close();error?reject(error):resolve({files,names,truncated:count>=2000||files.length>=24});};
|
|
8
|
+
zip.on('error',()=>finish(Error('ZIP解压读取失败。')));zip.on('end',()=>finish());zip.on('entry',e=>{if(++count>2000)return finish();if(names.length<120)names.push(e.fileName);if(files.length>=24||total>=512*1024)return finish();
|
|
9
|
+
if(!readable(e.fileName)||e.uncompressedSize>200*1024||e.uncompressedSize+total>512*1024||(e.generalPurposeBitFlag&1)){zip.readEntry();return;}
|
|
10
|
+
zip.openReadStream(e,(err,stream)=>{if(err)return finish(Error('ZIP文本条目无法读取。'));let size=0;const chunks=[];stream.on('data',chunk=>{size+=chunk.length;if(size>200*1024||total+size>512*1024){stream.destroy();finish(Error('ZIP条目超出读取上限。'));}else chunks.push(chunk);});stream.on('error',()=>finish(Error('ZIP文本读取失败。')));stream.on('end',()=>{if(done)return;total+=size;const text=decode(Buffer.concat(chunks));if(text?.trim()){files.push({path:e.fileName,text});}zip.readEntry();});});
|
|
11
|
+
});zip.readEntry();
|
|
12
|
+
});});}
|
|
13
|
+
export async function inspectProgram(ops,assetIds){
|
|
14
|
+
if(!Array.isArray(assetIds)||assetIds.length<1||assetIds.length>10||assetIds.some(x=>typeof x!=='string'))throw Error('请先传入1~10个程序或代码文件。');
|
|
15
|
+
const sources=[],names=[];let bytes=0;
|
|
16
|
+
for(const id of new Set(assetIds)){const asset=ops.assets.get(id);if(!asset)throw Error('传入文件已不存在,请重新传入。');const info=await stat(asset.diskPath);if(info.size!==asset.size)throw Error('暂存文件已变化,请重新传入。');names.push({name:asset.name,size:asset.size});
|
|
17
|
+
if(/\.zip$/i.test(asset.name)){if(asset.size>32*1024*1024)throw Error('用于AI读取的ZIP不能超过32MiB,请提供精简源码或README。');const data=await zipTexts(await readFile(asset.diskPath));for(const f of data.files){const n=Buffer.byteLength(f.text);if(sources.length>=24||bytes+n>512*1024)break;sources.push({path:asset.name+'/'+f.path,text:f.text});bytes+=n;}}
|
|
18
|
+
else if(readable(path.basename(asset.name))&&asset.size<=200*1024){const text=decode(await readFile(asset.diskPath));if(text?.trim()&&sources.length<24&&bytes+Buffer.byteLength(text)<=512*1024){sources.push({path:asset.name,text});bytes+=Buffer.byteLength(text);}}
|
|
19
|
+
}
|
|
20
|
+
if(!sources.length)throw Error('没有可供AI阅读的源码或说明文件。仅凭exe、msi、apk等安装包无法可靠判断功能,请补充源码ZIP、代码文件或README。');
|
|
21
|
+
// Explicitly bounded model context; archive metadata and binary names are not functional evidence.
|
|
22
|
+
let remaining=28000;const files=sources.map(f=>{const text=f.text.slice(0,Math.min(6000,remaining));remaining-=text.length;return {path:f.path,text};}).filter(f=>f.text);
|
|
23
|
+
return {uploadedFiles:names,files,readFiles:files.map(f=>f.path),notice:'只读取了列出的文本,没有运行程序;不要根据文件名推断未验证功能。'};
|
|
24
|
+
}
|