@ai-workbench/connect 0.7.53-rc.2 → 0.7.53-rc.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 +1 -1
- package/client/index.cjs +1 -12
- package/helper/remote-login.cjs +2 -1
- package/lib/api.d.ts +0 -7
- package/lib/components.js +1 -31
- package/lib/enrollment-runtime.js +0 -11
- package/lib/profile-enrollment.d.ts +1 -4
- package/lib/profile-enrollment.js +4 -10
- package/lib/remote-access.js +1 -1
- package/lib/ssh.js +2 -2
- package/package.json +1 -1
- package/lib/account-enrollment.d.ts +0 -17
- package/lib/account-enrollment.js +0 -61
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 远程主机连接插件(L)
|
|
2
2
|
|
|
3
|
-
`@ai-workbench/connect` 0.7.53-rc.
|
|
3
|
+
`@ai-workbench/connect` 0.7.53-rc.3,随总包 `@ai-workbench/workbench-toolbridge` 0.4.4-rc.3 安装(员工不单独安装)。公开接口见 [contracts/connect-api.md](contracts/connect-api.md),员工首次设置见 [docs/CONNECT-SETUP.md](docs/CONNECT-SETUP.md)。
|
|
4
4
|
|
|
5
5
|
## 做什么
|
|
6
6
|
|
package/client/index.cjs
CHANGED
|
@@ -193,7 +193,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
193
193
|
const validSnapshot=value=>{const s=value?.startup;return record(s)&&['checking','blocked','login-required','authorizing','idle','disposed'].includes(s.phase)&&record(s.logins)&&Object.values(s.logins).every(v=>typeof v==='boolean')&&(s.checkingProviders===undefined||Array.isArray(s.checkingProviders))&&(s.providerNeeds===undefined||record(s.providerNeeds));};
|
|
194
194
|
const accept=(value,source='event')=>{if(disposed)return;const next=value?.startup?.revision,id=value?.startup?.instanceId;if(typeof id!=='string'||!id||!Number.isSafeInteger(next)||next<0||!validSnapshot(value)){failure();return;}if(id!==instance){if(instance&&(source==='http'||retired.has(id)))return;if(instance)retired.add(instance);instance=id;revision=-1;}if(next<revision)return;revision=next;publish({...state,value,error:value.actionErrorCode||value.enrollment?.need?.code||(value.actionError?'ACTION_FAILED':''),reconfirming:false});};
|
|
195
195
|
const failure=()=>{if(!disposed)publish({...state,error:'CONNECTION_UNKNOWN',reconfirming:true});};
|
|
196
|
-
return {readNetworkQuality:refresh=>call('/network-quality'+(refresh?'?refresh=1':''),'GET'),quota:(path,body)=>call('/quota/'+path,body===undefined?'GET':'POST',body),getSnapshot:()=>state,subscribe:fn=>{listeners.add(fn);return()=>listeners.delete(fn);},async action(path='/check',body){if(state.reconfirming&&path!=='/check'||state.importing||state.acting)return;const account=/^\/(forget|logout)\//.test(path);if(account)publish({...state,acting:true});const importing=path==='/enrollment/import'
|
|
196
|
+
return {readNetworkQuality:refresh=>call('/network-quality'+(refresh?'?refresh=1':''),'GET'),quota:(path,body)=>call('/quota/'+path,body===undefined?'GET':'POST',body),getSnapshot:()=>state,subscribe:fn=>{listeners.add(fn);return()=>listeners.delete(fn);},async action(path='/check',body){if(state.reconfirming&&path!=='/check'||state.importing||state.acting)return;const account=/^\/(forget|logout)\//.test(path);if(account)publish({...state,acting:true});const importing=path==='/enrollment/import';if(importing)publish({...state,importing:true,error:''});const at=eventVersion;try{const value=await call(path,'POST',body);if(at===eventVersion)accept(value,'http');}catch{if(at===eventVersion)failure();}finally{if(!disposed&&(account||importing))publish({...state,...(account?{acting:false}:{}),...(importing?{importing:false}:{})});}},start(){if(disposed||started)return;started=true;off=subscribe(value=>{eventVersion++;accept(value);},()=>{eventVersion++;failure();});const at=eventVersion;void call('/status','GET').then(value=>{if(at===eventVersion)accept(value,'http');},()=>{if(at===eventVersion)failure();});},dispose(){disposed=true;off?.();listeners.clear();}};
|
|
197
197
|
}
|
|
198
198
|
function useWorkbench(workbench){const snapshot=React.useSyncExternalStore(workbench.subscribe,workbench.getSnapshot);return {state:snapshot.value,error:snapshot.error,reconfirming:snapshot.reconfirming,importing:snapshot.importing,acting:snapshot.acting,action:workbench.action};}
|
|
199
199
|
function isLoginQuestion(state){const s=state?.startup;return s?.phase==='login-required'&&s.requestId&&s.provider&&s.logins?.[s.provider]===false&&!s.checkingProviders?.includes(s.provider)&&!s.providerNeeds?.[s.provider];}
|
|
@@ -217,16 +217,6 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
217
217
|
h('p',{role:'status',style:{margin:0}},t('submitting'))):h('p',{role:'status',style:{margin:0}},t('waitingLogin')),
|
|
218
218
|
h('div',null,h(Button,{type:'button',variant:'ghost',icon:h(UI.IconCloseOutlineRegular,{'aria-hidden':true}),onClick:()=>{setCode('');void action('/cancel-login/'+value.id);}},t('cancelLogin'))));
|
|
219
219
|
}
|
|
220
|
-
function EmployeeAccountLogin({action,disabled,message}){
|
|
221
|
-
const [account,setAccount]=React.useState(''),[password,setPassword]=React.useState('');
|
|
222
|
-
const submit=event=>{event.preventDefault();if(disabled||!account.trim()||!password)return;const credentials={account:account.trim(),password};setPassword('');void action('/enrollment/login',credentials);};
|
|
223
|
-
return h('form',{onSubmit:submit,style:{display:'grid',gap:8,maxWidth:360,paddingTop:8}},
|
|
224
|
-
h('label',{htmlFor:'aw-employee-account'},'账号'),h(Input,{id:'aw-employee-account',type:'text',value:account,autoComplete:'username',spellCheck:false,disabled,onChange:event=>setAccount(event.target.value),placeholder:'emp-员工名'}),
|
|
225
|
-
h('label',{htmlFor:'aw-employee-password'},'密码'),h(Input,{id:'aw-employee-password',type:'password',value:password,autoComplete:'off',disabled,onChange:event=>setPassword(event.target.value)}),
|
|
226
|
-
h('div',null,h(Button,{type:'submit',variant:'toolbar',size:'md',disabled:disabled||!account.trim()||!password},'账号登录')),
|
|
227
|
-
h('p',{style:{...descriptionStyle,margin:0}},'使用管理员提供的账号和密码。需要改密请联系管理员。'),
|
|
228
|
-
message?h('p',{role:'alert',style:{...errorStyle,margin:0}},message):null);
|
|
229
|
-
}
|
|
230
220
|
function ConnectionInterruption({recovery}){const {t}=React.useContext(Translation);
|
|
231
221
|
const [,update]=React.useState(0);React.useEffect(()=>{if(recovery?.phase!=='reconnecting'||!Number.isFinite(recovery.startedAt))return;const timer=setInterval(()=>update(n=>n+1),60000);return()=>clearInterval(timer);},[recovery?.phase,recovery?.startedAt]);
|
|
232
222
|
if(recovery?.phase!=='reconnecting'||!Number.isFinite(recovery.startedAt))return null;return h('p',{role:'status'},t('interruptionPrefix')+Math.max(0,Math.floor((Date.now()-recovery.startedAt)/60000))+t('interruptionSuffix'));
|
|
@@ -354,7 +344,6 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
354
344
|
return h('section',{'aria-label':t('title')},h('p',{role:'status','data-connect-summary':true,style:{...descriptionStyle,margin:'16px 0 0'}},connecting?t('networkChecking'):steps.length?t('remainingTasks',{steps:steps.join(t('stepSeparator'))}):t('ready')),
|
|
355
345
|
reconfirming?h('p',{role:'status'},t('reconfirming')):null,
|
|
356
346
|
h('fieldset',{disabled:!!reconfirming||!!acting,style:{border:0,padding:0,margin:0,minWidth:0}},
|
|
357
|
-
enrollment&&!enrollment.username&&!imported&&!connected&&!state?.connection?.recovery?h(SettingsRow,{title:'员工账号',status:'输入管理员提供的账号和密码'},h(EmployeeAccountLogin,{action,disabled:connecting,message:enrollment?.need?.code==='LOGIN_FAILED'?enrollment.need.message:state?.actionErrorCode==='LOGIN_FAILED'?state.actionError:undefined})):null,
|
|
358
347
|
h(SettingsRow,{title:t('connectionFiles'),error:!!enrollmentError,status:imported&&!connecting?t('imported',{employee:enrollment.username?t('parenthetical',{value:enrollment.username}):''}):enrollmentError?t(enrollmentError==='ENROLLMENT_REQUIRED'?'enrollmentKeyMissing':needKey(enrollmentError)):t(connecting?'networkChecking':'importHelp'),action:forgetPath?h(Button,{type:'button',variant:'toolbar',size:'md',disabled:!!acting||connecting,onClick:()=>setConfirmForget({employee:enrollment.username,path:forgetPath})},t('forgetConnection')):h(Button,{type:'button',variant:'toolbar',size:'md',disabled:connecting||['ENROLLMENT_KEY_REJECTED','ENROLLMENT_REJECTED'].includes(enrollmentError),onClick:()=>void action('/enrollment/import')},t('import'))}),
|
|
359
348
|
h(SettingsRow,{title:t('networkLabel'),error:!!networkError,status:connecting?t('networkChecking'):connected?t('networkConnected'):state?.connection?.recovery?.phase==='reconnecting'?h(ConnectionInterruption,{recovery:state.connection.recovery}):networkError?h(NeedMessage,{need:state.connection.need}):t(!imported?'networkWaiting':'unknown'),action:h(Button,{type:'button',variant:'toolbar',size:'md',disabled:connecting,onClick:()=>void action()},t('recheck'))},h(NetworkSignal,{workbench,context:JSON.stringify([enrollment?.instanceId,enrollment?.revision,enrollment?.phase,state?.network?.phase,reconfirming]),available:!reconfirming&&imported&&state?.network?.phase==='online'})),
|
|
360
349
|
...providers.map(provider=>{
|
package/helper/remote-login.cjs
CHANGED
|
@@ -5,7 +5,8 @@ const [provider,graceText,...extra]=process.argv.slice(1);const grace=Number(gra
|
|
|
5
5
|
let seat,seatEnv;try{seat=require('/usr/local/aw-host/lib/agent-seats.cjs').getSeat(provider);seatEnv=require('/usr/local/aw-host/lib/agent-seats.cjs').seatEnvironment(provider);}catch{process.exit(2);}
|
|
6
6
|
if(!seat||!Number.isSafeInteger(grace)||grace<0||grace>2147483647||extra.length)process.exit(2);
|
|
7
7
|
let child,stopping=false,killTimer,codeSent=false,finished=false;
|
|
8
|
-
|
|
8
|
+
// Official CLI 2.1.330 shortens sign-in links by default; retain the full URL for PKCE/state validation.
|
|
9
|
+
const env={...seatEnv,BROWSER:'true',...(seat.provider==='claude'?{CLAUDE_CODE_FULL_SIGN_IN_LINK:'1'}:{})};
|
|
9
10
|
const input=createInterface({input:process.stdin});
|
|
10
11
|
function signalGroup(signal){if(child?.pid)try{process.kill(-child.pid,signal);}catch(e){if(e.code!=='ESRCH')process.exitCode=1;}}
|
|
11
12
|
function stop(){if(stopping||finished)return;stopping=true;signalGroup('SIGTERM');if(grace===0)signalGroup('SIGKILL');else killTimer=setTimeout(()=>signalGroup('SIGKILL'),grace);}
|
package/lib/api.d.ts
CHANGED
|
@@ -114,13 +114,6 @@ export interface ConnectApi {
|
|
|
114
114
|
getContractInfo(): ContractInfo;
|
|
115
115
|
getEnrollmentState(): EnrollmentState;
|
|
116
116
|
onEnrollmentState(listener: (state: EnrollmentState) => void): () => void;
|
|
117
|
-
loginEmployee?(credentials: {
|
|
118
|
-
account: string;
|
|
119
|
-
password: string;
|
|
120
|
-
}): Promise<Result<{
|
|
121
|
-
outcome: 'imported' | 'cancelled';
|
|
122
|
-
state: EnrollmentState;
|
|
123
|
-
}>>;
|
|
124
117
|
importEnrollment(): Promise<Result<{
|
|
125
118
|
outcome: 'imported' | 'cancelled';
|
|
126
119
|
state: EnrollmentState;
|
package/lib/components.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { ACCOUNT_LOGIN_MESSAGES } from "./account-enrollment.js";
|
|
2
1
|
import { connectionEmployeeMessage } from "./connection-messages.js";
|
|
3
2
|
import { L_DEFAULTS } from "./defaults.js";
|
|
4
3
|
import { fail } from "./needs.js";
|
|
@@ -184,35 +183,6 @@ export function registerComponents(ctx, inventory, metadataMaxBytes = L_DEFAULTS
|
|
|
184
183
|
else
|
|
185
184
|
result = operation === 'forget' ? await service.forgetEnrollment() : await service.logout(provider);
|
|
186
185
|
}
|
|
187
|
-
else if (path === '/ai-workbench-connect/enrollment/login') {
|
|
188
|
-
let credentials;
|
|
189
|
-
try {
|
|
190
|
-
const chunks = [];
|
|
191
|
-
let bytes = 0;
|
|
192
|
-
for await (const chunk of req) {
|
|
193
|
-
const part = Buffer.from(chunk);
|
|
194
|
-
bytes += part.length;
|
|
195
|
-
if (bytes > metadataMaxBytes)
|
|
196
|
-
throw Error();
|
|
197
|
-
chunks.push(part);
|
|
198
|
-
}
|
|
199
|
-
const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
200
|
-
if (!record(body) || Object.keys(body).sort().join(',') !== 'account,password' || typeof body.account !== 'string' || typeof body.password !== 'string')
|
|
201
|
-
throw Error();
|
|
202
|
-
credentials = { account: body.account, password: body.password };
|
|
203
|
-
}
|
|
204
|
-
catch {
|
|
205
|
-
res.statusCode = 400;
|
|
206
|
-
res.end(JSON.stringify({ ...getState(), actionErrorCode: 'LOGIN_FAILED', actionError: '请输入完整的员工账号和密码' }));
|
|
207
|
-
return;
|
|
208
|
-
}
|
|
209
|
-
try {
|
|
210
|
-
result = await service.loginEmployee?.(credentials) ?? fail('DEPENDENCY_REQUIRED');
|
|
211
|
-
}
|
|
212
|
-
finally {
|
|
213
|
-
credentials.password = '';
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
186
|
else if (path === '/ai-workbench-connect/enrollment/import') {
|
|
217
187
|
if (Number(req.headers?.['content-length'] ?? 0) > 0 || req.headers?.['transfer-encoding']) {
|
|
218
188
|
res.statusCode = 400;
|
|
@@ -256,7 +226,7 @@ export function registerComponents(ctx, inventory, metadataMaxBytes = L_DEFAULTS
|
|
|
256
226
|
if (!result.ok) {
|
|
257
227
|
res.statusCode = 409;
|
|
258
228
|
actionErrorCode = result.error.code;
|
|
259
|
-
actionError =
|
|
229
|
+
actionError = account ? result.error.message : ['LOGIN_PROMPT_INVALID', 'LOGOUT_FAILED', 'ENROLLMENT_CLEANUP_FAILED', 'ACTIVATION_CONFLICT'].includes(result.error.code) ? result.error.message : employeeMessage(result.error.code, service.getConnectionState());
|
|
260
230
|
}
|
|
261
231
|
}
|
|
262
232
|
else if (req.method !== 'GET' || path !== '/ai-workbench-connect/status') {
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { downloadEnrollment } from "./account-enrollment.js";
|
|
2
1
|
import { mapNetworkNeed } from "./provider.js";
|
|
3
2
|
import { createProfileEnrollment } from "./profile-enrollment.js";
|
|
4
3
|
import { createProfileActivation } from "./profile-activation.js";
|
|
@@ -22,16 +21,6 @@ function attachScoped(ctx, api, ports, config, network, autoStart = false) {
|
|
|
22
21
|
ports.enrollment = { read: () => manager.read(), pause: () => manager.pause(), forget: signal => manager.forget(signal) };
|
|
23
22
|
api.getEnrollmentState = manager.getState;
|
|
24
23
|
api.onEnrollmentState = manager.onState;
|
|
25
|
-
api.loginEmployee = async (credentials) => { if (api.getConnectionState().phase === 'disposed')
|
|
26
|
-
return fail('DISPOSED'); try {
|
|
27
|
-
const result = await manager.importEnrollment(signal => downloadEnrollment(credentials, { profileDir: profile.dir, metadataMaxBytes, signal }));
|
|
28
|
-
if (result.ok && result.value.outcome === 'imported')
|
|
29
|
-
await api.refreshLoginPrompts();
|
|
30
|
-
return result;
|
|
31
|
-
}
|
|
32
|
-
finally {
|
|
33
|
-
credentials.password = '';
|
|
34
|
-
} };
|
|
35
24
|
api.importEnrollment = async () => { if (api.getConnectionState().phase === 'disposed')
|
|
36
25
|
return fail('DISPOSED'); const result = await manager.importEnrollment(); if (result.ok && result.value.outcome === 'imported')
|
|
37
26
|
await api.refreshLoginPrompts(); return result; };
|
|
@@ -25,10 +25,7 @@ export declare function createProfileEnrollment(options: ProfileEnrollmentOption
|
|
|
25
25
|
getState: () => EnrollmentState;
|
|
26
26
|
onState(fn: (s: EnrollmentState) => void): () => void;
|
|
27
27
|
read(): Promise<Result<Enrollment>>;
|
|
28
|
-
importEnrollment(
|
|
29
|
-
source: string;
|
|
30
|
-
cleanup: () => Promise<void>;
|
|
31
|
-
}>): Promise<Result<{
|
|
28
|
+
importEnrollment(): Promise<Result<{
|
|
32
29
|
outcome: "imported" | "cancelled";
|
|
33
30
|
state: EnrollmentState;
|
|
34
31
|
}>>;
|
|
@@ -415,7 +415,7 @@ export function createProfileEnrollment(options) {
|
|
|
415
415
|
void promise.then(() => pending.delete(promise), () => pending.delete(promise));
|
|
416
416
|
return promise;
|
|
417
417
|
},
|
|
418
|
-
importEnrollment(
|
|
418
|
+
importEnrollment() {
|
|
419
419
|
if (disposed || paused || record?.retiring)
|
|
420
420
|
return Promise.resolve(fail(disposed ? 'DISPOSED' : 'ACTIVATION_CONFLICT'));
|
|
421
421
|
if (flight)
|
|
@@ -426,10 +426,8 @@ export function createProfileEnrollment(options) {
|
|
|
426
426
|
return fail(disposed ? 'DISPOSED' : 'ACTIVATION_CONFLICT');
|
|
427
427
|
if (!ready.ok)
|
|
428
428
|
return ready;
|
|
429
|
-
if (download && record)
|
|
430
|
-
return { ok: false, error: { ...need('ACTIVATION_CONFLICT'), message: '请先退出当前员工连接,再登录员工账号。' } };
|
|
431
429
|
const blocked = options.blockedByNetwork?.();
|
|
432
|
-
if (
|
|
430
|
+
if (blocked) {
|
|
433
431
|
publish('blocked', blocked.code);
|
|
434
432
|
return fail(blocked.code);
|
|
435
433
|
}
|
|
@@ -437,9 +435,8 @@ export function createProfileEnrollment(options) {
|
|
|
437
435
|
return fail('ENROLLMENT_INVALID');
|
|
438
436
|
const previous = record ? 'imported' : 'empty';
|
|
439
437
|
publish('importing');
|
|
440
|
-
let downloaded;
|
|
441
438
|
try {
|
|
442
|
-
const source =
|
|
439
|
+
const source = await options.pick(abort.signal);
|
|
443
440
|
if (disposed || paused)
|
|
444
441
|
return fail(disposed ? 'DISPOSED' : 'ACTIVATION_CONFLICT');
|
|
445
442
|
if (source === null) {
|
|
@@ -447,7 +444,7 @@ export function createProfileEnrollment(options) {
|
|
|
447
444
|
return ok({ outcome: 'cancelled', state: snapshot() });
|
|
448
445
|
}
|
|
449
446
|
const blocked = options.blockedByNetwork?.();
|
|
450
|
-
if (
|
|
447
|
+
if (blocked) {
|
|
451
448
|
publish('blocked', blocked.code);
|
|
452
449
|
return fail(blocked.code);
|
|
453
450
|
}
|
|
@@ -484,9 +481,6 @@ export function createProfileEnrollment(options) {
|
|
|
484
481
|
publish('blocked', reason);
|
|
485
482
|
return { ok: false, error: reason };
|
|
486
483
|
}
|
|
487
|
-
finally {
|
|
488
|
-
await downloaded?.cleanup();
|
|
489
|
-
}
|
|
490
484
|
};
|
|
491
485
|
const promise = run();
|
|
492
486
|
flight = promise;
|
package/lib/remote-access.js
CHANGED
|
@@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises';
|
|
|
2
2
|
import { execFile } from 'node:child_process';
|
|
3
3
|
import { stat } from 'node:fs/promises';
|
|
4
4
|
import { shellQuote } from "./ssh.js";
|
|
5
|
-
// TH2 约定 B/C:连上主机后把本机用户名与 N
|
|
5
|
+
// TH2 约定 B/C:连上主机后把本机用户名与 N 节点名写到主机 ~/.aw/emp.json,并读主机 emp 公钥;
|
|
6
6
|
// 本机“远程登录”未按该钥匙开通时,用 macOS 管理员授权框执行一次固定脚本(helper/remote-access.sh)。
|
|
7
7
|
const KEY = /^ssh-ed25519 [A-Za-z0-9+/]+=*( [ -~]*)?$/;
|
|
8
8
|
const USER = /^[A-Za-z0-9._][A-Za-z0-9._-]*$/;
|
package/lib/ssh.js
CHANGED
|
@@ -115,10 +115,10 @@ export function createSsh(runner, maxOutputBytes) {
|
|
|
115
115
|
return authFailure('ssh-status', 'STATUS_EXECUTION_FAILED', {}, error);
|
|
116
116
|
}
|
|
117
117
|
},
|
|
118
|
-
// 约定 C:每次连接把员工电脑 {user,node}
|
|
118
|
+
// 约定 C:每次连接把员工电脑 {user,node} 原子写到主机 ~/.aw/emp.json,并取回主机 emp 公钥(约定 B 判定用)。
|
|
119
119
|
employeeAccess: async (t, employee, signal) => {
|
|
120
120
|
try {
|
|
121
|
-
const r = await runRemote(runner, t, '
|
|
121
|
+
const r = await runRemote(runner, t, 'umask 077 && mkdir -p "$HOME/.aw" && cat > "$HOME/.aw/emp.json.$$" && mv -f "$HOME/.aw/emp.json.$$" "$HOME/.aw/emp.json" && cat "$HOME/.ssh/aw_emp.pub"', signal, employee);
|
|
122
122
|
return r.exitCode === 0 ? ok(r.stdout) : fail('SSH_FAILED');
|
|
123
123
|
}
|
|
124
124
|
catch (error) {
|
package/package.json
CHANGED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
export declare const ACCOUNT_ENROLLMENT_URL = "https://mini-awhost.tail9816d2.ts.net/enrollment/login";
|
|
2
|
-
export declare const ACCOUNT_LOGIN_MESSAGES: Set<string>;
|
|
3
|
-
interface Credentials {
|
|
4
|
-
account: string;
|
|
5
|
-
password: string;
|
|
6
|
-
}
|
|
7
|
-
interface Options {
|
|
8
|
-
profileDir: string;
|
|
9
|
-
metadataMaxBytes: number;
|
|
10
|
-
signal: AbortSignal;
|
|
11
|
-
fetch?: typeof globalThis.fetch;
|
|
12
|
-
}
|
|
13
|
-
export declare function downloadEnrollment(credentials: Credentials, options: Options): Promise<{
|
|
14
|
-
source: string;
|
|
15
|
-
cleanup: () => Promise<void>;
|
|
16
|
-
}>;
|
|
17
|
-
export {};
|
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import { mkdtemp, writeFile, rm, realpath } from 'node:fs/promises';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import { privateDirectory } from "./private-files.js";
|
|
4
|
-
import { NeedError, need } from "./needs.js";
|
|
5
|
-
// 产品默认开通地址随总包发布,不是员工设置。
|
|
6
|
-
export const ACCOUNT_ENROLLMENT_URL = 'https://mini-awhost.tail9816d2.ts.net/enrollment/login';
|
|
7
|
-
const invalid = '账号或密码不正确,需要改密请联系管理员';
|
|
8
|
-
export const ACCOUNT_LOGIN_MESSAGES = new Set([invalid, '同一账号连续输错 5 次,请 15 分钟后再试,需要改密请联系管理员', '这个网络登录太频繁,请一分钟后再试', '账号登录暂时不可用,请稍后再试或联系管理员']);
|
|
9
|
-
const failure = (message = '账号登录暂时不可用,请稍后再试或联系管理员') => new NeedError({ ...need('LOGIN_FAILED'), message });
|
|
10
|
-
export async function downloadEnrollment(credentials, options) {
|
|
11
|
-
let source;
|
|
12
|
-
try {
|
|
13
|
-
if (!/^emp-[a-z0-9][a-z0-9-]{0,27}$/.test(credentials.account) || credentials.account.length > 32 || typeof credentials.password !== 'string' || !credentials.password)
|
|
14
|
-
throw failure(invalid);
|
|
15
|
-
if (options.signal.aborted || await realpath(options.profileDir) !== options.profileDir)
|
|
16
|
-
throw failure();
|
|
17
|
-
const response = await (options.fetch ?? globalThis.fetch)(ACCOUNT_ENROLLMENT_URL, { method: 'POST', redirect: 'error', cache: 'no-store', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(credentials), signal: options.signal });
|
|
18
|
-
const reader = response.body?.getReader();
|
|
19
|
-
if (!reader)
|
|
20
|
-
throw failure();
|
|
21
|
-
const parts = [];
|
|
22
|
-
let size = 0;
|
|
23
|
-
try {
|
|
24
|
-
while (true) {
|
|
25
|
-
const { done, value } = await reader.read();
|
|
26
|
-
if (done)
|
|
27
|
-
break;
|
|
28
|
-
size += value.byteLength;
|
|
29
|
-
if (size > options.metadataMaxBytes)
|
|
30
|
-
throw failure();
|
|
31
|
-
parts.push(value);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
finally {
|
|
35
|
-
await reader.cancel();
|
|
36
|
-
}
|
|
37
|
-
const body = JSON.parse(Buffer.concat(parts).toString('utf8'));
|
|
38
|
-
if (response.status !== 200)
|
|
39
|
-
throw failure([401, 429, 503].includes(response.status) && ACCOUNT_LOGIN_MESSAGES.has(body?.message) ? body.message : undefined);
|
|
40
|
-
if (!body || Object.keys(body).sort().join(',') !== 'authKey,enrollment,sshRule' || body.enrollment?.employee?.username !== credentials.account || body.enrollment?.authKeyDelivery?.path !== 'authkey' || typeof body.authKey !== 'string' || !body.authKey || /[\r\n]/.test(body.authKey))
|
|
41
|
-
throw failure();
|
|
42
|
-
const root = join(options.profileDir, 'ai-workbench-connect');
|
|
43
|
-
await privateDirectory(root);
|
|
44
|
-
if (await realpath(root) !== root)
|
|
45
|
-
throw failure();
|
|
46
|
-
source = await mkdtemp(join(root, '.account-login-'));
|
|
47
|
-
await writeFile(join(source, 'enroll.json'), JSON.stringify(body.enrollment) + '\n', { mode: 0o600, flag: 'wx' });
|
|
48
|
-
await writeFile(join(source, 'ssh-rule.json'), JSON.stringify(body.sshRule) + '\n', { mode: 0o600, flag: 'wx' });
|
|
49
|
-
await writeFile(join(source, 'authkey'), body.authKey + '\n', { mode: 0o600, flag: 'wx' });
|
|
50
|
-
body.authKey = '';
|
|
51
|
-
const target = source;
|
|
52
|
-
return { source: target, cleanup: () => rm(target, { recursive: true, force: true }) };
|
|
53
|
-
}
|
|
54
|
-
catch (error) {
|
|
55
|
-
if (source)
|
|
56
|
-
await rm(source, { recursive: true, force: true });
|
|
57
|
-
if (error instanceof NeedError)
|
|
58
|
-
throw error;
|
|
59
|
-
throw failure();
|
|
60
|
-
}
|
|
61
|
-
}
|