ai_co_discuss 0.4.44 → 0.4.47

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.
@@ -10,9 +10,11 @@
10
10
  * to another, unverified connection; nothing here retries on a new one.
11
11
  */
12
12
  import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
13
- import { readFileSync } from 'node:fs';
13
+ import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
14
14
  import http from 'node:http';
15
15
  import net from 'node:net';
16
+ import { homedir } from 'node:os';
17
+ import { join } from 'node:path';
16
18
  import { Readable } from 'node:stream';
17
19
 
18
20
  export const ENTRY_KEY_PATTERN = /^[0-9a-f]{64}$/;
@@ -113,6 +115,53 @@ export function entry_access() {
113
115
  return process.env[KEY_FILE_VARIABLE] ? { entry_key_file: process.env[KEY_FILE_VARIABLE] } : {};
114
116
  }
115
117
 
118
+ // The computer owner's own site is protected while hosting is on (every hosted account's processes share this loopback);
119
+ // its key then sits in the owner's service directory, which no hosted account can open.
120
+ const OWNER_KEY_FILE = join('local', 'site-key.json');
121
+
122
+ /** The owner's site key file in a service directory (it exists only while that site runs protected). */
123
+ export function owner_key_file(home) {
124
+ return join(home, OWNER_KEY_FILE);
125
+ }
126
+
127
+ /**
128
+ * Turn the owner site's protection on or off for the next start: on writes a new key file (kept if one is there), off
129
+ * removes it. Returns the key file's path when on, '' when off.
130
+ */
131
+ export function set_owner_protection(home, on) {
132
+ const path = owner_key_file(home);
133
+ if (!on) { try { unlinkSync(path); } catch { /* already off */ } return ''; }
134
+ if (!existsSync(path)) writeFileSync(path, `${JSON.stringify({ key: randomBytes(32).toString('hex') })}\n`, { mode: 0o600 });
135
+ return path;
136
+ }
137
+
138
+ /**
139
+ * The key file a request to `target` proves itself with when the caller's environment names none: the owner's own site
140
+ * key, for the owner's own port only (the owner's command line in a terminal, started outside the service).
141
+ */
142
+ function default_key_file(target) {
143
+ const home = process.env.DISCUSS_SERVICE_HOME || join(homedir(), '.codiscuss');
144
+ const path = owner_key_file(home);
145
+ if (!existsSync(path)) return '';
146
+ let port = 8765;
147
+ try { port = Number(JSON.parse(readFileSync(join(home, 'local-settings.json'), 'utf8')).port) || 8765; } catch { /* default port */ }
148
+ return Number(target.port || 80) === port ? path : '';
149
+ }
150
+
151
+ /**
152
+ * A link that opens the owner's protected site in a browser: the site turns it into a cookie (backend/entry_guard.py).
153
+ * The URL is returned unchanged when the site is not protected. A fragment is kept (browsers keep it across the redirect).
154
+ */
155
+ export function signed_site_url(url, home) {
156
+ const path = owner_key_file(home);
157
+ let key = '';
158
+ try { key = String(JSON.parse(readFileSync(path, 'utf8')).key || ''); } catch { return url; }
159
+ if (!ENTRY_KEY_PATTERN.test(key)) return url;
160
+ const target = new URL(url);
161
+ const at = String(Math.floor(Date.now() / 1000));
162
+ return `${target.origin}/_instance/open?at=${at}&sig=${entry_proof(key, 'open', at)}${target.hash}`;
163
+ }
164
+
116
165
  /** The instance key when protection is configured: '' when it is not, an error when it is but unusable. */
