@ai-workbench/connect 0.7.28 → 0.7.31

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.
Files changed (68) hide show
  1. package/NOTICE.md +2 -6
  2. package/README.md +8 -22
  3. package/client/index.cjs +17 -11
  4. package/helper/claude-callback.cjs +2 -13
  5. package/helper/host-directories.cjs +7 -12
  6. package/helper/remote-login.cjs +4 -11
  7. package/lib/api.d.ts +13 -7
  8. package/lib/auth-diagnostics.js +1 -1
  9. package/lib/browser-login.d.ts +10 -0
  10. package/lib/browser-login.js +70 -0
  11. package/lib/components.d.ts +1 -3
  12. package/lib/components.js +37 -15
  13. package/lib/connect.js +5 -1
  14. package/lib/defaults.d.ts +0 -10
  15. package/lib/defaults.js +1 -2
  16. package/lib/host-directories.d.ts +2 -3
  17. package/lib/host-directories.js +10 -8
  18. package/lib/host-session-projects.d.ts +2 -13
  19. package/lib/host-session-projects.js +65 -50
  20. package/lib/index.d.ts +0 -9
  21. package/lib/index.js +4 -13
  22. package/lib/integration.d.ts +1 -3
  23. package/lib/integration.js +8 -26
  24. package/lib/login.d.ts +2 -2
  25. package/lib/login.js +11 -9
  26. package/lib/needs.js +2 -2
  27. package/lib/ports.d.ts +1 -0
  28. package/lib/profile-runtime.js +5 -5
  29. package/lib/profile-settings.d.ts +2 -6
  30. package/lib/profile-settings.js +4 -8
  31. package/lib/remote-login.d.ts +1 -1
  32. package/lib/remote-login.js +2 -2
  33. package/lib/startup.js +19 -1
  34. package/lib/workspace-directory-picker.js +51 -95
  35. package/lib/workspace-location-types.d.ts +18 -11
  36. package/lib/workspace-locations.d.ts +2 -12
  37. package/lib/workspace-locations.js +81 -217
  38. package/package.json +3 -6
  39. package/helper/device-panel.cjs +0 -4
  40. package/helper/device-panel.css +0 -1
  41. package/helper/device-panel.html +0 -1
  42. package/helper/device-preload.cjs +0 -5
  43. package/helper/device-window.cjs +0 -60
  44. package/helper/main.cjs +0 -19
  45. package/helper/window.cjs +0 -46
  46. package/lib/archive.d.ts +0 -1
  47. package/lib/archive.js +0 -63
  48. package/lib/cache.d.ts +0 -21
  49. package/lib/cache.js +0 -156
  50. package/lib/component-download.d.ts +0 -34
  51. package/lib/component-download.js +0 -86
  52. package/lib/component-source.d.ts +0 -31
  53. package/lib/component-source.js +0 -18
  54. package/lib/electron.d.ts +0 -8
  55. package/lib/electron.js +0 -83
  56. package/lib/physical-fs.d.ts +0 -3
  57. package/lib/physical-fs.js +0 -7
  58. package/node_modules/pend/LICENSE +0 -23
  59. package/node_modules/pend/README.md +0 -41
  60. package/node_modules/pend/index.js +0 -55
  61. package/node_modules/pend/package.json +0 -18
  62. package/node_modules/pend/test.js +0 -137
  63. package/node_modules/yauzl/LICENSE +0 -21
  64. package/node_modules/yauzl/README.md +0 -1015
  65. package/node_modules/yauzl/crc32.js +0 -45
  66. package/node_modules/yauzl/fd-slicer.js +0 -188
  67. package/node_modules/yauzl/index.js +0 -1096
  68. package/node_modules/yauzl/package.json +0 -40
@@ -1,4 +1,4 @@
1
- import { renameSync, realpathSync, lstatSync } from 'node:fs';
1
+ import { renameSync } from 'node:fs';
2
2
  import { lstat, realpath, open, rm } from 'node:fs/promises';
3
3
  import { join, isAbsolute } from 'node:path';
4
4
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
@@ -10,9 +10,8 @@ const queues = new Map();
10
10
  const hash = (v) => createHash('sha256').update(JSON.stringify(v)).digest('hex');
11
11
  const token = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
12
12
  const obj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
13
- const checksum = (r, historicalRevoked) => hash([r.workspaceId, r.localPath, r.localDev, r.localIno, r.bindingId, r.source, r.active, r.remote, r.identity, r.host, undefined, ...(historicalRevoked === undefined ? [] : [historicalRevoked])]);
13
+ const checksum = (r) => hash([r.workspaceId, r.localPath, r.localDev, r.localIno, r.bindingId, r.source, r.active, r.remote, r.identity, r.host, undefined]);
14
14
  const sameNative = (a, b) => a.workspaceId === b.workspaceId && a.localPath === b.localPath && a.localDev === b.localDev && a.localIno === b.localIno;
