@ai-workbench/connect 0.7.32 → 0.7.36
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 +29 -9
- package/client/index.cjs +470 -83
- package/helper/host-directories.cjs +43 -1
- package/lib/api.d.ts +5 -0
- package/lib/browser-login.d.ts +1 -0
- package/lib/browser-login.js +28 -9
- package/lib/components.js +2 -2
- package/lib/connect.js +1 -0
- package/lib/directory-session.d.ts +7 -0
- package/lib/directory-session.js +153 -0
- package/lib/enrollment.d.ts +1 -0
- package/lib/enrollment.js +4 -1
- package/lib/host-directories.d.ts +5 -1
- package/lib/host-directories.js +11 -5
- package/lib/index.js +1 -1
- package/lib/integration.d.ts +1 -1
- package/lib/integration.js +2 -2
- package/lib/needs.js +1 -1
- package/lib/ports.d.ts +1 -0
- package/lib/profile-activation.js +1 -3
- package/lib/profile-enrollment.js +11 -10
- package/lib/profile-runtime.js +6 -0
- package/lib/startup.js +4 -2
- package/package.json +1 -1
|
@@ -70,5 +70,47 @@ async function main(){
|
|
|
70
70
|
let result;try{result=await execute(JSON.parse(input));}catch{result=error('PROJECT_PROTOCOL_INVALID');}
|
|
71
71
|
process.stdout.write(JSON.stringify(result)+'\n');
|
|
72
72
|
}
|
|
73
|
-
|
|
73
|
+
// One remote Node process per browsing connection. Speculation is one level only,
|
|
74
|
+
// shares the existing output budget, and never authorizes execution or selection.
|
|
75
|
+
async function serve(maxBytes){
|
|
76
|
+
const {StringDecoder}=require('node:string_decoder');const decoder=new StringDecoder('utf8');
|
|
77
|
+
let buffer='',cache=new Map(),prefetchGeneration=0;
|
|
78
|
+
const cacheKey=r=>JSON.stringify([r?.operation,r?.path??null,r?.after??null,r?.pageSize,r?.maxOutputBytes]);
|
|
79
|
+
async function respond(frame){
|
|
80
|
+
if(!frame||Object.keys(frame).sort().join(',')!=='id,request'||typeof frame.id!=='string')throw new Error('PROJECT_PROTOCOL_INVALID');
|
|
81
|
+
const request=frame.request,key=cacheKey(request),saved=cache.get(key);
|
|
82
|
+
let result=saved?await saved:await execute(request);
|
|
83
|
+
// Re-observe a prefetched directory at click time: changed links, permissions,
|
|
84
|
+
// or entries must not return an old canonical path or a stale listing.
|
|
85
|
+
if(saved&&!result.ok)result=await execute(request);
|
|
86
|
+
else if(saved&&result.ok){
|
|
87
|
+
let current;try{current=await observe(request.path);}catch(exception){result=error(classify(exception),exception);}
|
|
88
|
+
if(current){
|
|
89
|
+
let changed=JSON.stringify(current)!==JSON.stringify((({entries,nextAfter,...info})=>info)(result.value));
|
|
90
|
+
if(!changed)try{for(const entry of result.value.entries){if(JSON.stringify(await directoryEntry(entry.requestedPath,entry.name))!==JSON.stringify(entry)){changed=true;break;}}}catch{changed=true;}
|
|
91
|
+
if(changed)result=await execute(request);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const mine=++prefetchGeneration;cache=new Map();
|
|
95
|
+
const line=JSON.stringify({id:frame.id,result})+'\n';
|
|
96
|
+
process.stdout.write(Buffer.byteLength(line)>maxBytes?JSON.stringify({id:frame.id,result:error('HOST_DIRECTORY_PAGE_TOO_LARGE')})+'\n':line);
|
|
97
|
+
if(request?.operation!=='browse'||!result.ok)return;
|
|
98
|
+
const nextCache=cache;let bytes=0;
|
|
99
|
+
// No recursion: execute() never calls serve() or starts another prefetch.
|
|
100
|
+
void (async()=>{for(const entry of result.value.entries){
|
|
101
|
+
if(mine!==prefetchGeneration)break;
|
|
102
|
+
if(entry.errorCode||entry.permissions.read!==true||entry.permissions.execute!==true)continue;
|
|
103
|
+
const child={...request,path:entry.requestedPath};delete child.after;
|
|
104
|
+
const key=cacheKey(child),pending=execute(child);nextCache.set(key,pending);
|
|
105
|
+
const value=await pending;bytes+=Buffer.byteLength(JSON.stringify(value));
|
|
106
|
+
if(bytes>maxBytes){nextCache.delete(key);break;}
|
|
107
|
+
}})().catch(()=>{prefetchGeneration++;cache.clear();process.exitCode=1;process.stdin.destroy();});
|
|
108
|
+
}
|
|
109
|
+
for await(const chunk of process.stdin){
|
|
110
|
+
buffer+=decoder.write(chunk);if(Buffer.byteLength(buffer)>maxBytes)throw new Error('HOST_DIRECTORY_PAGE_TOO_LARGE');
|
|
111
|
+
let end;while((end=buffer.indexOf('\n'))!==-1){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);await respond(JSON.parse(line));}
|
|
112
|
+
}
|
|
113
|
+
prefetchGeneration++;cache.clear();if(buffer||decoder.end())throw new Error('PROJECT_PROTOCOL_INVALID');
|
|
114
|
+
}
|
|
115
|
+
module.exports={execute,serve};
|
|
74
116
|
if(require.main===module)void main();
|
package/lib/api.d.ts
CHANGED
|
@@ -45,7 +45,9 @@ export type BrowserLoginState = null | {
|
|
|
45
45
|
id: string;
|
|
46
46
|
provider: Provider;
|
|
47
47
|
phase: 'waiting' | 'submitting';
|
|
48
|
+
url: string;
|
|
48
49
|
deviceCode?: string;
|
|
50
|
+
openError?: boolean;
|
|
49
51
|
};
|
|
50
52
|
export interface LoginState {
|
|
51
53
|
provider: Provider;
|
|
@@ -118,9 +120,11 @@ export interface HostSessionProjectTarget {
|
|
|
118
120
|
target: SshTarget;
|
|
119
121
|
}
|
|
120
122
|
export interface EnrollmentState {
|
|
123
|
+
workspaceSources?: ('host' | 'local')[];
|
|
121
124
|
instanceId: string;
|
|
122
125
|
revision: number;
|
|
123
126
|
phase: 'empty' | 'importing' | 'imported' | 'blocked';
|
|
127
|
+
username?: string;
|
|
124
128
|
need?: ConnectNeed;
|
|
125
129
|
}
|
|
126
130
|
export type DetailJson = null | boolean | number | string | DetailJson[] | {
|
|
@@ -157,6 +161,7 @@ export interface ConnectApi {
|
|
|
157
161
|
onBrowserLoginState?(listener: () => void): () => void;
|
|
158
162
|
submitLoginCode?(id: string, code: string): Promise<Result<void>>;
|
|
159
163
|
cancelBrowserLogin?(id: string): Result<void>;
|
|
164
|
+
openBrowserLoginPage?(id: string): Promise<Result<void>>;
|
|
160
165
|
getWorkspaceDirectoryPickerSettings?(): import('./workspace-directory-picker-types.ts').WorkspacePickerSettings;
|
|
161
166
|
browseWorkspaceDirectories?(request: import('./workspace-directory-picker-types.ts').WorkspacePickerRequest): Promise<Result<import('./workspace-directory-picker-types.ts').WorkspacePickerPage>>;
|
|
162
167
|
createWorkspaceDirectory?(request: {
|
package/lib/browser-login.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export declare function createBrowserLogin(open?: (url: string, signal: AbortSig
|
|
|
5
5
|
getState: () => BrowserLoginState;
|
|
6
6
|
onState(fn: () => void): () => void;
|
|
7
7
|
open(boot: LoginBoot, onCode: (code: string) => Promise<void>, signal: AbortSignal): Promise<LoginInteraction>;
|
|
8
|
+
openPage(id: string): Promise<Result<void>>;
|
|
8
9
|
submit(id: string, code: string): Promise<Result<void>>;
|
|
9
10
|
cancel(id: string): Result<void>;
|
|
10
11
|
};
|
package/lib/browser-login.js
CHANGED
|
@@ -34,20 +34,39 @@ export function createBrowserLogin(open = openDefaultBrowser) {
|
|
|
34
34
|
const ended = new Promise(resolve => closed = resolve), id = randomUUID();
|
|
35
35
|
const close = () => { if (active?.state.id !== id)
|
|
36
36
|
return; active = undefined; opening.abort(); signal.removeEventListener('abort', close); closed(); emit(); };
|
|
37
|
-
|
|
37
|
+
let openRevision = 0;
|
|
38
|
+
const current = { state: { id, provider: boot.provider, phase: 'waiting', url: boot.url, ...(boot.provider === 'codex' ? { deviceCode: boot.deviceCode } : {}) }, submit: onCode, close, openPage: async () => {
|
|
39
|
+
const revision = ++openRevision;
|
|
40
|
+
try {
|
|
41
|
+
await open(boot.url, AbortSignal.any([signal, opening.signal]));
|
|
42
|
+
if (active !== current)
|
|
43
|
+
return fail('LOGIN_PROMPT_INVALID');
|
|
44
|
+
if (revision === openRevision) {
|
|
45
|
+
delete current.state.openError;
|
|
46
|
+
emit();
|
|
47
|
+
}
|
|
48
|
+
return ok(undefined);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
if (active === current && revision === openRevision) {
|
|
52
|
+
current.state.openError = true;
|
|
53
|
+
emit();
|
|
54
|
+
}
|
|
55
|
+
return fail('LOGIN_FAILED');
|
|
56
|
+
}
|
|
57
|
+
} };
|
|
58
|
+
active = current;
|
|
38
59
|
signal.addEventListener('abort', close, { once: true });
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
if (signal.aborted || active?.state.id !== id)
|
|
42
|
-
throw Error('LOGIN_CANCELLED');
|
|
43
|
-
emit();
|
|
44
|
-
return { closed: ended, close: async () => close() };
|
|
45
|
-
}
|
|
46
|
-
catch {
|
|
60
|
+
emit();
|
|
61
|
+
if (signal.aborted || active !== current) {
|
|
47
62
|
close();
|
|
48
63
|
throw Error('BROWSER_OPEN_FAILED');
|
|
49
64
|
}
|
|
65
|
+
// Publish the public link before handing it to the OS. A slow/failed opener must not hide it.
|
|
66
|
+
void current.openPage();
|
|
67
|
+
return { closed: ended, close: async () => close() };
|
|
50
68
|
},
|
|
69
|
+
async openPage(id) { const current = active; return !current || current.state.id !== id ? fail('LOGIN_PROMPT_INVALID') : current.openPage(); },
|
|
51
70
|
async submit(id, code) {
|
|
52
71
|
const current = active;
|
|
53
72
|
if (!current || current.state.id !== id || current.state.provider !== 'claude' || current.state.phase !== 'waiting')
|
package/lib/components.js
CHANGED
|
@@ -206,7 +206,7 @@ export function registerComponents(ctx, inventory, metadataMaxBytes = L_DEFAULTS
|
|
|
206
206
|
res.end(JSON.stringify(result));
|
|
207
207
|
return;
|
|
208
208
|
}
|
|
209
|
-
if (req.method === 'POST' && /^\/ai-workbench-connect\/(login-code|cancel-login)\/[a-zA-Z0-9-]+$/.test(path)) {
|
|
209
|
+
if (req.method === 'POST' && /^\/ai-workbench-connect\/(login-code|cancel-login|open-login)\/[a-zA-Z0-9-]+$/.test(path)) {
|
|
210
210
|
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
211
211
|
const id = path.split('/').at(-1);
|
|
212
212
|
let code;
|
|
@@ -236,7 +236,7 @@ export function registerComponents(ctx, inventory, metadataMaxBytes = L_DEFAULTS
|
|
|
236
236
|
res.end(JSON.stringify(fail('LOGIN_PROMPT_INVALID')));
|
|
237
237
|
return;
|
|
238
238
|
}
|
|
239
|
-
const result = typeof code === 'string' ? await service?.submitLoginCode?.(id, code) : service?.cancelBrowserLogin?.(id);
|
|
239
|
+
const result = typeof code === 'string' ? await service?.submitLoginCode?.(id, code) : path.includes('/open-login/') ? await service?.openBrowserLoginPage?.(id) : service?.cancelBrowserLogin?.(id);
|
|
240
240
|
res.statusCode = result?.ok ? 200 : 409;
|
|
241
241
|
res.end(JSON.stringify({ ...getState(), ...(!result?.ok ? { actionErrorCode: result?.error.code ?? 'LOGIN_PROMPT_INVALID', actionError: result && !result.ok ? result.error.message : '本次登录已结束,请重新发起。' } : {}) }));
|
|
242
242
|
return;
|
package/lib/connect.js
CHANGED
|
@@ -267,6 +267,7 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
267
267
|
getBrowserLoginState: () => ports.login?.interaction?.getState() ?? null,
|
|
268
268
|
onBrowserLoginState: fn => ports.login?.interaction?.onState(fn) ?? (() => { }),
|
|
269
269
|
submitLoginCode: async (id, code) => disposed ? fail('DISPOSED') : ports.login?.interaction?.submit(id, code) ?? fail('LOGIN_PROMPT_INVALID'),
|
|
270
|
+
openBrowserLoginPage: async (id) => disposed ? fail('DISPOSED') : ports.login?.interaction?.openPage(id) ?? fail('LOGIN_PROMPT_INVALID'),
|
|
270
271
|
cancelBrowserLogin: id => ports.login?.interaction?.cancel(id) ?? fail('LOGIN_PROMPT_INVALID'),
|
|
271
272
|
getModelCatalogTarget: provider => {
|
|
272
273
|
if (disposed)
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SshTarget } from './api.ts';
|
|
2
|
+
export declare const DIRECTORY_CONTROL_PERSIST_SECONDS = 60;
|
|
3
|
+
export declare function createDirectorySession(profileDir: string, maxBytes: number): {
|
|
4
|
+
request(target: SshTarget, request: unknown, signal: AbortSignal): Promise<string>;
|
|
5
|
+
reset(): Promise<void>;
|
|
6
|
+
dispose(): Promise<void>;
|
|
7
|
+
};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { readFile, mkdtemp, realpath, rm, lstat } from 'node:fs/promises';
|
|
3
|
+
import { join, relative } from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
6
|
+
import { sshArgs } from "./ssh.js";
|
|
7
|
+
import { privateDirectory } from "./private-files.js";
|
|
8
|
+
import { AuthDiagnosticError } from "./auth-diagnostics.js";
|
|
9
|
+
// B-class fixed transport policy, documented in README; not a business deadline.
|
|
10
|
+
export const DIRECTORY_CONTROL_PERSIST_SECONDS = 60;
|
|
11
|
+
export function createDirectorySession(profileDir, maxBytes) {
|
|
12
|
+
let current;
|
|
13
|
+
let tail = Promise.resolve(), generation = 0, disposed = false;
|
|
14
|
+
const failure = (reason) => new AuthDiagnosticError({ stage: 'directory-stream', reason });
|
|
15
|
+
async function close() {
|
|
16
|
+
const old = current;
|
|
17
|
+
if (!old)
|
|
18
|
+
return;
|
|
19
|
+
old.failure ??= failure('CONNECTION_LOST');
|
|
20
|
+
old.pending?.reject(old.failure);
|
|
21
|
+
old.pending = undefined;
|
|
22
|
+
if (old.child.exitCode === null && old.child.signalCode === null)
|
|
23
|
+
old.child.kill('SIGTERM');
|
|
24
|
+
// Only this instance's private master, never another profile's connection.
|
|
25
|
+
const exitCode = await new Promise((resolve, reject) => { const child = spawn('ssh', ['-O', 'exit', ...old.args], { cwd: profileDir, stdio: 'ignore', shell: false, env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined } }); child.once('error', () => reject(failure('MASTER_CLEANUP_FAILED'))); child.once('close', code => resolve(code)); });
|
|
26
|
+
if (exitCode !== 0)
|
|
27
|
+
try {
|
|
28
|
+
await lstat(join(old.directory, 'c'));
|
|
29
|
+
throw failure('MASTER_CLEANUP_FAILED');
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (error.code !== 'ENOENT')
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
await old.closed;
|
|
36
|
+
try {
|
|
37
|
+
await lstat(join(old.directory, 'c'));
|
|
38
|
+
throw failure('MASTER_CLEANUP_FAILED');
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (error.code !== 'ENOENT')
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
await rm(old.directory, { recursive: true, force: true });
|
|
45
|
+
if (current === old)
|
|
46
|
+
current = undefined;
|
|
47
|
+
}
|
|
48
|
+
async function open(target) {
|
|
49
|
+
const key = JSON.stringify(target);
|
|
50
|
+
if (current?.target === key && !current.failure)
|
|
51
|
+
return current;
|
|
52
|
+
await close();
|
|
53
|
+
if (await realpath(profileDir) !== profileDir)
|
|
54
|
+
throw failure('PRIVATE_DIRECTORY_REQUIRED');
|
|
55
|
+
const root = join(profileDir, 'ai-workbench-connect');
|
|
56
|
+
await privateDirectory(root);
|
|
57
|
+
if (await realpath(root) !== root)
|
|
58
|
+
throw failure('PRIVATE_DIRECTORY_REQUIRED');
|
|
59
|
+
const sockets = join(root, 'ssh');
|
|
60
|
+
await privateDirectory(sockets);
|
|
61
|
+
const directory = await mkdtemp(join(sockets, 'm-'));
|
|
62
|
+
// A relative Unix socket path avoids macOS sun_path limits for long profile paths.
|
|
63
|
+
const control = './' + relative(profileDir, join(directory, 'c'));
|
|
64
|
+
const args = ['-o', 'ControlMaster=auto', '-o', 'ControlPath=' + JSON.stringify(control.replaceAll('%', '%%')), '-o', 'ControlPersist=' + DIRECTORY_CONTROL_PERSIST_SECONDS, ...sshArgs(target)];
|
|
65
|
+
try {
|
|
66
|
+
const source = await readFile(new URL('../helper/host-directories.cjs', import.meta.url), 'utf8');
|
|
67
|
+
const command = 'node -e ' + "'" + (source + '\nserve(' + maxBytes + ');').replaceAll("'", "'\\''") + "'";
|
|
68
|
+
const child = spawn('ssh', [...args, command], { cwd: profileDir, shell: false, stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined } });
|
|
69
|
+
let done = () => { };
|
|
70
|
+
const closed = new Promise(resolve => done = resolve);
|
|
71
|
+
const session = { target: key, child, closed, directory, args };
|
|
72
|
+
current = session;
|
|
73
|
+
const stop = (reason) => { session.failure ??= failure(reason); session.pending?.reject(session.failure); session.pending = undefined; if (child.exitCode === null && child.signalCode === null)
|
|
74
|
+
child.kill('SIGTERM'); };
|
|
75
|
+
const decoder = new StringDecoder('utf8');
|
|
76
|
+
let buffer = '';
|
|
77
|
+
child.stdout.on('data', (chunk) => {
|
|
78
|
+
buffer += decoder.write(chunk);
|
|
79
|
+
if (Buffer.byteLength(buffer) > maxBytes) {
|
|
80
|
+
stop('OUTPUT_LIMIT_EXCEEDED');
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
let end;
|
|
84
|
+
while ((end = buffer.indexOf('\n')) !== -1) {
|
|
85
|
+
const line = buffer.slice(0, end);
|
|
86
|
+
buffer = buffer.slice(end + 1);
|
|
87
|
+
try {
|
|
88
|
+
const frame = JSON.parse(line);
|
|
89
|
+
if (!session.pending || !frame || Object.keys(frame).sort().join(',') !== 'id,result' || frame.id !== session.pending.id)
|
|
90
|
+
throw Error();
|
|
91
|
+
const pending = session.pending;
|
|
92
|
+
session.pending = undefined;
|
|
93
|
+
pending.resolve(JSON.stringify(frame.result));
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
stop('PROJECT_PROTOCOL_INVALID');
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
child.stderr.on('data', () => stop('SSH_STDERR_NONEMPTY'));
|
|
102
|
+
child.stdin.on('error', () => stop('STDIN_FAILED'));
|
|
103
|
+
child.once('error', () => stop('SPAWN_FAILED'));
|
|
104
|
+
child.once('close', () => { stop('CONNECTION_LOST'); done(); });
|
|
105
|
+
return session;
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
await rm(directory, { recursive: true, force: true });
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
request(target, request, signal) {
|
|
114
|
+
const mine = generation;
|
|
115
|
+
const task = tail.then(async () => {
|
|
116
|
+
if (disposed || signal.aborted || mine !== generation)
|
|
117
|
+
throw failure('CANCELLED');
|
|
118
|
+
const session = await open(target);
|
|
119
|
+
if (disposed || signal.aborted || mine !== generation) {
|
|
120
|
+
await close();
|
|
121
|
+
throw failure('CANCELLED');
|
|
122
|
+
}
|
|
123
|
+
if (session.failure)
|
|
124
|
+
throw session.failure;
|
|
125
|
+
const id = randomUUID(), line = JSON.stringify({ id, request }) + '\n';
|
|
126
|
+
if (Buffer.byteLength(line) > maxBytes)
|
|
127
|
+
throw failure('OUTPUT_LIMIT_EXCEEDED');
|
|
128
|
+
const abort = () => { session.failure ??= failure('CANCELLED'); session.pending?.reject(session.failure); session.pending = undefined; session.child.kill('SIGTERM'); };
|
|
129
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
130
|
+
try {
|
|
131
|
+
return await new Promise((resolve, reject) => { session.pending = { id, resolve, reject }; if (signal.aborted)
|
|
132
|
+
abort();
|
|
133
|
+
else
|
|
134
|
+
session.child.stdin.write(line); });
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
signal.removeEventListener('abort', abort);
|
|
138
|
+
if (session.failure)
|
|
139
|
+
await close();
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
tail = task.catch(() => { });
|
|
143
|
+
return task;
|
|
144
|
+
},
|
|
145
|
+
reset() { generation++; const task = tail.then(close); tail = task.catch(() => { }); if (current) {
|
|
146
|
+
current.failure ??= failure('CONNECTION_LOST');
|
|
147
|
+
current.pending?.reject(current.failure);
|
|
148
|
+
current.pending = undefined;
|
|
149
|
+
current.child.kill('SIGTERM');
|
|
150
|
+
} return task; },
|
|
151
|
+
dispose() { disposed = true; return this.reset(); },
|
|
152
|
+
};
|
|
153
|
+
}
|
package/lib/enrollment.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import type { Result } from './api.ts';
|
|
2
2
|
import type { Enrollment } from './ports.ts';
|
|
3
|
+
export declare function validWorkspaceSources(value: unknown): value is ('host' | 'local')[];
|
|
3
4
|
export declare function readEnrollment(packageDir: string, trustDir: string, maxMetadataBytes?: number): Promise<Result<Enrollment>>;
|
package/lib/enrollment.js
CHANGED
|
@@ -3,6 +3,7 @@ import { join, isAbsolute } from 'node:path';
|
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { fail, ok } from "./needs.js";
|
|
5
5
|
import { privateDirectory, privateFile, readPrivate } from "./private-files.js";
|
|
6
|
+
export function validWorkspaceSources(value) { return Array.isArray(value) && value.length > 0 && value.length <= 2 && value.every(source => source === 'host' || source === 'local') && new Set(value).size === value.length; }
|
|
6
7
|
export async function readEnrollment(packageDir, trustDir, maxMetadataBytes) {
|
|
7
8
|
try {
|
|
8
9
|
if (!isAbsolute(packageDir) || !isAbsolute(trustDir))
|
|
@@ -11,6 +12,8 @@ export async function readEnrollment(packageDir, trustDir, maxMetadataBytes) {
|
|
|
11
12
|
if (!dir.isDirectory() || dir.isSymbolicLink() || dir.uid !== process.getuid() || (dir.mode & 0o077) !== 0)
|
|
12
13
|
return fail('ENROLLMENT_INVALID');
|
|
13
14
|
const wire = JSON.parse(await readPrivate(join(packageDir, 'enroll.json'), maxMetadataBytes));
|
|
15
|
+
if (wire.workspaceSources !== undefined && !validWorkspaceSources(wire.workspaceSources))
|
|
16
|
+
return fail('ENROLLMENT_INVALID');
|
|
14
17
|
if (wire.schemaVersion !== 1 || !/^emp-[a-z0-9][a-z0-9-]*$/.test(wire.employee?.username) || wire.employee.username.length > 32)
|
|
15
18
|
return fail('ENROLLMENT_INVALID');
|
|
16
19
|
const user = wire.employee.username, home = '/Users/' + user;
|
|
@@ -63,7 +66,7 @@ export async function readEnrollment(packageDir, trustDir, maxMetadataBytes) {
|
|
|
63
66
|
await rm(temp, { force: true });
|
|
64
67
|
}
|
|
65
68
|
}
|
|
66
|
-
return ok({ authKeyFile, host: wire.host.name, username: user, port: wire.host.sshPort, projectRoot: wire.employee.projectsRoot, knownHostsFile: destination, session: { command: wire.session.command, root: wire.session.root, settingsPath: wire.session.settingsPath, protocolVersion: 1 } });
|
|
69
|
+
return ok({ ...wire.workspaceSources === undefined ? {} : { workspaceSources: [...wire.workspaceSources] }, authKeyFile, host: wire.host.name, username: user, port: wire.host.sshPort, projectRoot: wire.employee.projectsRoot, knownHostsFile: destination, session: { command: wire.session.command, root: wire.session.root, settingsPath: wire.session.settingsPath, protocolVersion: 1 } });
|
|
67
70
|
}
|
|
68
71
|
catch {
|
|
69
72
|
return fail('ENROLLMENT_INVALID');
|
|
@@ -47,8 +47,12 @@ export interface HostDirectoryRequest {
|
|
|
47
47
|
pageSize: number;
|
|
48
48
|
}
|
|
49
49
|
export interface HostDirectories {
|
|
50
|
+
reset?(): Promise<void>;
|
|
51
|
+
dispose?(): Promise<void>;
|
|
50
52
|
browse(target: SshTarget, data: HostDirectoryRequest, signal: AbortSignal): Promise<Result<HostDirectoryData>>;
|
|
51
53
|
inspect(target: SshTarget, path: string, signal: AbortSignal): Promise<Result<Pick<HostDirectoryInfo, 'path'>>>;
|
|
52
54
|
create?(target: SshTarget, path: string, name: string, signal: AbortSignal): Promise<Result<HostDirectoryInfo>>;
|
|
53
55
|
}
|
|
54
|
-
export declare function createHostDirectories(runner: Runner, maxOutputBytes: number
|
|
56
|
+
export declare function createHostDirectories(runner: Runner, maxOutputBytes: number, options?: {
|
|
57
|
+
profileDir: string;
|
|
58
|
+
}): HostDirectories;
|
package/lib/host-directories.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createDirectorySession } from "./directory-session.js";
|
|
1
2
|
import { readFile } from 'node:fs/promises';
|
|
2
3
|
import { runRemote } from "./ssh.js";
|
|
3
4
|
import { fail, ok } from "./needs.js";
|
|
@@ -21,16 +22,21 @@ function validEntry(value, parent) {
|
|
|
21
22
|
return validPath(value.path) && validIdentity(value.identity);
|
|
22
23
|
}
|
|
23
24
|
const binaryCompare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
|
24
|
-
export function createHostDirectories(runner, maxOutputBytes) {
|
|
25
|
+
export function createHostDirectories(runner, maxOutputBytes, options) {
|
|
26
|
+
const session = options ? createDirectorySession(options.profileDir, maxOutputBytes) : undefined;
|
|
25
27
|
async function request(target, operation, data, signal) {
|
|
26
28
|
if (signal.aborted)
|
|
27
29
|
return fail('CONNECTION_LOST');
|
|
28
30
|
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || data.path !== undefined && !validPath(data.path) || operation === 'create' && (!validPath(data.path) || !validName(data.name)) || operation === 'inspect' && data.path === undefined || operation === 'browse' && (!Number.isSafeInteger(data.pageSize) || data.pageSize < 1 || data.after !== undefined && (!validName(data.after))))
|
|
29
31
|
return fail('HOST_DIRECTORY_INVALID');
|
|
30
32
|
try {
|
|
31
|
-
const
|
|
33
|
+
const payload = { protocolVersion: 1, operation, ...data, maxOutputBytes };
|
|
34
|
+
// Inspect/create always perform a fresh check/mutation through the original path.
|
|
35
|
+
if (operation === 'create')
|
|
36
|
+
await session?.reset();
|
|
37
|
+
const source = operation === 'browse' && session ? '' : await readFile(new URL('../helper/host-directories.cjs', import.meta.url), 'utf8');
|
|
32
38
|
const command = 'node -e ' + "'" + (source + '\nmain();').replaceAll("'", "'\\''") + "'";
|
|
33
|
-
const raw = await runRemote(runner, target, command, signal, JSON.stringify(
|
|
39
|
+
const raw = operation === 'browse' && session ? { exitCode: 0, stderr: '', stdout: await session.request(target, payload, signal) } : await runRemote(runner, target, command, signal, JSON.stringify(payload));
|
|
34
40
|
if (signal.aborted)
|
|
35
41
|
return fail('CONNECTION_LOST');
|
|
36
42
|
if (raw.exitCode !== 0 || raw.stderr !== '')
|
|
@@ -68,11 +74,11 @@ export function createHostDirectories(runner, maxOutputBytes) {
|
|
|
68
74
|
if (error instanceof AuthDiagnosticError) {
|
|
69
75
|
if (error.diagnostic.reason === 'OUTPUT_LIMIT_EXCEEDED')
|
|
70
76
|
return fail('HOST_DIRECTORY_PAGE_TOO_LARGE');
|
|
71
|
-
if (error.diagnostic.stage === 'remote-frame')
|
|
77
|
+
if (error.diagnostic.stage === 'remote-frame' || error.diagnostic.reason === 'PROJECT_PROTOCOL_INVALID')
|
|
72
78
|
return fail('PROJECT_PROTOCOL_INVALID');
|
|
73
79
|
}
|
|
74
80
|
return authFailure('host-directory', 'DIRECTORY_CHECK_EXCEPTION', {}, error, 'CONNECTION_LOST');
|
|
75
81
|
}
|
|
76
82
|
}
|
|
77
|
-
return { create: (target, path, name, signal) => request(target, 'create', { path, name }, signal), browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
|
|
83
|
+
return { ...(session ? { reset: () => session.reset(), dispose: () => session.dispose() } : {}), create: (target, path, name, signal) => request(target, 'create', { path, name }, signal), browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
|
|
78
84
|
}
|
package/lib/index.js
CHANGED
|
@@ -41,7 +41,7 @@ export function register(ctx, ports, _inventory, extend, autoStart = true) {
|
|
|
41
41
|
export function apply(ctx, config = {}) {
|
|
42
42
|
config = profileSettings(config, ctx.get('profileContext')?.dir);
|
|
43
43
|
const network = ctx.get('aiWorkbenchNetwork');
|
|
44
|
-
const ports = configuredPorts(config, network);
|
|
44
|
+
const ports = configuredPorts(config, network, ctx.get('profileContext')?.dir);
|
|
45
45
|
register(ctx, ports, config.inventory, api => attachProfileRuntime(ctx, api, ports, config, network, true), false);
|
|
46
46
|
registerComponents(ctx, config.inventory, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
|
|
47
47
|
}
|
package/lib/integration.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { RuntimeConfig } from './profile-settings.ts';
|
|
2
2
|
import type { Ports } from './ports.ts';
|
|
3
3
|
import { type NetworkProvider } from './provider.ts';
|
|
4
|
-
export declare function configuredPorts(config: RuntimeConfig, provider?: NetworkProvider): Ports;
|
|
4
|
+
export declare function configuredPorts(config: RuntimeConfig, provider?: NetworkProvider, profileDir?: string): Ports;
|
package/lib/integration.js
CHANGED
|
@@ -9,7 +9,7 @@ import { runLogin } from "./login.js";
|
|
|
9
9
|
import { parseLoginStatus } from "./auth-status.js";
|
|
10
10
|
import { authFailure } from "./auth-diagnostics.js";
|
|
11
11
|
import { fail, ok } from "./needs.js";
|
|
12
|
-
export function configuredPorts(config, provider) {
|
|
12
|
+
export function configuredPorts(config, provider, profileDir) {
|
|
13
13
|
const ports = {};
|
|
14
14
|
const network = provider ? adaptNetwork(provider) : undefined;
|
|
15
15
|
if (config.enrollmentPackageDir && config.trustDir)
|
|
@@ -19,7 +19,7 @@ export function configuredPorts(config, provider) {
|
|
|
19
19
|
if (config.commandOutputMaxBytes !== undefined) {
|
|
20
20
|
const runner = createRunner(config.commandOutputMaxBytes);
|
|
21
21
|
ports.ssh = createSsh(runner, config.commandOutputMaxBytes);
|
|
22
|
-
ports.hostDirectories = createHostDirectories(runner, config.commandOutputMaxBytes);
|
|
22
|
+
ports.hostDirectories = createHostDirectories(runner, config.commandOutputMaxBytes, profileDir ? { profileDir } : undefined);
|
|
23
23
|
}
|
|
24
24
|
else if (provider)
|
|
25
25
|
ports.ssh = { verify: async () => fail('SETTINGS_REQUIRED'), status: async () => fail('SETTINGS_REQUIRED') };
|
package/lib/needs.js
CHANGED
|
@@ -30,7 +30,7 @@ const entries = {
|
|
|
30
30
|
HELPER_SHUTDOWN_FORCED: { layer: 'network', message: '网络组件未能正常退出,请联系管理员核实状态。', requires: '核实网络组件退出状态', actor: 'administrator', action: { id: 'inspect-network-enrollment', label: '联系管理员', available: false } },
|
|
31
31
|
ENROLLMENT_KEY_REJECTED: { layer: 'enrollment', message: '开通链接已失效,请向管理员领取新的。', requires: '新的开通链接', actor: 'administrator', action: { id: 'renew-enrollment', label: '联系管理员', available: false } },
|
|
32
32
|
ENROLLMENT_REJECTED: { layer: 'enrollment', message: '已存设备身份已失效,请联系管理员处理。', requires: '管理员处理已失效的设备身份', actor: 'administrator', action: { id: 'check-enrollment-result', label: '联系管理员', available: false } },
|
|
33
|
-
ENROLLMENT_REQUIRED: { layer: 'enrollment', message: '
|
|
33
|
+
ENROLLMENT_REQUIRED: { layer: 'enrollment', message: '这份连接资料缺少开通凭据,请导入含有效开通凭据的连接资料。', requires: '含有效开通凭据的连接资料', actor: 'employee', action: { id: 'import-enrollment', label: '导入连接资料', available: true } },
|
|
34
34
|
ENROLLMENT_INVALID: { layer: 'enrollment', message: '开通文件无效,我需要管理员重新发放。', requires: '有效开通文件', actor: 'administrator', action: { id: 'request-enrollment', label: '重新开通', available: false } },
|
|
35
35
|
NETWORK_KEY_INVALID: { layer: 'network', message: '员工开通已失效,请联系管理员重新发放开通链接。', requires: '新的开通链接', actor: 'administrator', action: { id: 'request-enrollment', label: '联系管理员', available: false } },
|
|
36
36
|
HOST_OFFLINE: { layer: 'network', message: '暂时无法连接主机,最后在线时间未提供时为未知;可先检查本机网络。', requires: '在线的公司主机', actor: 'administrator', action: { id: 'contact-administrator', label: '联系管理员', available: false } },
|
package/lib/ports.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Provider, Result, SshTarget, SessionTarget } from './api.ts';
|
|
2
2
|
import type { createHostDirectories } from './host-directories.ts';
|
|
3
3
|
export interface Enrollment {
|
|
4
|
+
workspaceSources?: ('host' | 'local')[];
|
|
4
5
|
authKeyFile?: string;
|
|
5
6
|
host: string;
|
|
6
7
|
username: string;
|
|
@@ -86,9 +86,7 @@ export function createProfileActivation(options) {
|
|
|
86
86
|
throw error;
|
|
87
87
|
if (stored)
|
|
88
88
|
return fail('LOCAL_STATE_INVALID');
|
|
89
|
-
|
|
90
|
-
return fail('ENROLLMENT_REQUIRED');
|
|
91
|
-
await save(settings.configFile, { ...expected, authKeyFile: e.authKeyFile });
|
|
89
|
+
await save(settings.configFile, { ...expected, ...e.authKeyFile === undefined ? {} : { authKeyFile: e.authKeyFile } });
|
|
92
90
|
}
|
|
93
91
|
if (!stored)
|
|
94
92
|
await save(recordFile, registration);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { lstat, realpath, open, rename, rm } from 'node:fs/promises';
|
|
2
2
|
import { join, isAbsolute, resolve } from 'node:path';
|
|
3
3
|
import { randomUUID, createHash } from 'node:crypto';
|
|
4
|
-
import { readEnrollment } from "./enrollment.js";
|
|
4
|
+
import { readEnrollment, validWorkspaceSources } from "./enrollment.js";
|
|
5
5
|
import { privateDirectory, privateFile, readPrivate } from "./private-files.js";
|
|
6
6
|
import { ok, fail, need, NeedError } from "./needs.js";
|
|
7
7
|
// Only metadata about authkey is examined here. Its contents belong exclusively to N.
|
|
@@ -14,7 +14,7 @@ export function createProfileEnrollment(options) {
|
|
|
14
14
|
const dataDir = join(options.profileDir, 'ai-workbench-connect'), file = join(dataDir, 'enrollment.json'), trustDir = join(dataDir, 'trust');
|
|
15
15
|
const snapshot = () => structuredClone(state);
|
|
16
16
|
const publish = (phase, reason) => { if (disposed)
|
|
17
|
-
return; state = { instanceId, revision: state.revision + 1, phase, ...(reason ? { need: typeof reason === 'string' ? need(reason) : structuredClone(reason) } : {}) }; options.onState?.(snapshot()); for (const fn of listeners)
|
|
17
|
+
return; state = { instanceId, revision: state.revision + 1, phase, ...(phase === 'imported' && record ? { username: record.username } : {}), ...(record?.workspaceSources ? { workspaceSources: [...record.workspaceSources] } : {}), ...(reason ? { need: typeof reason === 'string' ? need(reason) : structuredClone(reason) } : {}) }; options.onState?.(snapshot()); for (const fn of listeners)
|
|
18
18
|
fn(snapshot()); };
|
|
19
19
|
const validOptions = () => isAbsolute(options.profileDir) && Number.isSafeInteger(options.metadataMaxBytes) && options.metadataMaxBytes > 0 && options.metadataMaxBytes <= 2147483647;
|
|
20
20
|
const canonical = async (path) => { if (!isAbsolute(path) || await realpath(path) !== resolve(path))
|
|
@@ -49,7 +49,7 @@ export function createProfileEnrollment(options) {
|
|
|
49
49
|
await canonical(dataDir);
|
|
50
50
|
try {
|
|
51
51
|
const value = JSON.parse(await readPrivate(file, options.metadataMaxBytes));
|
|
52
|
-
if (value.schemaVersion !== 1 || typeof value.requestId !== 'string' || !value.requestId || typeof value.source !== 'string' || !/^[a-f0-9]{64}$/.test(value.digest) || !['host', 'username', 'projectRoot'].every(k => typeof value[k] === 'string') || !Number.isInteger(value.port))
|
|
52
|
+
if (value.workspaceSources !== undefined && !validWorkspaceSources(value.workspaceSources) || value.schemaVersion !== 1 || typeof value.requestId !== 'string' || !value.requestId || typeof value.source !== 'string' || !/^[a-f0-9]{64}$/.test(value.digest) || !['host', 'username', 'projectRoot'].every(k => typeof value[k] === 'string') || !Number.isInteger(value.port))
|
|
53
53
|
throw Error('REGISTRATION_INVALID');
|
|
54
54
|
record = value;
|
|
55
55
|
}
|
|
@@ -91,11 +91,11 @@ export function createProfileEnrollment(options) {
|
|
|
91
91
|
const key = join(source, keyName);
|
|
92
92
|
try {
|
|
93
93
|
if ((await sourceFile(key)).size === 0)
|
|
94
|
-
return fail('
|
|
94
|
+
return fail('ENROLLMENT_INVALID');
|
|
95
95
|
}
|
|
96
96
|
catch (error) {
|
|
97
|
-
if (error.code !== 'ENOENT'
|
|
98
|
-
return fail(
|
|
97
|
+
if (error.code !== 'ENOENT')
|
|
98
|
+
return fail('ENROLLMENT_INVALID');
|
|
99
99
|
}
|
|
100
100
|
// Validate the source digest before replacing our trust cache on an existing registration.
|
|
101
101
|
const digest = createHash('sha256').update(metadata).digest('hex');
|
|
@@ -114,7 +114,7 @@ export function createProfileEnrollment(options) {
|
|
|
114
114
|
return fail('ENROLLMENT_INVALID');
|
|
115
115
|
await canonical(source);
|
|
116
116
|
const { host, username, port, projectRoot } = normalized.value;
|
|
117
|
-
return ok({ enrollment: normalized.value, registration: { schemaVersion: 1, requestId: record?.requestId ?? randomUUID(), source, digest, host, username, port, projectRoot } });
|
|
117
|
+
return ok({ enrollment: normalized.value, registration: { schemaVersion: 1, ...normalized.value.workspaceSources === undefined ? {} : { workspaceSources: [...normalized.value.workspaceSources] }, requestId: record?.requestId ?? randomUUID(), source, digest, host, username, port, projectRoot } });
|
|
118
118
|
}
|
|
119
119
|
catch {
|
|
120
120
|
return fail('ENROLLMENT_INVALID');
|
|
@@ -143,16 +143,17 @@ export function createProfileEnrollment(options) {
|
|
|
143
143
|
publish('blocked', result.error.code);
|
|
144
144
|
return result;
|
|
145
145
|
}
|
|
146
|
+
record = result.value.registration;
|
|
146
147
|
if (!options.activate)
|
|
147
148
|
return fail('DEPENDENCY_REQUIRED');
|
|
148
149
|
const activated = await options.activate(result.value.enrollment, abort.signal);
|
|
149
150
|
if (disposed)
|
|
150
151
|
return fail('DISPOSED');
|
|
151
152
|
if (!activated.ok) {
|
|
152
|
-
publish('blocked', activated.error
|
|
153
|
+
publish('blocked', activated.error);
|
|
153
154
|
return activated;
|
|
154
155
|
}
|
|
155
|
-
if (state.phase !== 'imported' || state.need)
|
|
156
|
+
if (state.phase !== 'imported' || state.need || JSON.stringify(state.workspaceSources) !== JSON.stringify(record.workspaceSources))
|
|
156
157
|
publish('imported');
|
|
157
158
|
return ok(result.value.enrollment);
|
|
158
159
|
})();
|
|
@@ -245,7 +246,7 @@ export function createProfileEnrollment(options) {
|
|
|
245
246
|
if (disposed)
|
|
246
247
|
return fail('DISPOSED');
|
|
247
248
|
if (!activated.ok) {
|
|
248
|
-
publish('blocked', activated.error
|
|
249
|
+
publish('blocked', activated.error);
|
|
249
250
|
return activated;
|
|
250
251
|
}
|
|
251
252
|
publish('imported');
|
package/lib/profile-runtime.js
CHANGED
|
@@ -15,6 +15,12 @@ function attachScopedProfileRuntime(ctx, api, ports, config, network, autoStart
|
|
|
15
15
|
const profile = ctx.get('profileContext');
|
|
16
16
|
if (!profile || typeof profile.dir !== 'string')
|
|
17
17
|
return;
|
|
18
|
+
let directoryConnection = '';
|
|
19
|
+
const releaseDirectories = api.onConnectionState(state => { const key = JSON.stringify([state.instanceId, state.epoch, state.phase]); if (key !== directoryConnection) {
|
|
20
|
+
directoryConnection = key;
|
|
21
|
+
void ports.hostDirectories?.reset?.().catch(() => console.warn('目录浏览连接未能完整关闭,请查看技术详情。'));
|
|
22
|
+
} });
|
|
23
|
+
ctx.effect(() => () => { releaseDirectories(); return ports.hostDirectories?.dispose?.(); });
|
|
18
24
|
const activation = createProfileActivation({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, network, settings: config.network });
|
|
19
25
|
const manager = createProfileEnrollment({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes,
|
|
20
26
|
pick: createNativeImportPicker(() => ctx.get('directoryPicker')),
|
package/lib/startup.js
CHANGED
|
@@ -10,8 +10,10 @@ export function employeeMessage(code, connection) {
|
|
|
10
10
|
return need(code).message;
|
|
11
11
|
if (code === 'DEPENDENCY_REQUIRED')
|
|
12
12
|
return '远程主机连接尚未准备好,请联系管理员。';
|
|
13
|
-
if (code === 'ENROLLMENT_REQUIRED'
|
|
14
|
-
return '
|
|
13
|
+
if (code === 'ENROLLMENT_REQUIRED')
|
|
14
|
+
return '请先导入连接资料。';
|
|
15
|
+
if (code === 'ENROLLMENT_INVALID' || code === 'NETWORK_KEY_INVALID')
|
|
16
|
+
return need(code).message;
|
|
15
17
|
if (code === 'SETTINGS_REQUIRED')
|
|
16
18
|
return need(code).message;
|
|
17
19
|
if (code === 'LOGIN_FAILED')
|