117
166
  function configured_key(key_file = process.env[KEY_FILE_VARIABLE]) {
118
167
  const path = key_file;
@@ -133,7 +182,7 @@ function configured_key(key_file = process.env[KEY_FILE_VARIABLE]) {
133
182
  */
134
183
  export async function site_fetch(url, init = {}, { key_file } = {}) {
135
184
  const target = new URL(url);
136
- const key = LOOPBACK_HOSTS.has(target.hostname) ? configured_key(key_file || process.env[KEY_FILE_VARIABLE]) : '';
185
+ const key = LOOPBACK_HOSTS.has(target.hostname) ? configured_key(key_file || process.env[KEY_FILE_VARIABLE] || default_key_file(target)) : '';
137
186
  if (!key) return fetch(url, init);
138
187
  const port = Number(target.port || 80);
139
188
  const { socket, header } = await verified_connection(port, key, { signal: init.signal });
@@ -165,6 +165,7 @@ if (Get-LocalUser -Name ${quote(user)} -ErrorAction SilentlyContinue) { Set-Loca
165
165
  else { New-LocalUser -Name ${quote(user)} -Password $secure -PasswordNeverExpires -UserMayNotChangePassword -Description 'AI CoDiscuss hosted account' | Out-Null }
166
166
  if (-not (Get-LocalGroupMember -Group 'Users' -Member ${quote(user)} -ErrorAction SilentlyContinue)) { Add-LocalGroupMember -Group 'Users' -Member ${quote(user)} }
167
167
  icacls ${quote(account_folder)} /grant ${quote(`${user}:(OI)(CI)M`)} /T /C /Q | Out-Null
168
+ ${register_task_script(account, user, '$secure', owner_sid({ run }))}
168
169
  'ok'`, { elevated: true });
169
170
  write_os_users(data, { ...read_os_users(data), [account]: { user, secret: protect(password) } });
170
171
  return { user };
@@ -174,7 +175,8 @@ icacls ${quote(account_folder)} /grant ${quote(`${user}:(OI)(CI)M`)} /T /C /Q |
174
175
  export function remove_os_user(data, account, { run = run_powershell } = {}) {
175
176
  const record = read_os_users(data)[account];
176
177
  if (!record) throw new Error(`账号 ${account} 没有 Windows 用户`);
177
- run(`$user = Get-LocalUser -Name ${quote(record.user)} -ErrorAction SilentlyContinue
178
+ run(`Unregister-ScheduledTask -TaskName ${quote(task_name(account))} -Confirm:$false -ErrorAction SilentlyContinue
179
+ $user = Get-LocalUser -Name ${quote(record.user)} -ErrorAction SilentlyContinue
178
180
  if ($user) {
179
181
  Get-CimInstance Win32_UserProfile | Where-Object SID -eq $user.SID.Value | Remove-CimInstance
180
182
  Remove-LocalUser -Name ${quote(record.user)}
@@ -239,8 +241,9 @@ $process = Start-Process ${POWERSHELL} -Credential $credential -LoadUserProfile
239
241
  ${wait ? `if (-not $process.WaitForExit(${timeout})) { $process.Kill(); throw '运行超时' }` : ''}
240
242
  $process.Id`;
241
243
  try {
242
- run(start, { timeout: timeout + 10_000 });
243
- if (!wait) return { folder, output };
244
+ const started = run(start, { timeout: timeout + 10_000 });
245
+ // Not waiting: the started process's id comes back too (the last line the start printed).
246
+ if (!wait) return { folder, output, pid: Number(String(started).trim().split(/\s+/).pop()) || 0 };
244
247
  return existsSync(output) ? read_output(output).trim() : '';
245
248
  } finally {
246
249
  // A program the script started may still hold the folder; the job's result does not depend on removing it.
@@ -338,6 +341,17 @@ export function instance_key_file(account, root = SHARED_ROOT) {
338
341
  */
339
342
  export function place_instance_key(data, account, key, { root = SHARED_ROOT, run = run_powershell } = {}) {
340
343
  if (!/^[0-9a-f]{64}$/.test(String(key))) throw new Error('实例密钥格式不对');
344
+ return place_account_file(data, account, KEY_FILE, `${JSON.stringify({ key })}\n`, { root, run });
345
+ }
346
+
347
+ /**
348
+ * Write one file into the account's folder of the shared folder, which only the owner can change and only the account's
349
+ * Windows user (if any) can read: the folder and every level above are secured and checked first.
350
+ *
351
+ * Returns:
352
+ * The file's path.
353
+ */
354
+ function place_account_file(data, account, file_name, text, { root = SHARED_ROOT, run = run_powershell } = {}) {
341
355
  // Each level is secured and checked in turn: the shared folder, the keys folder, then the account's own.
342
356
  secure_shared_root({ root, run });
343
357
  secure_folder(join(root, 'keys'), [`(New-Object Security.Principal.SecurityIdentifier('${USERS_SID}'))`], { run });
@@ -345,16 +359,16 @@ export function place_instance_key(data, account, key, { root = SHARED_ROOT, run
345
359
  const folder = join(root, 'keys', account);
346
360
  secure_folder(folder, user ? [`(New-Object Security.Principal.NTAccount(${quote(user)}))`] : [], { run });
347
361
  // A new file of its own (never one that was already there, which could carry its own grants), then only the folder's
348
- // inherited rights on the final key, checked.
349
- const path = join(folder, KEY_FILE), draft = join(folder, `${randomBytes(12).toString('hex')}.tmp`);
350
- writeFileSync(draft, `${JSON.stringify({ key })}\n`, { flag: 'wx' });
362
+ // inherited rights on the final file, checked.
363
+ const path = join(folder, file_name), draft = join(folder, `${randomBytes(12).toString('hex')}.tmp`);
364
+ writeFileSync(draft, text, { flag: 'wx' });
351
365
  renameSync(draft, path);
352
366
  run(`$file = ${quote(path)}
353
367
  & icacls $file /reset /Q | Out-Null
354
- if ($LASTEXITCODE -ne 0) { throw "密钥文件的权限没有重置成功" }
368
+ if ($LASTEXITCODE -ne 0) { throw "文件的权限没有重置成功" }
355
369
  $read = Get-Acl -LiteralPath $file
356
- if ($read.AreAccessRulesProtected) { throw "密钥文件没有沿用所在目录的权限" }
357
- foreach ($rule in $read.Access) { if (-not $rule.IsInherited) { throw "密钥文件带有单独的授权:$($rule.IdentityReference)" } }
370
+ if ($read.AreAccessRulesProtected) { throw "文件没有沿用所在目录的权限" }
371
+ foreach ($rule in $read.Access) { if (-not $rule.IsInherited) { throw "文件带有单独的授权:$($rule.IdentityReference)" } }
358
372
  'ok'`);
359
373
  return path;
360
374
  }
@@ -380,8 +394,10 @@ function copy_over(source, target, filter) {
380
394
  * Returns:
381
395
  * { installed: [label], missing: [label], warnings: [text] }.
382
396
  */
383
- export function install_shared_runtime(python_source = '') {
397
+ export function install_shared_runtime(python_source = '', { run = run_powershell } = {}) {
384
398
  const installed = [], missing = [], warnings = [];
399
+ // Secured before anything is copied in: a file another user put there first would stay theirs.
400
+ secure_shared_root({ run });
385
401
  for (const cli of Object.values(cli_sources())) {
386
402
  if (!existsSync(cli.source)) { missing.push(cli.label); continue; }
387
403
  mkdirSync(dirname(cli.target), { recursive: true });
@@ -407,16 +423,81 @@ export function shared_cli_state() {
407
423
  app: existsSync(paths.local_script), python: existsSync(paths.python), app_version };
408
424
  }
409
425
 
426
+ // ---- The instance of an account with its own Windows user: a scheduled task ----
427
+ //
428
+ // The instance runs as a scheduled task of the account's Windows user that runs whether or not anyone is signed in: it
429
+ // is then in a session of its own with no desktop, out of reach of the owner's windows, keyboard and clipboard (a
430
+ // program started with the user's credentials on the owner's desktop would share them), and it comes back when the
431
+ // computer starts. The task runs START_SCRIPT from the account's folder of the shared folder, which only the owner can
432
+ // change; it starts the instance only while RUN_FLAG is there (the owner's start puts it, the owner's stop removes it),
433
+ // so an instance the owner stopped stays stopped after a restart.
434
+
435
+ const START_SCRIPT = 'start-instance.ps1';
436
+ const RUN_FLAG = 'run.flag';
437
+ const TASK_PREFIX = 'CoDiscuss instance ';
438
+
439
+ /** The scheduled task of one account's instance. */
440
+ export function task_name(account) {
441
+ return `${TASK_PREFIX}${account}`;
442
+ }
443
+
444
+ let cached_owner_sid = '';
445
+
446
+ /** The owner's own security identifier (granted by the elevated scripts, even when another administrator elevates). */
447
+ function owner_sid({ run = run_powershell } = {}) {
448
+ if (!cached_owner_sid) cached_owner_sid = run('[Security.Principal.WindowsIdentity]::GetCurrent().User.Value');
449
+ return cached_owner_sid;
450
+ }
451
+
410
452
  /**
411
- * Start one account's instance as its Windows user, in the background.
412
- *
413
- * The instance supervisor runs with the account's service directory; it keeps running after this returns.
453
+ * PowerShell, run elevated, that (re)registers the account's instance task as `user` with the SecureString in
454
+ * `password_variable`, and lets the owner (`sid`) start it without elevation.
414
455
  */
415
- export function start_instance_as_user(data, account, service_home, local_script, node = process.execPath, options = {}) {
416
- const { key_file = '', ...rest } = options;
417
- // The instance keeps running in its own folder rather than in the job folder, which is removed afterwards. A protected
418
- // instance, and every member it starts, gets the key file it proves itself with.
419
- run_as_user(data, account, `$env:DISCUSS_SERVICE_HOME = ${quote(service_home)}
420
- ${key_file ? `$env:DISCUSS_ENTRY_KEY_FILE = ${quote(key_file)}\n` : ''}Set-Location ${quote(service_home)}
421
- & ${quote(node)} ${quote(local_script)} start --json`, { ...rest, timeout: 90_000 });
456
+ function register_task_script(account, user, password_variable, sid) {
457
+ const script = join(SHARED_ROOT, 'keys', account, START_SCRIPT);
458
+ return `$action = New-ScheduledTaskAction -Execute ${quote(POWERSHELL)} -Argument ${quote(`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "${script}"`)}
459
+ $trigger = New-ScheduledTaskTrigger -AtStartup
460
+ $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable
461
+ $plain = [Runtime.InteropServices.Marshal]::PtrToStringBSTR([Runtime.InteropServices.Marshal]::SecureStringToBSTR(${password_variable}))
462
+ Register-ScheduledTask -TaskName ${quote(task_name(account))} -Action $action -Trigger $trigger -Settings $settings -User ${quote(user)} -Password $plain -RunLevel Limited -Force | Out-Null
463
+ $service = New-Object -ComObject Schedule.Service
464
+ $service.Connect()
465
+ $task = $service.GetFolder('\').GetTask(${quote(task_name(account))})
466
+ $task.SetSecurityDescriptor($task.GetSecurityDescriptor(4) + '(A;;GRGX;;;${sid})', 0)`;
467
+ }
468
+
469
+ /** Register the instance task of an account isolated before instances ran as tasks (one elevation prompt). */
470
+ function register_instance_task(data, account, { run = run_powershell } = {}) {
471
+ const record = read_os_users(data)[account];
472
+ run(`$secure = ConvertTo-SecureString ${quote(record.secret)}
473
+ ${register_task_script(account, record.user, '$secure', owner_sid({ run }))}
474
+ 'ok'`, { elevated: true });
475
+ }
476
+
477
+ /**
478
+ * Start one account's instance as its Windows user, in the background: write its start script and run flag, then start
479
+ * its task. The instance keeps running after this returns; a protected instance, and every member it starts, gets the
480
+ * key file it proves itself with.
481
+ */
482
+ export function start_instance_as_user(data, account, service_home, local_script, node = process.execPath, { key_file = '', run = run_powershell } = {}) {
483
+ const record = read_os_users(data)[account];
484
+ if (!record) throw new Error(`账号 ${account} 还没有 Windows 用户,请先隔离这个账号`);
485
+ place_account_file(data, account, START_SCRIPT, `$flag = ${quote(join(SHARED_ROOT, 'keys', account, RUN_FLAG))}
486
+ if (-not (Test-Path -LiteralPath $flag)) { exit 0 }
487
+ $env:DISCUSS_SERVICE_HOME = ${quote(service_home)}
488
+ ${key_file ? `$env:DISCUSS_ENTRY_KEY_FILE = ${quote(key_file)}\n` : ''}Set-Location -LiteralPath ${quote(service_home)}
489
+ & ${quote(node)} ${quote(local_script)} run
490
+ exit $LASTEXITCODE
491
+ `, { run });
492
+ writeFileSync(join(SHARED_ROOT, 'keys', account, RUN_FLAG), `${Date.now()}\n`);
493
+ const name = quote(task_name(account));
494
+ const found = run(`if (Get-ScheduledTask -TaskName ${name} -ErrorAction SilentlyContinue) { 'yes' } else { 'no' }`);
495
+ if (found !== 'yes') register_instance_task(data, account, { run });
496
+ run(`Start-ScheduledTask -TaskName ${name}
497
+ 'ok'`);
498
+ }
499
+
500
+ /** Keep a stopped instance stopped when the computer starts again (its supervisor is stopped separately). */
501
+ export function clear_instance_flag(account) {
502
+ rmSync(join(SHARED_ROOT, 'keys', account, RUN_FLAG), { force: true });
422
503
  }
@@ -12,7 +12,8 @@ import { dirname, join, normalize, relative, sep } from 'node:path';
12
12
 
13
13
  const LIBRARY = 'skill-library';
14
14
  const PROMPT_FILE = 'hosted-system-prompt.md';
15
- const SKILL_NAME = /^[\w.-]{1,64}$/;
15
+ // Starts with a letter, digit or underscore: "." and ".." would name the folder above when joined and removed.
16
+ const SKILL_NAME = /^\w[\w.-]{0,63}$/;
16
17
  const MAX_FILES = 2000;
17
18
  // What a hosted account's AI starts with; the owner's own rules are personal and are not given out. How to work in a room
18
19
  // is the skills' business, so this holds only what no skill covers: the language, and this account's boundaries.