15
- const sameDirectory = (a, b) => a.path === b.path && a.requestedPath === b.requestedPath && a.isSymlink === b.isSymlink && JSON.stringify(a.identity) === JSON.stringify(b.identity) && JSON.stringify(a.entryIdentity) === JSON.stringify(b.entryIdentity);
16
15
  export function createWorkspaceLocations(o) {
17
16
  const controllers = new Set();
18
17
  const root = join(o.profileDir, 'ai-workbench-connect'), file = join(root, 'locations.json'), secret = randomBytes(32), listeners = new Set();
@@ -93,17 +92,28 @@ export function createWorkspaceLocations(o) {
93
92
  const data = JSON.parse(raw);
94
93
  if (!obj(data) || data.schemaVersion !== 1 || !Array.isArray(data.items))
95
94
  reject('WORKSPACE_LOCATION_STORAGE_FAILED');
96
- const items = data.items.filter(r => !obj(r) || r.source !== 'legacy-host');
97
- const ids = new Set(), active = new Set();
98
- for (const r of items) {
99
- if (!obj(r) || !token(r.bindingId) || !token(r.workspaceId) || !isAbsolute(r.localPath) || !Number.isSafeInteger(r.localDev) || !Number.isSafeInteger(r.localIno) || !['local', 'host'].includes(r.source) || typeof r.active !== 'boolean' || r.legacyBindingId !== undefined || r.revoked !== undefined && (r.source !== 'host' || !['HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_UNREADABLE'].includes(r.revoked)) || r.key !== checksum(r, r.revoked) || ids.has(r.bindingId) || r.active && active.has(r.workspaceId) || r.source !== 'local' && (!obj(r.remote) || !isAbsolute(r.remote.path) || !isAbsolute(r.remote.requestedPath) || !obj(r.remote.identity) || !obj(r.remote.entryIdentity) || !obj(r.remote.permissions) || !obj(r.host) || !token(r.host.host) || !token(r.host.username) || !Number.isSafeInteger(r.host.port) || !(/^[a-f0-9]{64}$/.test(r.identity))))
95
+ const result = [], ids = new Set(), active = new Set();
96
+ for (const r of data.items) {
97
+ if (r?.source === 'legacy-host' || r?.source === 'host' && r.active === false)
98
+ continue;
99
+ if (!obj(r) || !token(r.workspaceId) || typeof r.active !== 'boolean' || r.active && active.has(r.workspaceId))
100
100
  reject('WORKSPACE_LOCATION_STORAGE_FAILED');
101
- ids.add(r.bindingId);
101
+ if (r.source === 'host') {
102
+ // 旧记录仅取主机与路径;旧 identity/key/dev/ino 不再属于主机来源合同。
103
+ if (!obj(r.host) || !token(r.host.host) || !obj(r.remote) || !token(r.remote.path) || !isAbsolute(r.remote.path))
104
+ reject('WORKSPACE_LOCATION_STORAGE_FAILED');
105
+ result.push({ workspaceId: r.workspaceId, source: 'host', active: r.active, host: { host: r.host.host }, remote: { path: r.remote.path } });
106
+ }
107
+ else {
108
+ if (r.source !== 'local' || !token(r.bindingId) || !isAbsolute(r.localPath) || !Number.isSafeInteger(r.localDev) || !Number.isSafeInteger(r.localIno) || r.key !== checksum(r) || r.legacyBindingId !== undefined || r.revoked !== undefined || ids.has(r.bindingId))
109
+ reject('WORKSPACE_LOCATION_STORAGE_FAILED');
110
+ ids.add(r.bindingId);
111
+ result.push(r);
112
+ }
102
113
  if (r.active)
103
114
  active.add(r.workspaceId);
104
- delete r.revoked;
105
115
  }
106
- return items;
116
+ return result;
107
117
  }
108
118
  function guardStoredBinding(expected) {
109
119
  const current = parseRecords(readPrivateSync(file, o.metadataMaxBytes)).find(r => r.active && r.workspaceId === expected.workspaceId);
@@ -114,7 +124,8 @@ export function createWorkspaceLocations(o) {
114
124
  }
115
125
  async function save(items, beforeCommit, context) {
116
126
  for (const r of items)
117
- r.key = checksum(r);
127
+ if (r.source === 'local')
128
+ r.key = checksum(r);
118
129
  const bytes = JSON.stringify({ schemaVersion: 1, items }) + '\n';
119
130
  if (!Number.isSafeInteger(o.metadataMaxBytes) || o.metadataMaxBytes < 1 || Buffer.byteLength(bytes) > o.metadataMaxBytes)
120
131
  reject('WORKSPACE_LOCATION_STORAGE_FAILED');
@@ -129,7 +140,8 @@ export function createWorkspaceLocations(o) {
129
140
  await h.close();
130
141
  }
131
142
  await beforeCommit();
132
- check(context);
143
+ if (context)
144
+ check(context);
133
145
  renameSync(temp, file);
134
146
  const d = await open(root, 'r');
135
147
  try {
@@ -170,7 +182,7 @@ export function createWorkspaceLocations(o) {
170
182
  const current = stored.find(r => r.active && r.workspaceId === c.workspaceId);
171
183
  if ((current?.bindingId ?? null) !== c.expectedBindingId)
172
184
  reject('WORKSPACE_LOCATION_CONFLICT');
173
- if (current && !sameNative(current, n))
185
+ if (current?.source === 'local' && !sameNative(current, n))
174
186
  reject('WORKSPACE_LOCATION_INVALID');
175
187
  return { stored, n, current };
176
188
  }
@@ -185,15 +197,8 @@ export function createWorkspaceLocations(o) {
185
197
  controllers.delete(controller);
186
198
  }
187
199
  }
188
- async function target(c) {
189
- const t = o.api.getModelCatalogTarget('codex');
190
- if (!t.ok)
191
- throw new NeedError(t.error);
192
- const trust = await readPrivate(t.value.target.knownHostsFile, o.metadataMaxBytes);
193
- check(c);
194
- const value = t.value.target;
195
- return { value, identity: hash([value.host, value.username, value.port, value.projectRoot, value.session, trust]) };
196
- }
200
+ function target() { const t = o.api.getModelCatalogTarget('codex'); if (!t.ok)
201
+ throw new NeedError(t.error); return t.value.target; }
197
202
  const seal = (data) => { const body = Buffer.from(JSON.stringify(data)).toString('base64url'); return body + '.' + createHmac('sha256', secret).update(body).digest('base64url'); };
198
203
  function unseal(value) {
199
204
  if (!token(value) || Buffer.byteLength(value) > o.metadataMaxBytes)
@@ -211,17 +216,17 @@ export function createWorkspaceLocations(o) {
211
216
  reject('WORKSPACE_LOCATION_CONFLICT');
212
217
  }
213
218
  }
214
- function directoryChange(a, b) {
215
- if (a.path !== b.path || a.requestedPath !== b.requestedPath || a.identity.device !== b.identity.device || a.identity.inode !== b.identity.inode || a.entryIdentity.device !== b.entryIdentity.device || a.entryIdentity.inode !== b.entryIdentity.inode || a.isSymlink !== b.isSymlink)
216
- return 'HOST_DIRECTORY_CHANGED';
217
- if (b.permissions.read === false || b.permissions.execute === false)
218
- return 'HOST_DIRECTORY_UNREADABLE';
219
- if (['read', 'write', 'execute'].some(k => typeof a.permissions[k] === 'boolean' && typeof b.permissions[k] === 'boolean' && a.permissions[k] !== b.permissions[k]))
220
- return 'HOST_DIRECTORY_CHANGED';
221
- }
222
- async function items(stored, inspectHost = false, c = connection()) {
219
+ async function items(stored) {
223
220
  const result = [];
224
221
  for (const w of o.registry.list()) {
222
+ const r = stored.find(r => r.active && r.workspaceId === w.id);
223
+ if (r?.source === 'host') {
224
+ const title = w.title.replace(/(本机)$|(远程主机)$/u, '') + '(远程主机)';
225
+ if (w.setTitle && w.title !== title)
226
+ await w.setTitle(title);
227
+ result.push({ workspaceId: w.id, workspaceName: title, localPath: w.path, bindingId: null, source: 'host', host: r.host, remote: r.remote });
228
+ continue;
229
+ }
225
230
  let n;
226
231
  try {
227
232
  n = await native(w.id);
@@ -230,140 +235,72 @@ export function createWorkspaceLocations(o) {
230
235
  result.push({ workspaceId: w.id, workspaceName: w.title, localPath: w.path, bindingId: null, source: null, status: 'invalid', execution: 'not-selected', need: need('WORKSPACE_LOCATION_INVALID') });
231
236
  continue;
232
237
  }
233
- const r = stored.find(r => r.active && r.workspaceId === w.id);
234
- const base = { workspaceId: w.id, workspaceName: w.title || w.id, localPath: n.localPath, bindingId: r?.bindingId ?? null };
235
- if (r) {
236
- let valid = sameNative(r, n), error;
237
- // 来源来自本插件的原生路径绑定,离线仍可显示;不改目录或员工自取名称。
238
- if (valid && w.setTitle) {
239
- const title = w.title.replace(/(本机)$|(远程主机)$/u, '') + (r.source === 'local' ? '(本机)' : '(远程主机)');
240
- if (title !== w.title) {
241
- await w.setTitle(title);
242
- check(c);
243
- }
244
- base.workspaceName = title;
245
- }
246
- if (valid && r.source !== 'local') {
247
- try {
248
- valid = (await target(c)).identity === r.identity;
249
- if (valid && inspectHost && r.source === 'host') {
250
- const t = await target(c);
251
- check(c);
252
- const inspected = o.hostDirectories ? await remote(c, signal => o.hostDirectories.inspect(t.value, r.remote.requestedPath, signal)) : fail('DEPENDENCY_REQUIRED');
253
- check(c);
254
- if (!inspected.ok)
255
- error = inspected.error.code;
256
- else {
257
- const changed = directoryChange(r.remote, inspected.value);
258
- if (changed) {
259
- error = changed;
260
- }
261
- else if (Object.values(inspected.value.permissions).includes(null))
262
- error = 'HOST_DIRECTORY_UNREADABLE';
263
- }
264
- }
265
- }
266
- catch (e) {
267
- check(c);
268
- valid = false;
269
- error = e instanceof NeedError ? e.need.code : 'WORKSPACE_LOCATION_STORAGE_FAILED';
270
- }
271
- }
272
- result.push({ ...base, source: r.source, status: valid && !error ? 'selected' : 'invalid', execution: r.source === 'local' ? 'local-pending' : 'host-pending', ...(r.remote ? { remote: r.remote, host: r.host } : {}), ...(!valid || error ? { need: need(error ?? 'WORKSPACE_LOCATION_INVALID') } : {}) });
238
+ let title = w.title;
239
+ if (r && w.setTitle) {
240
+ title = w.title.replace(/(本机)$|(远程主机)$/u, '') + '(本机)';
241
+ if (title !== w.title)
242
+ await w.setTitle(title);
273
243
  }
274
- else
275
- result.push({ ...base, source: null, status: 'unselected', execution: 'not-selected' });
244
+ const valid = !r || sameNative(r, n);
245
+ result.push({ workspaceId: w.id, workspaceName: title || w.id, localPath: n.localPath, bindingId: r?.bindingId ?? null, source: r ? 'local' : null, status: r ? (valid ? 'selected' : 'invalid') : 'unselected', execution: r ? 'local-pending' : 'not-selected', ...(!valid ? { need: need('WORKSPACE_LOCATION_INVALID') } : {}) });
276
246
  }
277
247
  return result;
278
248
  }
279
- async function refresh(c = connection()) {
280
- try {
281
- check(c);
282
- await prepare();
283
- const stored = await records();
284
- const next = await items(stored, true, c);
285
- check(c);
286
- publish(next);
287
- return ok(structuredClone(snapshot));
288
- }
289
- catch (e) {
290
- if (exact(c))
291
- publish(snapshot.items, e instanceof NeedError ? e.need.code : 'WORKSPACE_LOCATION_STORAGE_FAILED');
292
- throw e;
293
- }
249
+ async function refresh() { try {
250
+ await prepare();
251
+ publish(await items(await records()));
252
+ return ok(structuredClone(snapshot));
294
253
  }
254
+ catch (e) {
255
+ publish(snapshot.items, e instanceof NeedError ? e.need.code : 'WORKSPACE_LOCATION_STORAGE_FAILED');
256
+ throw e;
257
+ } }
295
258
  function strict(value, keys) {
296
259
  if (Object.keys(value).some(k => !keys.includes(k)))
297
260
  reject('WORKSPACE_LOCATION_INVALID');
298
261
  }
299
262
  async function browse(c) {
300
- strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId', 'path', 'cursor', 'pageSize']);
301
- if (c.path !== undefined && (!isAbsolute(c.path) || c.path.includes('\0')) || c.path !== undefined && c.cursor !== undefined || c.pageSize !== undefined && (!Number.isSafeInteger(c.pageSize) || c.pageSize < 1))
263
+ await prepare();
264
+ if (!token(c.workspaceId) || c.path !== undefined && (!token(c.path) || !isAbsolute(c.path)))
302
265
  reject('HOST_DIRECTORY_INVALID');
303
- const x = await context(c), t = await target(c);
266
+ const t = target();
304
267
  if (!o.hostDirectories)
305
268
  reject('DEPENDENCY_REQUIRED');
306
- let request = { pageSize: c.pageSize ?? o.pageSize, ...(c.path !== undefined ? { path: c.path } : {}) };
307
- if (c.cursor) {
308
- const saved = unseal(c.cursor);
309
- if (saved.kind !== 'cursor' || JSON.stringify(saved.context) !== JSON.stringify({ instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, expectedBindingId: c.expectedBindingId }) || !sameNative(saved.native, x.n) || saved.identity !== t.identity || c.pageSize !== undefined && c.pageSize !== saved.request.pageSize)
310
- reject('WORKSPACE_LOCATION_CONFLICT');
311
- request = saved.request;
312
- }
313
- const page = await remote(c, signal => o.hostDirectories.browse(t.value, request, signal));
314
- check(c);
269
+ const previous = c.cursor ? unseal(c.cursor) : undefined;
270
+ const page = await remote(connection(), signal => o.hostDirectories.browse(t, { ...(c.path ? { path: c.path } : previous ? { path: previous.path } : {}), pageSize: c.pageSize ?? o.pageSize, ...(previous ? { after: previous.after } : {}) }, signal));
315
271
  if (!page.ok)
316
272
  return page;
317
- if (!sameNative(await native(c.workspaceId), x.n))
318
- reject('WORKSPACE_LOCATION_CONFLICT');
319
- check(c);
320
- const base = { context: { instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, expectedBindingId: c.expectedBindingId }, native: x.n, identity: t.identity };
321
- const choose = (info) => seal({ kind: 'selection', ...base, info });
322
- const { entries, nextAfter, ...info } = page.value;
323
- return ok({ ...info, ...connection(), workspaceId: c.workspaceId, bindingId: c.expectedBindingId, host: { host: t.value.host, username: t.value.username, port: t.value.port }, selectionToken: choose(info), pageSize: request.pageSize, entries: entries.map(e => ({ ...e, ...(e.path && e.identity && !e.errorCode ? { selectionToken: choose({ requestedPath: e.requestedPath, path: e.path, parentPath: info.path, identity: e.identity, entryIdentity: e.entryIdentity, isSymlink: e.isSymlink, permissions: e.permissions }) } : {}) })), ...(nextAfter ? { nextCursor: seal({ kind: 'cursor', ...base, request: { path: info.requestedPath, pageSize: request.pageSize, after: nextAfter, expected: info.identity } }) } : {}) });
273
+ const host = { host: t.host, username: t.username, port: t.port };
274
+ return ok({ ...page.value, ...connection(), workspaceId: c.workspaceId, bindingId: c.expectedBindingId, host, pageSize: c.pageSize ?? o.pageSize, selectionToken: seal({ host: t.host, path: page.value.path }), entries: page.value.entries.map(e => ({ ...e, selectionToken: seal({ host: t.host, path: e.path ?? e.requestedPath }) })), ...(page.value.nextAfter ? { nextCursor: seal({ path: page.value.path, after: page.value.nextAfter }) } : {}) });
324
275
  }
325
276
  async function select(c) {
326
- if (!obj(c))
327
- reject('WORKSPACE_LOCATION_INVALID');
328
- strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId', 'source', ...(c.source === 'host' ? ['selectionToken'] : [])]);
329
- if (!['local', 'host'].includes(c.source))
277
+ if (!obj(c) || !['local', 'host'].includes(c.source))
330
278
  reject('WORKSPACE_LOCATION_INVALID');
331
- const x = await context(c);
332
- let r = { ...x.n, bindingId: randomUUID(), source: c.source, active: true, key: '' };
333
- if (c.source !== 'local') {
334
- const t = await target(c);
335
- if (!o.hostDirectories)
336
- reject('DEPENDENCY_REQUIRED');
337
- const selected = unseal(c.selectionToken);
338
- if (selected.kind !== 'selection' || !sameNative(selected.native, x.n) || selected.identity !== t.identity || JSON.stringify(selected.context) !== JSON.stringify({ instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, expectedBindingId: c.expectedBindingId }))
339
- reject('WORKSPACE_LOCATION_CONFLICT');
340
- const selectedInfo = selected.info;
341
- const inspected = await remote(c, signal => o.hostDirectories.inspect(t.value, selectedInfo.requestedPath, signal));
342
- check(c);
343
- if (!inspected.ok)
344
- return inspected;
345
- if (!sameDirectory(selectedInfo, inspected.value))
346
- reject('HOST_DIRECTORY_CHANGED');
347
- if (inspected.value.permissions.read !== true || inspected.value.permissions.execute !== true)
348
- reject('HOST_DIRECTORY_UNREADABLE');
349
- r = { ...r, remote: inspected.value, identity: t.identity, host: { host: t.value.host, username: t.value.username, port: t.value.port } };
279
+ if (c.source === 'host') {
280
+ await prepare();
281
+ const selected = 'selectionToken' in c ? unseal(c.selectionToken) : c;
282
+ if (!token(c.workspaceId) || !token(selected.host) || !token(selected.path) || !isAbsolute(selected.path))
283
+ reject('HOST_DIRECTORY_INVALID');
284
+ const stored = await records();
285
+ for (const old of stored)
286
+ if (old.workspaceId === c.workspaceId)
287
+ old.active = false;
288
+ stored.push({ workspaceId: c.workspaceId, source: 'host', active: true, host: { host: selected.host }, remote: { path: selected.path } });
289
+ await save(stored, async () => { });
290
+ publish(await items(stored));
291
+ return ok(structuredClone(snapshot));
350
292
  }
351
- if (!sameNative(await native(c.workspaceId), x.n))
352
- reject('WORKSPACE_LOCATION_CONFLICT');
353
- check(c);
354
- if (x.current && x.current.source === r.source && JSON.stringify(x.current.remote) === JSON.stringify(r.remote) && x.current.identity === r.identity)
293
+ strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId', 'source']);
294
+ const x = await context(c);
295
+ if (x.current?.source === 'local')
355
296
  return ok(structuredClone(snapshot));
297
+ const r = { ...x.n, bindingId: randomUUID(), source: 'local', active: true, key: '' };
356
298
  for (const old of x.stored)
357
299
  if (old.active && old.workspaceId === c.workspaceId)
358
300
  old.active = false;
359
- if (x.stored.some(old => old.bindingId === r.bindingId))
360
- reject('WORKSPACE_LOCATION_CONFLICT');
361
301
  x.stored.push(r);
362
- await save(x.stored, async () => {
363
- if (!sameNative(await native(c.workspaceId), x.n))
364
- reject('WORKSPACE_LOCATION_CONFLICT');
365
- check(c);
366
- }, c);
302
+ await save(x.stored, async () => { if (!sameNative(await native(c.workspaceId), x.n))
303
+ reject('WORKSPACE_LOCATION_CONFLICT'); check(c); }, c);
367
304
  publish(await items(x.stored));
368
305
  check(c);
369
306
  return ok(structuredClone(snapshot));
@@ -424,93 +361,20 @@ export function createWorkspaceLocations(o) {
424
361
  const c = { instanceId: request.instanceId, epoch: request.epoch, workspaceId: request.workspaceId, expectedBindingId: request.expectedBindingId };
425
362
  return serial(() => localContext(c));
426
363
  }
427
- function withHostBinding(input, run, finalize = () => { }) {
428
- const c = structuredClone(input);
429
- return serial(async () => {
430
- strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId']);
431
- if (!token(c.expectedBindingId))
432
- reject('WORKSPACE_LOCATION_INVALID');
433
- checkPending(c.workspaceId);
434
- const x = await context(c), r = x.current;
435
- if (!r || r.source !== 'host' || !r.remote)
436
- reject('WORKSPACE_LOCATION_CONFLICT');
437
- const t = await target(c);
438
- check(c);
439
- if (t.identity !== r.identity)
440
- reject('WORKSPACE_LOCATION_INVALID');
441
- const bytes = await readPrivate(file, o.metadataMaxBytes), registeredPath = registeredLocalPath(c.workspaceId);
442
- const guard = () => {
443
- checkPending(c.workspaceId);
444
- check(c);
445
- const now = o.api.getConnectionState();
446
- if (now.phase !== 'connected')
447
- reject('CONNECTION_LOST');
448
- const latest = o.api.getModelCatalogTarget('codex');
449
- if (!latest.ok)
450
- throw new NeedError(latest.error);
451
- const v = latest.value.target;
452
- if (hash([v.host, v.username, v.port, v.projectRoot, v.session, readPrivateSync(v.knownHostsFile, o.metadataMaxBytes)]) !== t.identity)
453
- reject('WORKSPACE_LOCATION_INVALID');
454
- if (readPrivateSync(file, o.metadataMaxBytes) !== bytes)
455
- reject('WORKSPACE_LOCATION_CONFLICT');
456
- if (registeredLocalPath(c.workspaceId) !== registeredPath)
457
- reject('WORKSPACE_LOCATION_INVALID');
458
- try {
459
- const path = realpathSync(registeredPath), st = lstatSync(path);
460
- if (path !== x.n.localPath || !st.isDirectory() || st.dev !== x.n.localDev || st.ino !== x.n.localIno)
461
- reject('WORKSPACE_LOCATION_INVALID');
462
- }
463
- catch (e) {
464
- if (e instanceof NeedError)
465
- throw e;
466
- reject('WORKSPACE_LOCATION_INVALID');
467
- }
468
- };
469
- guard();
470
- if (!o.hostDirectories)
471
- reject('DEPENDENCY_REQUIRED');
472
- const current = await remote(c, signal => o.hostDirectories.inspect(t.value, r.remote.requestedPath, signal));
473
- if (!current.ok)
474
- throw new NeedError(current.error);
475
- const changed = directoryChange(r.remote, current.value);
476
- if (changed)
477
- reject(changed);
478
- if (Object.values(current.value.permissions).includes(null))
479
- reject('HOST_DIRECTORY_UNREADABLE');
480
- const value = { directory: current.value, target: structuredClone(t.value), local: { path: x.n.localPath, device: x.n.localDev, inode: x.n.localIno }, revision: snapshot.revision };
481
- const result = await run(value, guard);
482
- if (!result.ok)
483
- return result;
484
- guard();
485
- finalize();
486
- return result;
487
- });
488
- }
489
364
  function captureWorkspacePickerGuard(workspaceId, expectedBindingId) {
490
365
  const original = parseRecords(readPrivateSync(file, o.metadataMaxBytes)).find(r => r.active && r.workspaceId === workspaceId);
491
- if (!original || original.bindingId !== expectedBindingId)
366
+ if (!original || original.source !== 'local' || original.bindingId !== expectedBindingId)
492
367
  reject('WORKSPACE_LOCATION_CONFLICT');
493
368
  const registeredPath = registeredLocalPath(workspaceId);
494
369
  return () => { guardStoredBinding(original); if (registeredLocalPath(workspaceId) !== registeredPath)
495
370
  reject('WORKSPACE_LOCATION_INVALID'); };
496
371
  }
497
- return { captureWorkspacePickerGuard, withHostBinding, getLocalWorkspaceContext, getWorkspaceLocationState: () => ({ ...structuredClone(snapshot), host: currentHost() }), onWorkspaceLocationState(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, refreshWorkspaceLocations: () => serial(refresh), browseWorkspaceHostDirectories: (c) => serial(() => browse(c)), selectWorkspaceLocation: (c) => serial(() => select(c)), observeConnection() {
372
+ return { captureWorkspacePickerGuard, getLocalWorkspaceContext, getWorkspaceLocationState: () => ({ ...structuredClone(snapshot), host: currentHost() }), onWorkspaceLocationState(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, refreshWorkspaceLocations: () => serial(refresh), browseWorkspaceHostDirectories: (c) => serial(() => browse(c)), selectWorkspaceLocation: (c) => serial(() => select(c)), observeConnection() {
498
373
  if (disposed)
499
374
  return;
500
375
  for (const controller of controllers)
501
376
  controller.abort();
502
- const connected = o.api.getConnectionState().phase === 'connected';
503
- publish(snapshot.items.map(item => {
504
- if (item.source !== 'host')
505
- return item;
506
- if (!connected)
507
- return { ...item, need: need('CONNECTION_LOST') };
508
- if (item.need?.code === 'CONNECTION_LOST' || item.need?.code === 'WORKSPACE_LOCATION_CONFLICT') {
509
- const { need: _, ...selected } = item;
510
- return selected;
511
- }
512
- return item;
513
- }));
377
+ publish(snapshot.items);
514
378
  }, dispose() {
515
379
  disposed = true;
516
380
  for (const controller of controllers)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/connect",
3
- "version": "0.7.28",
3
+ "version": "0.7.31",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.13.1"
@@ -53,14 +53,12 @@
53
53
  "@deepseek-ai/schemastery": "3.18.4",
54
54
  "@types/js-yaml": "4.0.9",
55
55
  "@types/node": "24.0.0",
56
- "@types/yauzl": "2.10.3",
57
56
  "react": "18.3.1",
58
57
  "react-test-renderer": "18.3.1",
59
58
  "typescript": "5.9.3"
60
59
  },
61
60
  "dependencies": {
62
- "js-yaml": "4.3.2",
63
- "yauzl": "3.4.0"
61
+ "js-yaml": "4.3.2"
64
62
  },
65
63
  "dsh": {
66
64
  "client": {
@@ -79,8 +77,7 @@
79
77
  },
80
78
  "description": "查看远程主机连接状态并管理 Claude/Codex 登录。",
81
79
  "bundleDependencies": [
82
- "js-yaml",
83
- "yauzl"
80
+ "js-yaml"
84
81
  ],
85
82
  "publishConfig": {
86
83
  "access": "public"
@@ -1,4 +0,0 @@
1
- 'use strict';
2
- const code=document.getElementById('code'),copy=document.getElementById('copy'),status=document.getElementById('status');
3
- window.deviceLogin.readCode().then(value=>{code.textContent=value;copy.disabled=false;}).catch(()=>{code.textContent='读取失败';status.textContent='请关闭窗口,回设置查看详情';});
4
- copy.addEventListener('click',async()=>{try{await window.deviceLogin.copyCode();status.textContent='已复制,请粘贴到下方官方页面';}catch{status.textContent='复制失败,请手动选择上方代码';}});
@@ -1 +0,0 @@
1
- :root{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#202124;background:#f6f7f9;color-scheme:light}*{box-sizing:border-box}body{margin:0}main{height:160px;padding:16px 24px;border-bottom:1px solid #d7dce2;display:grid;grid-template-columns:1fr auto;gap:8px 24px}.label{font-size:12px;color:#586174;display:block}strong{font:700 32px ui-monospace,SFMono-Regular,Consolas,monospace;letter-spacing:2px;user-select:text}.action{display:flex;flex-direction:column;align-items:center;gap:6px;justify-content:center}button{border:0;border-radius:7px;background:#1759bb;color:#fff;font-size:14px;padding:10px 16px;cursor:pointer}button:disabled{opacity:.5;cursor:default}button:focus-visible{outline:3px solid #9bc0fa;outline-offset:3px}#status{font-size:12px;color:#586174}p{grid-column:1/-1;margin:0;font-size:13px;line-height:1.5;color:#465064}
@@ -1 +0,0 @@
1
- <!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; base-uri 'none'; form-action 'none'"><title>登录 Codex</title><link rel="stylesheet" href="device-panel.css"></head><body><main><div><span class="label">本次设备码</span><strong id="code" aria-label="本次设备码">正在读取…</strong></div><div class="action"><button id="copy" type="button" disabled>复制一次性码</button><span id="status" role="status">仅复制本次登录的码</span></div><p>下方网页使用本机网络。登录后复制上方代码,粘贴到官方输码框,再按页面提示确认。当前不支持自动填码。</p></main><script src="device-panel.cjs"></script></body></html>
@@ -1,5 +0,0 @@
1
- const {contextBridge,ipcRenderer}=require('electron');
2
- const prefix='--aw-device-channel=',arg=process.argv.find(value=>value.startsWith(prefix));
3
- if(!arg)throw Error('DEVICE_CHANNEL_REQUIRED');
4
- const channel=arg.slice(prefix.length);
5
- contextBridge.exposeInMainWorld('deviceLogin',Object.freeze({readCode:()=>ipcRenderer.invoke(channel+'-read'),copyCode:()=>ipcRenderer.invoke(channel+'-copy')}));
@@ -1,60 +0,0 @@
1
- const {randomUUID}=require('node:crypto');
2
- const {join}=require('node:path');
3
- const {pathToFileURL}=require('node:url');
4
- function bindDeviceExit(app,close,send,signals=process){
5
- let finishing;
6
- const unbind=()=>{signals.removeListener('SIGTERM',finish);app.removeListener('before-quit',beforeQuit);};
7
- const finish=()=>finishing??=(async()=>{
8
- try{await close();}catch{send({type:'error',code:'CLEANUP_FAILED'});}
9
- finally{unbind();app.quit();}
10
- })();
11
- const beforeQuit=event=>{event.preventDefault();void finish();};
12
- signals.on('SIGTERM',finish);app.on('before-quit',beforeQuit);return unbind;
13
- }
14
- async function openDeviceWindow({app,BrowserWindow,WebContentsView,session,ipcMain,clipboard},boot,send){
15
- if(boot.provider!=='codex'||boot.url!=='https://auth.openai.com/codex/device'||typeof boot.deviceCode!=='string'||!boot.deviceCode||/[\x00-\x1f\x7f]/.test(boot.deviceCode))throw Error('DEVICE_BOOT_INVALID');
16
- const ses=session.fromPartition('aw-device-'+randomUUID(),{cache:false});
17
- await ses.setProxy({mode:'system'});
18
- ses.setPermissionRequestHandler((_contents,_permission,callback)=>callback(false));
19
- ses.on('will-download',event=>event.preventDefault());
20
- const channel='aw-device-'+randomUUID(),panelFile=join(__dirname,'device-panel.html'),panelUrl=pathToFileURL(panelFile).href;
21
- const win=new BrowserWindow({title:'登录 Codex',show:true,width:900,height:800,webPreferences:{session:ses,preload:join(__dirname,'device-preload.cjs'),additionalArguments:['--aw-device-channel='+channel],nodeIntegration:false,contextIsolation:true,sandbox:true,devTools:false,spellcheck:false}});
22
- const page=new WebContentsView({webPreferences:{session:ses,nodeIntegration:false,contextIsolation:true,sandbox:true,devTools:false,spellcheck:false}});
23
- win.contentView.addChildView(page);
24
- const layout=()=>{const [width,height]=win.getContentSize();page.setBounds({x:0,y:160,width,height:Math.max(0,height-160)});};layout();win.on('resize',layout);
25
- let closing,copyAttempted=false,unbindExit=()=>{};const pendingCopies=new Set();
26
- const check=(event,args)=>{
27
- if(closing||args.length||event.sender!==win.webContents||event.senderFrame!==win.webContents.mainFrame||event.senderFrame.url!==panelUrl)throw Error('DEVICE_IPC_REJECTED');
28
- };
29
- ipcMain.handle(channel+'-read',(event,...args)=>{check(event,args);return boot.deviceCode;});
30
- ipcMain.handle(channel+'-copy',(event,...args)=>{
31
- check(event,args);copyAttempted=true;const code=boot.deviceCode;
32
- const operation=Promise.resolve().then(()=>clipboard.writeText(code)).then(()=>true);
33
- pendingCopies.add(operation);void operation.then(()=>pendingCopies.delete(operation),()=>pendingCopies.delete(operation));return operation;
34
- });
35
- const close=()=>closing??=Promise.resolve().then(async()=>{
36
- try{
37
- ipcMain.removeHandler(channel+'-read');ipcMain.removeHandler(channel+'-copy');
38
- // Do not erase a clipboard the employee has since changed. No clipboard history is retained.
39
- await Promise.allSettled([...pendingCopies]);
40
- let clipboardFailed=false;
41
- try{if(copyAttempted&&(await clipboard.readText())===boot.deviceCode)await clipboard.clear();}catch{clipboardFailed=true;}
42
- boot.deviceCode='';
43
- if(!page.webContents.isDestroyed())page.webContents.close({waitForBeforeUnload:false});
44
- if(!win.isDestroyed())win.destroy();
45
- const cleaned=await Promise.allSettled([ses.closeAllConnections(),ses.clearStorageData(),ses.clearCache()]);
46
- if(clipboardFailed||cleaned.some(result=>result.status==='rejected'))throw Error('CLEANUP_FAILED');
47
- }finally{unbindExit();}
48
- send({type:'closed'});
49
- });
50
- if(app)unbindExit=bindDeviceExit(app,close,send);
51
- win.on('closed',()=>{void close().catch(()=>send({type:'error',code:'CLEANUP_FAILED'}));});
52
- win.webContents.setWindowOpenHandler(()=>({action:'deny'}));
53
- win.webContents.on('will-navigate',(event,url)=>{if((event.url??url)!==panelUrl)event.preventDefault();});
54
- page.webContents.setWindowOpenHandler(({url})=>{if(url.startsWith('https://'))void page.webContents.loadURL(url).catch(()=>send({type:'error',code:'NAVIGATION_FAILED'}));return {action:'deny'};});
55
- const httpsOnly=(event,url)=>{if(typeof (event.url??url)!=='string'||!(event.url??url).startsWith('https://'))event.preventDefault();};
56
- page.webContents.on('will-navigate',httpsOnly);page.webContents.on('will-redirect',httpsOnly);
57
- try{await win.loadFile(panelFile);await page.webContents.loadURL(boot.url);}catch{if(closing){await closing;return {close};}await close();throw Error('NAVIGATION_FAILED');}
58
- if(!closing)send({type:'ready'});return {close};
59
- }
60
- module.exports={openDeviceWindow,bindDeviceExit};
package/helper/main.cjs DELETED
@@ -1,19 +0,0 @@
1
- const {app}=require('electron');
2
- const {createInterface}=require('node:readline');
3
- const {openWindow}=require('./window.cjs');
4
- const input=createInterface({input:process.stdin});let active,started=false;
5
- const send=event=>{process.stdout.write(JSON.stringify(event)+'\n');if(event.type==='closed')app.quit();};
6
- input.on('line',async line=>{
7
- try{
8
- const message=JSON.parse(line);
9
- if(started){if(message.type==='close'){await active?.close();app.quit();}return;}
10
- started=true;
11
- // Parent creates this private disposable directory; OAuth data remains in a memory session.
12
- app.setPath('userData',message.userDataDir);app.setPath('sessionData',message.userDataDir);
13
- app.commandLine.appendSwitch('disable-background-networking');
14
- app.commandLine.appendSwitch('disable-component-update');
15
- await app.whenReady();active=await openWindow(require('electron'),message,send);
16
- }catch{send({type:'error',code:'HELPER_FAILED'});await active?.close();app.quit();}
17
- });
18
- input.on('close',async()=>{await active?.close();app.quit();});
19
- app.on('window-all-closed',()=>{});
package/helper/window.cjs DELETED
@@ -1,46 +0,0 @@
1
- const {randomUUID}=require('node:crypto');
2
- const {isCallback,createClaudeCapture}=require('./claude-callback.cjs');
3
- async function openWindow(electron,boot,send){
4
- const {BrowserWindow,session}=electron;
5
- if(!['claude','codex'].includes(boot.provider))throw new Error('LOGIN_PROVIDER_INVALID');
6
- if(boot.provider==='codex')return require('./device-window.cjs').openDeviceWindow(electron,boot,send);
7
- const capture=boot.provider==='claude'?createClaudeCapture(boot.url):null;
8
- const ses=session.fromPartition('aw-login-'+randomUUID(),{cache:false});
9
- await ses.setProxy({mode:'system'});
10
- ses.setPermissionRequestHandler((_contents,_permission,callback)=>callback(false));
11
- ses.on('will-download',event=>event.preventDefault());
12
- const win=new BrowserWindow({show:true,webPreferences:{session:ses,nodeIntegration:false,contextIsolation:true,sandbox:true,devTools:false,spellcheck:false}});
13
- let closing,capturedCode=false;
14
- const close=()=>closing??=(async()=>{
15
- if(!win.isDestroyed())win.destroy();
16
- await ses.closeAllConnections();await ses.clearStorageData();await ses.clearCache();
17
- send({type:'closed'});
18
- })();
19
- win.on('closed',()=>{void close().catch(()=>send({type:'error',code:'CLEANUP_FAILED'}));});
20
- win.webContents.setWindowOpenHandler(({url})=>{
21
- if(url.startsWith('https://'))void win.loadURL(url).catch(()=>send({type:'error',code:'NAVIGATION_FAILED'}));
22
- return {action:'deny'};
23
- });
24
- const captureUrl=(url,main,event)=>{
25
- if(!capture||main!==true||typeof url!=='string')return;
26
- const result=capture.capture(url);if(result.kind==='unrelated')return;
27
- event?.preventDefault?.();
28
- if(result.kind==='code'){capturedCode=true;send({type:'claude-code',code:result.code});}
29
- else if(result.kind==='error')send({type:'error',code:result.error});
30
- };
31
- win.webContents.on('will-navigate',(event,legacyUrl)=>{
32
- const url=typeof event.url==='string'?event.url:legacyUrl;
33
- captureUrl(url,true,event);
34
- if(typeof url!=='string'||!url.startsWith('https://'))event.preventDefault();
35
- });
36
- win.webContents.on('will-redirect',(event,legacyUrl,_inPlace,legacyMain)=>{
37
- captureUrl(typeof event.url==='string'?event.url:legacyUrl,typeof event.isMainFrame==='boolean'?event.isMainFrame:legacyMain,event);
38
- });
39
- win.webContents.on('did-navigate',(_event,url)=>captureUrl(url,true));
40
- try{await win.loadURL(boot.url);}catch(error){
41
- if(!(capturedCode&&(error?.code==='ERR_ABORTED'||error?.errno===-3))){await close();throw new Error('NAVIGATION_FAILED');}
42
- }
43
- send({type:'ready'});
44
- return {close};
45
- }
46
- module.exports={openWindow,isCallback};
package/lib/archive.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare function unpackZip(zipPath: string, root: string, maxBytes: number, signal?: AbortSignal): Promise<void>;