@ai-workbench/connect 0.7.53-rc.3 → 0.7.53-rc.4
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 +12 -1
- package/lib/account-enrollment.d.ts +17 -0
- package/lib/account-enrollment.js +61 -0
- package/lib/api.d.ts +7 -0
- package/lib/components.js +31 -1
- package/lib/enrollment-runtime.js +11 -0
- package/lib/profile-enrollment.d.ts +4 -1
- package/lib/profile-enrollment.js +10 -4
- package/lib/remote-access.js +1 -1
- package/lib/ssh.js +2 -2
- package/package.json +1 -1
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.4,随总包 `@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';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();}};
|
|
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'||path==='/enrollment/login';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,6 +217,16 @@ 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
|
+
}
|
|
220
230
|
function ConnectionInterruption({recovery}){const {t}=React.useContext(Translation);
|
|
221
231
|
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]);
|
|
222
232
|
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'));
|
|
@@ -344,6 +354,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
344
354
|
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')),
|
|
345
355
|
reconfirming?h('p',{role:'status'},t('reconfirming')):null,
|
|
346
356
|
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,
|
|
347
358
|
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'))}),
|
|
348
359
|
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'})),
|
|
349
360
|
...providers.map(provider=>{
|
|
@@ -0,0 +1,17 @@
|
|
|
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 {};
|
|
@@ -0,0 +1,61 @@
|
|
|
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
|
+
}
|
package/lib/api.d.ts
CHANGED
|
@@ -114,6 +114,13 @@ 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
|
+
}>>;
|
|
117
124
|
importEnrollment(): Promise<Result<{
|
|
118
125
|
outcome: 'imported' | 'cancelled';
|
|
119
126
|
state: EnrollmentState;
|
package/lib/components.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ACCOUNT_LOGIN_MESSAGES } from "./account-enrollment.js";
|
|
1
2
|
import { connectionEmployeeMessage } from "./connection-messages.js";
|
|
2
3
|
import { L_DEFAULTS } from "./defaults.js";
|
|
3
4
|
import { fail } from "./needs.js";
|
|
@@ -183,6 +184,35 @@ export function registerComponents(ctx, inventory, metadataMaxBytes = L_DEFAULTS
|
|
|
183
184
|
else
|
|
184
185
|
result = operation === 'forget' ? await service.forgetEnrollment() : await service.logout(provider);
|
|
185
186
|
}
|
|
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
|
+
}
|
|
186
216
|
else if (path === '/ai-workbench-connect/enrollment/import') {
|
|
187
217
|
if (Number(req.headers?.['content-length'] ?? 0) > 0 || req.headers?.['transfer-encoding']) {
|
|
188
218
|
res.statusCode = 400;
|
|
@@ -226,7 +256,7 @@ export function registerComponents(ctx, inventory, metadataMaxBytes = L_DEFAULTS
|
|
|
226
256
|
if (!result.ok) {
|
|
227
257
|
res.statusCode = 409;
|
|
228
258
|
actionErrorCode = result.error.code;
|
|
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());
|
|
259
|
+
actionError = path === '/ai-workbench-connect/enrollment/login' ? (ACCOUNT_LOGIN_MESSAGES.has(result.error.message) || result.error.code === 'ACTIVATION_CONFLICT' ? result.error.message : '账号登录暂时不可用,请稍后再试或联系管理员') : 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());
|
|
230
260
|
}
|
|
231
261
|
}
|
|
232
262
|
else if (req.method !== 'GET' || path !== '/ai-workbench-connect/status') {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { downloadEnrollment } from "./account-enrollment.js";
|
|
1
2
|
import { mapNetworkNeed } from "./provider.js";
|
|
2
3
|
import { createProfileEnrollment } from "./profile-enrollment.js";
|
|
3
4
|
import { createProfileActivation } from "./profile-activation.js";
|
|
@@ -21,6 +22,16 @@ function attachScoped(ctx, api, ports, config, network, autoStart = false) {
|
|
|
21
22
|
ports.enrollment = { read: () => manager.read(), pause: () => manager.pause(), forget: signal => manager.forget(signal) };
|
|
22
23
|
api.getEnrollmentState = manager.getState;
|
|
23
24
|
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
|
+
} };
|
|
24
35
|
api.importEnrollment = async () => { if (api.getConnectionState().phase === 'disposed')
|
|
25
36
|
return fail('DISPOSED'); const result = await manager.importEnrollment(); if (result.ok && result.value.outcome === 'imported')
|
|
26
37
|
await api.refreshLoginPrompts(); return result; };
|
|
@@ -25,7 +25,10 @@ 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(
|
|
28
|
+
importEnrollment(download?: (signal: AbortSignal) => Promise<{
|
|
29
|
+
source: string;
|
|
30
|
+
cleanup: () => Promise<void>;
|
|
31
|
+
}>): Promise<Result<{
|
|
29
32
|
outcome: "imported" | "cancelled";
|
|
30
33
|
state: EnrollmentState;
|
|
31
34
|
}>>;
|
|
@@ -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(download) {
|
|
419
419
|
if (disposed || paused || record?.retiring)
|
|
420
420
|
return Promise.resolve(fail(disposed ? 'DISPOSED' : 'ACTIVATION_CONFLICT'));
|
|
421
421
|
if (flight)
|
|
@@ -426,8 +426,10 @@ 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: '请先退出当前员工连接,再登录员工账号。' } };
|
|
429
431
|
const blocked = options.blockedByNetwork?.();
|
|
430
|
-
if (blocked) {
|
|
432
|
+
if (!download && blocked) {
|
|
431
433
|
publish('blocked', blocked.code);
|
|
432
434
|
return fail(blocked.code);
|
|
433
435
|
}
|
|
@@ -435,8 +437,9 @@ export function createProfileEnrollment(options) {
|
|
|
435
437
|
return fail('ENROLLMENT_INVALID');
|
|
436
438
|
const previous = record ? 'imported' : 'empty';
|
|
437
439
|
publish('importing');
|
|
440
|
+
let downloaded;
|
|
438
441
|
try {
|
|
439
|
-
const source = await options.pick(abort.signal);
|
|
442
|
+
const source = download ? (downloaded = await download(abort.signal)).source : await options.pick(abort.signal);
|
|
440
443
|
if (disposed || paused)
|
|
441
444
|
return fail(disposed ? 'DISPOSED' : 'ACTIVATION_CONFLICT');
|
|
442
445
|
if (source === null) {
|
|
@@ -444,7 +447,7 @@ export function createProfileEnrollment(options) {
|
|
|
444
447
|
return ok({ outcome: 'cancelled', state: snapshot() });
|
|
445
448
|
}
|
|
446
449
|
const blocked = options.blockedByNetwork?.();
|
|
447
|
-
if (blocked) {
|
|
450
|
+
if (!download && blocked) {
|
|
448
451
|
publish('blocked', blocked.code);
|
|
449
452
|
return fail(blocked.code);
|
|
450
453
|
}
|
|
@@ -481,6 +484,9 @@ export function createProfileEnrollment(options) {
|
|
|
481
484
|
publish('blocked', reason);
|
|
482
485
|
return { ok: false, error: reason };
|
|
483
486
|
}
|
|
487
|
+
finally {
|
|
488
|
+
await downloaded?.cleanup();
|
|
489
|
+
}
|
|
484
490
|
};
|
|
485
491
|
const promise = run();
|
|
486
492
|
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 节点名经主机 helper 按来源设备登记,并读主机 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} 经主机 helper 按 SSH 来源登记到该设备目录,并取回主机 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, 'node /usr/local/aw-host/lib/employee-devices.mjs register', signal, employee);
|
|
122
122
|
return r.exitCode === 0 ? ok(r.stdout) : fail('SSH_FAILED');
|
|
123
123
|
}
|
|
124
124
|
catch (error) {
|