claude-guest 0.1.0 → 0.3.0
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 +73 -37
- package/index.js +475 -161
- package/mac/probe.sh +47 -0
- package/mac/setup.sh +340 -0
- package/mac.sh +53 -0
- package/package.json +6 -2
- package/server/verify.sh +4 -3
- package/ui.js +200 -0
- package/win/setup.ps1 +30 -32
- package/win.txt +7 -1
package/ui.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Оформление в терминале: шапка, панель этапов с галочками и общей полосой, рамка итога.
|
|
3
|
+
// Цвета - из брендбука канала: акцент #FF1861, светлый #E3E1D8, приглушённый #80847D, «готово» #2FD27A.
|
|
4
|
+
|
|
5
|
+
const TTY = !!process.stdout.isTTY;
|
|
6
|
+
const WIN = process.platform === 'win32';
|
|
7
|
+
// Windows Terminal и терминал VS Code рисуют любые символы и 24-битный цвет. Старая консоль Windows
|
|
8
|
+
// со шрифтом Consolas - не все: галочку и скруглённые углы заменяем на то, что в ней точно есть.
|
|
9
|
+
const FANCY = !WIN || !!process.env.WT_SESSION || process.env.TERM_PROGRAM === 'vscode';
|
|
10
|
+
const TRUECOLOR = FANCY || process.env.COLORTERM === 'truecolor';
|
|
11
|
+
const PLAIN = !TTY || !!process.env.NO_COLOR;
|
|
12
|
+
|
|
13
|
+
const rgb = hex => { const n = parseInt(hex.slice(1), 16); return `${n >> 16};${(n >> 8) & 255};${n & 255}`; };
|
|
14
|
+
const paint = (hex, basic) => s => (PLAIN ? String(s) : TRUECOLOR ? `\x1b[38;2;${rgb(hex)}m${s}\x1b[39m` : `\x1b[${basic}m${s}\x1b[39m`);
|
|
15
|
+
const C = {
|
|
16
|
+
acc: paint('#FF1861', 35),
|
|
17
|
+
ok: paint('#2FD27A', 32),
|
|
18
|
+
warn: paint('#FFB020', 33),
|
|
19
|
+
err: paint('#FF4D4D', 31),
|
|
20
|
+
light: paint('#E3E1D8', 37),
|
|
21
|
+
muted: paint('#80847D', 90),
|
|
22
|
+
b: s => (PLAIN ? String(s) : `\x1b[1m${s}\x1b[22m`),
|
|
23
|
+
dim: s => (PLAIN ? String(s) : `\x1b[2m${s}\x1b[22m`)
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const G = FANCY
|
|
27
|
+
? { ok: '✓', fail: '✗', warn: '!', wait: '○', skip: '-', spin: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],
|
|
28
|
+
full: '█', part: ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉'], empty: '░',
|
|
29
|
+
tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│', sub: '└', arrow: '⇄', dot: '·' }
|
|
30
|
+
: { ok: '√', fail: 'x', warn: '!', wait: '·', skip: '-', spin: ['|', '/', '-', '\\'],
|
|
31
|
+
full: '█', part: [''], empty: '░',
|
|
32
|
+
tl: '┌', tr: '┐', bl: '└', br: '┘', h: '─', v: '│', sub: '└', arrow: '<->', dot: '·' };
|
|
33
|
+
|
|
34
|
+
const strip = s => String(s).replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '');
|
|
35
|
+
const vlen = s => strip(s).length;
|
|
36
|
+
const padEnd = (s, w) => s + ' '.repeat(Math.max(0, w - vlen(s)));
|
|
37
|
+
const cut = (s, w) => (s.length > w ? s.slice(0, Math.max(0, w - 1)) + '…' : s);
|
|
38
|
+
const cols = () => Math.max(40, (process.stdout.columns || 80) - 1);
|
|
39
|
+
const mmss = ms => { const s = Math.floor(ms / 1000); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; };
|
|
40
|
+
|
|
41
|
+
// Перенос по словам с отступом: длинная строка не рвётся посреди слова краем окна.
|
|
42
|
+
function wrap(text, indent = 4, width = Math.min(cols(), 100)) {
|
|
43
|
+
const w = Math.max(20, width - indent), out = [];
|
|
44
|
+
let line = '';
|
|
45
|
+
for (const word of String(text).split(/\s+/)) {
|
|
46
|
+
if (line && vlen(line) + 1 + vlen(word) > w) { out.push(line); line = word; } else line = line ? line + ' ' + word : word;
|
|
47
|
+
}
|
|
48
|
+
if (line) out.push(line);
|
|
49
|
+
return out.map((l, i) => ' '.repeat(indent) + l);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function bar(frac, w, color = C.acc) {
|
|
53
|
+
const f = Math.max(0, Math.min(1, frac)) * w;
|
|
54
|
+
const full = Math.floor(f);
|
|
55
|
+
const part = G.part.length > 1 && full < w ? G.part[Math.floor((f - full) * G.part.length)] : '';
|
|
56
|
+
const empty = w - full - (part ? 1 : 0);
|
|
57
|
+
return color(G.full.repeat(full) + part) + C.muted(G.empty.repeat(Math.max(0, empty)));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Рамка вокруг уже раскрашенных строк.
|
|
61
|
+
function box(lines, { color = C.acc, minWidth = 40 } = {}) {
|
|
62
|
+
const inner = Math.min(cols() - 6, Math.max(minWidth, ...lines.map(vlen)));
|
|
63
|
+
const out = [' ' + color(G.tl + G.h.repeat(inner + 2) + G.tr)];
|
|
64
|
+
for (const l of lines) out.push(' ' + color(G.v) + ' ' + padEnd(l, inner) + ' ' + color(G.v));
|
|
65
|
+
out.push(' ' + color(G.bl + G.h.repeat(inner + 2) + G.br));
|
|
66
|
+
return out.join('\n');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function banner(version, subtitle, machine = 'этот ПК') {
|
|
70
|
+
console.log('');
|
|
71
|
+
console.log(box([
|
|
72
|
+
'',
|
|
73
|
+
C.b(C.light('Claude в гостях')) + ' ' + C.muted(`версия ${version}`),
|
|
74
|
+
C.muted('ваш сервер ') + C.acc(G.arrow) + C.muted(' ' + machine),
|
|
75
|
+
''
|
|
76
|
+
], { minWidth: 44 }));
|
|
77
|
+
if (subtitle) subtitle.split('\n').forEach(l => console.log(' ' + C.muted(l)));
|
|
78
|
+
console.log('');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Панель этапов: все этапы видны сразу, идущий крутится с секундомером и строкой «что сейчас»,
|
|
82
|
+
// закончившиеся получают галочку и своё время. Внизу общая полоса.
|
|
83
|
+
// Без терминала (вывод в файл) - просто строки «→ этап» и «✓ этап».
|
|
84
|
+
class Board {
|
|
85
|
+
constructor(rows) {
|
|
86
|
+
this.rows = rows.map(r => ({ weight: 1, tau: 15000, state: 'wait', note: '', detail: '', ...r }));
|
|
87
|
+
this.height = 0;
|
|
88
|
+
this.timer = null;
|
|
89
|
+
this.t0 = 0;
|
|
90
|
+
this.paused = false;
|
|
91
|
+
this.done_ = false;
|
|
92
|
+
}
|
|
93
|
+
get(id) { return this.rows.find(r => r.id === id); }
|
|
94
|
+
// Этап, о котором заранее не знали, - вставляем перед указанным.
|
|
95
|
+
ensure(id, title, before, extra = {}) {
|
|
96
|
+
if (this.get(id)) return this.get(id);
|
|
97
|
+
const row = { id, title, weight: 1, tau: 15000, state: 'wait', note: '', detail: '', ...extra };
|
|
98
|
+
const i = before ? this.rows.findIndex(r => r.id === before) : -1;
|
|
99
|
+
if (i >= 0) this.rows.splice(i, 0, row); else this.rows.push(row);
|
|
100
|
+
return row;
|
|
101
|
+
}
|
|
102
|
+
begin() {
|
|
103
|
+
this.t0 = Date.now();
|
|
104
|
+
if (!TTY) return;
|
|
105
|
+
process.stdout.write('\x1b[?25l');
|
|
106
|
+
this.draw();
|
|
107
|
+
this.timer = setInterval(() => this.draw(), 90);
|
|
108
|
+
}
|
|
109
|
+
start(id, note = '') {
|
|
110
|
+
const r = this.get(id);
|
|
111
|
+
if (!r || r.state === 'run') return;
|
|
112
|
+
r.state = 'run'; r.t0 = Date.now(); r.note = note;
|
|
113
|
+
if (!TTY) console.log(' → ' + r.title);
|
|
114
|
+
this.draw();
|
|
115
|
+
}
|
|
116
|
+
note(id, text) { const r = this.get(id); if (r) { r.note = text; if (!TTY && text) console.log(' ' + text); } }
|
|
117
|
+
done(id, state = 'ok', detail = '') {
|
|
118
|
+
const r = this.get(id);
|
|
119
|
+
if (!r || ['ok', 'warn', 'fail', 'skip'].includes(r.state)) return;
|
|
120
|
+
if (!r.t0) r.t0 = Date.now();
|
|
121
|
+
r.state = state; r.t1 = Date.now(); r.note = ''; r.detail = detail;
|
|
122
|
+
if (!TTY) console.log(` ${{ ok: G.ok, warn: G.warn, fail: G.fail, skip: G.skip }[state]} ${r.title}${detail ? ' ' + detail : ''}`);
|
|
123
|
+
this.draw();
|
|
124
|
+
}
|
|
125
|
+
skip(id, detail = '') { this.done(id, 'skip', detail); }
|
|
126
|
+
running() { return this.rows.find(r => r.state === 'run'); }
|
|
127
|
+
frac() {
|
|
128
|
+
const total = this.rows.reduce((a, r) => a + r.weight, 0) || 1;
|
|
129
|
+
let got = 0;
|
|
130
|
+
for (const r of this.rows) {
|
|
131
|
+
if (['ok', 'warn', 'fail', 'skip'].includes(r.state)) got += r.weight;
|
|
132
|
+
else if (r.state === 'run') got += r.weight * 0.9 * (1 - Math.exp(-(Date.now() - r.t0) / r.tau));
|
|
133
|
+
}
|
|
134
|
+
return this.done_ ? 1 : Math.min(0.99, got / total);
|
|
135
|
+
}
|
|
136
|
+
render() {
|
|
137
|
+
const W = Math.min(cols() - 4, 96);
|
|
138
|
+
const tw = Math.max(...this.rows.map(r => r.title.length)) + 2;
|
|
139
|
+
const spin = G.spin[Math.floor(Date.now() / 90) % G.spin.length];
|
|
140
|
+
const lines = [];
|
|
141
|
+
for (const r of this.rows) {
|
|
142
|
+
const icon = { wait: C.muted(G.wait), run: C.acc(spin), ok: C.ok(G.ok), warn: C.warn(G.warn), fail: C.err(G.fail), skip: C.muted(G.skip) }[r.state];
|
|
143
|
+
const t = r.state === 'run' ? mmss(Date.now() - r.t0) : r.t1 ? mmss(r.t1 - r.t0) : '';
|
|
144
|
+
const title = cut(r.title, W - 12);
|
|
145
|
+
const ttl = r.state === 'wait' || r.state === 'skip' ? C.muted(title) : r.state === 'run' ? C.b(C.light(title)) : C.light(title);
|
|
146
|
+
let line = ` ${icon} ${padEnd(ttl, Math.min(tw, W - 10))} ${C.muted(t.padStart(5))}`;
|
|
147
|
+
if (r.detail) line += ' ' + C.muted(cut(r.detail, Math.max(0, W - vlen(line))));
|
|
148
|
+
lines.push(line);
|
|
149
|
+
if (r.state === 'run' && r.note) lines.push(' ' + C.muted(G.sub + ' ' + cut(r.note, W - 8)));
|
|
150
|
+
}
|
|
151
|
+
const f = this.frac();
|
|
152
|
+
const bw = Math.min(30, Math.max(10, W - 22));
|
|
153
|
+
lines.push('');
|
|
154
|
+
lines.push(' ' + bar(f, bw, this.done_ ? C.ok : C.acc) + ' ' + C.b(String(Math.floor(f * 100)).padStart(3) + '%')
|
|
155
|
+
+ ' ' + C.muted(mmss(Date.now() - this.t0)));
|
|
156
|
+
return lines;
|
|
157
|
+
}
|
|
158
|
+
draw() {
|
|
159
|
+
if (!TTY || this.paused) return;
|
|
160
|
+
const lines = this.render();
|
|
161
|
+
let s = this.height ? `\x1b[${this.height}A` : '';
|
|
162
|
+
for (const l of lines) s += '\r\x1b[2K' + l + '\n';
|
|
163
|
+
const extra = Math.max(0, this.height - lines.length);
|
|
164
|
+
for (let i = 0; i < extra; i++) s += '\r\x1b[2K\n';
|
|
165
|
+
if (extra) s += `\x1b[${extra}A`;
|
|
166
|
+
this.height = lines.length;
|
|
167
|
+
process.stdout.write(s);
|
|
168
|
+
}
|
|
169
|
+
// Вопрос посреди работы: панель убираем, вопрос печатается на её месте, потом панель рисуется ниже.
|
|
170
|
+
pause() {
|
|
171
|
+
if (!TTY) return;
|
|
172
|
+
clearInterval(this.timer);
|
|
173
|
+
let s = this.height ? `\x1b[${this.height}A` : '';
|
|
174
|
+
for (let i = 0; i < this.height; i++) s += '\r\x1b[2K\n';
|
|
175
|
+
if (this.height) s += `\x1b[${this.height}A`;
|
|
176
|
+
process.stdout.write(s + '\x1b[?25h');
|
|
177
|
+
this.height = 0;
|
|
178
|
+
this.paused = true;
|
|
179
|
+
}
|
|
180
|
+
resume() {
|
|
181
|
+
if (!TTY) return;
|
|
182
|
+
this.paused = false;
|
|
183
|
+
process.stdout.write('\x1b[?25l');
|
|
184
|
+
this.draw();
|
|
185
|
+
this.timer = setInterval(() => this.draw(), 90);
|
|
186
|
+
}
|
|
187
|
+
finish(ok = true) {
|
|
188
|
+
if (ok) this.done_ = true;
|
|
189
|
+
const r = this.running();
|
|
190
|
+
if (r) this.done(r.id, ok ? 'ok' : 'fail');
|
|
191
|
+
clearInterval(this.timer);
|
|
192
|
+
this.draw();
|
|
193
|
+
if (TTY) process.stdout.write('\x1b[?25h');
|
|
194
|
+
}
|
|
195
|
+
elapsed() { return Date.now() - this.t0; }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
process.on('exit', () => { if (TTY) process.stdout.write('\x1b[?25h'); }); // курсор вернётся при любом выходе
|
|
199
|
+
|
|
200
|
+
module.exports = { C, G, TTY, FANCY, Board, banner, box, bar, wrap, mmss, vlen, padEnd, strip };
|
package/win/setup.ps1
CHANGED
|
@@ -6,7 +6,12 @@
|
|
|
6
6
|
param(
|
|
7
7
|
[Parameter(Mandatory = $true)][ValidateSet('Install', 'Remove')][string]$Mode,
|
|
8
8
|
[Parameter(Mandatory = $true)][string]$ParamsFile,
|
|
9
|
-
[Parameter(Mandatory = $true)][string]$ResultFile
|
|
9
|
+
[Parameter(Mandatory = $true)][string]$ResultFile,
|
|
10
|
+
# Окно этого скрипта спрятано: ход работы он пишет строками в файл, их показывает панель index.js.
|
|
11
|
+
# STAGE <этап> начался этап (user, sshd, folders, deny / sshd, unprotect, remove)
|
|
12
|
+
# INFO <текст> что сейчас делается - строка под этапом
|
|
13
|
+
# WARN <текст> предупреждение - этап получит «!»
|
|
14
|
+
[string]$ProgressFile = ''
|
|
10
15
|
)
|
|
11
16
|
$ErrorActionPreference = 'Stop'
|
|
12
17
|
$ProgressPreference = 'SilentlyContinue'
|
|
@@ -15,9 +20,6 @@ try { $Host.UI.RawUI.WindowTitle = 'Claude в гостях - настройка
|
|
|
15
20
|
$Tag = 'claude-guest'
|
|
16
21
|
$DefaultUser = 'claude-guest'
|
|
17
22
|
$Description = 'Claude с вашего сервера (claude-guest)'
|
|
18
|
-
# Гость, которого настраивали руками до появления скрипта: скрипт убирает его и ставит своего.
|
|
19
|
-
$LegacyUser = 'render'
|
|
20
|
-
$LegacyDescription = 'Вход для сервера'
|
|
21
23
|
|
|
22
24
|
$SshDir = Join-Path $env:ProgramData 'ssh'
|
|
23
25
|
$SshdConfig = Join-Path $SshDir 'sshd_config'
|
|
@@ -34,8 +36,13 @@ $SystemDirs = @('Windows', 'Program Files', 'Program Files (x86)', 'ProgramData'
|
|
|
34
36
|
'Recovery', 'System Volume Information', 'Documents and Settings', 'Config.Msi')
|
|
35
37
|
|
|
36
38
|
$result = [ordered]@{ ok = $false; error = $null; warnings = @(); log = @() }
|
|
37
|
-
function
|
|
38
|
-
|
|
39
|
+
function Report([string]$line) {
|
|
40
|
+
if (-not $ProgressFile) { return }
|
|
41
|
+
try { [IO.File]::AppendAllText($ProgressFile, $line + "`n", (New-Object Text.UTF8Encoding($false))) } catch { }
|
|
42
|
+
}
|
|
43
|
+
function Stage([string]$id) { Report "STAGE $id" }
|
|
44
|
+
function Say([string]$t) { Write-Host " $t"; $script:result.log += $t; Report "INFO $t" }
|
|
45
|
+
function Warn([string]$t) { Write-Host " ! $t" -ForegroundColor Yellow; $script:result.warnings += $t; Report "WARN $t" }
|
|
39
46
|
function Save-Result { $script:result | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $ResultFile -Encoding UTF8 }
|
|
40
47
|
function Write-NoBom([string]$path, [string[]]$lines) {
|
|
41
48
|
# sshd не понимает метку BOM в начале файла, а Set-Content -Encoding UTF8 в PowerShell 5.1 её ставит.
|
|
@@ -70,7 +77,7 @@ function Read-State {
|
|
|
70
77
|
function Norm([string]$p) { if (-not $p) { return '' }; return $p.TrimEnd('\').ToLowerInvariant() }
|
|
71
78
|
# Из sshd_config убираем свои блоки и строки, которые раньше вписывали руками (до первого Match).
|
|
72
79
|
function Get-CleanSshdConfig([string[]]$lines, [string]$user) {
|
|
73
|
-
$hand = @('ListenAddress 127.0.0.1', "AllowUsers $user",
|
|
80
|
+
$hand = @('ListenAddress 127.0.0.1', "AllowUsers $user", 'PasswordAuthentication no',
|
|
74
81
|
'KbdInteractiveAuthentication no', 'AllowTcpForwarding no')
|
|
75
82
|
$out = New-Object System.Collections.Generic.List[string]
|
|
76
83
|
$skip = $false; $inMatch = $false
|
|
@@ -88,8 +95,9 @@ function Get-CleanSshdConfig([string[]]$lines, [string]$user) {
|
|
|
88
95
|
}
|
|
89
96
|
|
|
90
97
|
# Убрать гостя: сначала его записи в правах (пока Windows знает его имя), потом процессы, профиль, учётную запись.
|
|
91
|
-
function Remove-Guest([string]$user, [string[]]$extra) {
|
|
98
|
+
function Remove-Guest([string]$user, [string[]]$extra, [bool]$stages = $false) {
|
|
92
99
|
$sid = Get-Sid $user
|
|
100
|
+
if ($stages) { Stage 'unprotect' }
|
|
93
101
|
if ($sid) {
|
|
94
102
|
$paths = New-Object System.Collections.Generic.List[string]
|
|
95
103
|
foreach ($x in @($extra)) { if ($x) { $paths.Add([string]$x) } }
|
|
@@ -110,6 +118,7 @@ function Remove-Guest([string]$user, [string[]]$extra) {
|
|
|
110
118
|
if ((Invoke-Icacls @($t, '/remove', "*$sid", '/C', '/Q')) -ne 0) { Warn "С части файлов в $t права $user снять не удалось." }
|
|
111
119
|
}
|
|
112
120
|
}
|
|
121
|
+
if ($stages) { Stage 'remove' }
|
|
113
122
|
if (Get-LocalUser -Name $user -ErrorAction SilentlyContinue) {
|
|
114
123
|
Say "Удаляю пользователя $user"
|
|
115
124
|
Get-Process -IncludeUserName -ErrorAction SilentlyContinue | Where-Object { $_.UserName -like "*\$user" } | Stop-Process -Force -ErrorAction SilentlyContinue
|
|
@@ -129,23 +138,7 @@ function Install {
|
|
|
129
138
|
# --- 1. Пользователь-гость: обычный, не администратор, скрыт с экрана входа ---
|
|
130
139
|
$user = $DefaultUser
|
|
131
140
|
if ($state -and $state.user) { $user = [string]$state.user }
|
|
132
|
-
|
|
133
|
-
$result.legacyFolders = @()
|
|
134
|
-
if (-not $state -and $legacy -and $legacy.Description -eq $LegacyDescription) {
|
|
135
|
-
# SSH-сервер ставили руками ради этой же связки - запоминаем до того, как строки render уйдут из настроек.
|
|
136
|
-
if ((Test-Path -LiteralPath $SshdConfig) -and (((Read-Lines $SshdConfig) -join "`n") -match "(?m)^\s*AllowUsers\s+$LegacyUser\s*$")) {
|
|
137
|
-
$script:legacySshd = $true
|
|
138
|
-
}
|
|
139
|
-
Say "Убираю гостя $LegacyUser, настроенного вручную: дальше вместо него $user"
|
|
140
|
-
$folders = @()
|
|
141
|
-
foreach ($d in @(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3')) {
|
|
142
|
-
$c = Join-Path ($d.DeviceID + '\') $LegacyUser
|
|
143
|
-
if (Test-Path -LiteralPath $c) { $folders += $c }
|
|
144
|
-
}
|
|
145
|
-
Remove-Guest $LegacyUser $folders
|
|
146
|
-
$result.legacyFolders = @($folders)
|
|
147
|
-
}
|
|
148
|
-
|
|
141
|
+
Stage 'user'
|
|
149
142
|
$sec = ConvertTo-SecureString $p.password -AsPlainText -Force
|
|
150
143
|
$existing = Get-LocalUser -Name $user -ErrorAction SilentlyContinue
|
|
151
144
|
if ($existing) {
|
|
@@ -171,6 +164,7 @@ function Install {
|
|
|
171
164
|
Warn "Пользователь $user был администратором - права администратора сняты."
|
|
172
165
|
}
|
|
173
166
|
} catch { Warn 'Не удалось проверить состав группы «Администраторы»: Windows не показала её участников.' }
|
|
167
|
+
Say "Скрываю $user с экрана входа"
|
|
174
168
|
if (-not (Test-Path $UserList)) { New-Item -Path $UserList -Force | Out-Null }
|
|
175
169
|
New-ItemProperty -Path $UserList -Name $user -Value 0 -PropertyType DWord -Force | Out-Null
|
|
176
170
|
|
|
@@ -188,6 +182,7 @@ public static extern int CreateProfile(string sid, string name, System.Text.Stri
|
|
|
188
182
|
try { $profilePath = (Get-CimInstance Win32_UserProfile -Filter "SID='$sid'").LocalPath } catch { }
|
|
189
183
|
|
|
190
184
|
# --- 2. SSH-сервер Windows: только 127.0.0.1, только ключ, только гость ---
|
|
185
|
+
Stage 'sshd'
|
|
191
186
|
$svc = Get-Service -Name sshd -ErrorAction SilentlyContinue
|
|
192
187
|
$installedByUs = $false
|
|
193
188
|
if ($state) { $installedByUs = [bool]$state.installedSshd }
|
|
@@ -202,7 +197,6 @@ public static extern int CreateProfile(string sid, string name, System.Text.Stri
|
|
|
202
197
|
$installedByUs = $true
|
|
203
198
|
} elseif (-not $state) {
|
|
204
199
|
$wasStart = [string]$svc.StartType
|
|
205
|
-
if ($script:legacySshd) { $installedByUs = $true }
|
|
206
200
|
}
|
|
207
201
|
# Правило брандмауэра Windows создаёт открытым - закрываем до первого запуска службы.
|
|
208
202
|
Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue | Disable-NetFirewallRule
|
|
@@ -212,6 +206,7 @@ public static extern int CreateProfile(string sid, string name, System.Text.Stri
|
|
|
212
206
|
Start-Sleep -Seconds 3
|
|
213
207
|
Stop-Service -Name sshd -Force
|
|
214
208
|
}
|
|
209
|
+
Say 'Настраиваю: только этот ПК, только ключ, только гость'
|
|
215
210
|
$backup = "$SshdConfig.bak-$Tag"
|
|
216
211
|
$clean = Get-CleanSshdConfig (Read-Lines $SshdConfig) $user
|
|
217
212
|
if (-not (Test-Path -LiteralPath $backup)) { Write-NoBom $backup $clean }
|
|
@@ -240,6 +235,7 @@ public static extern int CreateProfile(string sid, string name, System.Text.Stri
|
|
|
240
235
|
if ((Test-Path -LiteralPath $old) -and ((Get-Content -LiteralPath $old -Raw) -match 'from="127\.0\.0\.1",restrict')) { Remove-Item -LiteralPath $old -Force }
|
|
241
236
|
}
|
|
242
237
|
|
|
238
|
+
Say 'Запускаю и проверяю, что SSH-сервер не виден из сети'
|
|
243
239
|
Set-Service -Name sshd -StartupType Automatic
|
|
244
240
|
if ((Get-Service -Name sshd).Status -eq 'Running') { Restart-Service -Name sshd -Force } else { Start-Service -Name sshd }
|
|
245
241
|
Start-Sleep -Seconds 2
|
|
@@ -254,6 +250,7 @@ public static extern int CreateProfile(string sid, string name, System.Text.Stri
|
|
|
254
250
|
$result.sshPort = [int]$listen[0].LocalPort
|
|
255
251
|
|
|
256
252
|
# --- 3. Папка Claude на диске, где больше всего места: inbox - только чтение, work - работа ---
|
|
253
|
+
Stage 'folders'
|
|
257
254
|
# Имена латиницей: в этих папках Claude запускает программы, а часть из них ломается на кириллице.
|
|
258
255
|
$drives = @(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3')
|
|
259
256
|
$sys = $env:SystemDrive
|
|
@@ -265,6 +262,7 @@ public static extern int CreateProfile(string sid, string name, System.Text.Stri
|
|
|
265
262
|
}
|
|
266
263
|
$inbox = Join-Path $base 'inbox'
|
|
267
264
|
$work = Join-Path $base 'work'
|
|
265
|
+
Say "Создаю $inbox и $work"
|
|
268
266
|
foreach ($x in @($base, $inbox, $work)) { New-Item -ItemType Directory -Force -Path $x | Out-Null }
|
|
269
267
|
# Сама папка Claude: гость видит её список, а во всё, что в ней лежит, кроме inbox и work, не заходит.
|
|
270
268
|
# Разрешения, выданные прямо на inbox и work, сильнее запрета, унаследованного от папки Claude.
|
|
@@ -293,6 +291,7 @@ public static extern int CreateProfile(string sid, string name, System.Text.Stri
|
|
|
293
291
|
# Запрет ставится «только для вложенного» (IO): сам корень гость видит, но внутрь не попадает.
|
|
294
292
|
# Корень не закрываем совсем: Node.js проверяет каждую папку пути и без этого не запустится из рабочей папки.
|
|
295
293
|
# Разрешение, выданное на рабочую папку напрямую, сильнее унаследованного запрета - поэтому она работает.
|
|
294
|
+
Stage 'deny'
|
|
296
295
|
$exempt = @((Norm $base)) + @($sources | ForEach-Object { Norm $_ })
|
|
297
296
|
$denied = New-Object System.Collections.Generic.List[string]
|
|
298
297
|
$nonNtfs = New-Object System.Collections.Generic.List[string]
|
|
@@ -310,7 +309,7 @@ public static extern int CreateProfile(string sid, string name, System.Text.Stri
|
|
|
310
309
|
foreach ($t in $targets) {
|
|
311
310
|
if ($exempt -contains (Norm $t)) { continue }
|
|
312
311
|
if (Test-OwnAce $t $sid $true) { $denied.Add($t); continue }
|
|
313
|
-
if ($t -eq $root) { Say "Закрываю диск $($d.DeviceID) - Windows
|
|
312
|
+
if ($t -eq $root) { Say "Закрываю диск $($d.DeviceID) - Windows проставляет запрет на каждый файл, это минуты" }
|
|
314
313
|
else { Say "Закрываю $t" }
|
|
315
314
|
$rc = Invoke-Icacls @($t, '/deny', "*${sid}:(OI)(CI)(IO)F", '/C', '/Q')
|
|
316
315
|
# В папках из корня C: гостю не показываем даже имена файлов.
|
|
@@ -340,14 +339,13 @@ function Remove {
|
|
|
340
339
|
$user = $null
|
|
341
340
|
if ($state -and $state.user) { $user = [string]$state.user }
|
|
342
341
|
else {
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
if ($lu -and ($lu.Description -eq $Description -or $lu.Description -eq $LegacyDescription)) { $user = $u; break }
|
|
346
|
-
}
|
|
342
|
+
$lu = Get-LocalUser -Name $DefaultUser -ErrorAction SilentlyContinue
|
|
343
|
+
if ($lu -and $lu.Description -eq $Description) { $user = $DefaultUser }
|
|
347
344
|
}
|
|
348
345
|
$result.user = $user
|
|
349
346
|
|
|
350
347
|
# SSH-сервер: свои строки убираем; если ставили его мы - выключаем, если стоял до нас - возвращаем как было.
|
|
348
|
+
Stage 'sshd'
|
|
351
349
|
$svc = Get-Service -Name sshd -ErrorAction SilentlyContinue
|
|
352
350
|
if ($svc) {
|
|
353
351
|
if (Test-Path -LiteralPath $SshdConfig) {
|
|
@@ -374,7 +372,7 @@ function Remove {
|
|
|
374
372
|
if ($user) {
|
|
375
373
|
$extra = @()
|
|
376
374
|
if ($state) { $extra = @($state.denied) + @($state.sources) + @($state.base) + @($state.inbox) + @($state.work) }
|
|
377
|
-
Remove-Guest $user $extra
|
|
375
|
+
Remove-Guest $user $extra $true
|
|
378
376
|
}
|
|
379
377
|
if ($state -and $state.base -and (Test-Path -LiteralPath $state.base)) { $result.base = [string]$state.base }
|
|
380
378
|
if (Test-Path -LiteralPath $StateDir) { Remove-Item -LiteralPath $StateDir -Recurse -Force }
|
package/win.txt
CHANGED
|
@@ -19,6 +19,10 @@
|
|
|
19
19
|
$tag = 'latest'
|
|
20
20
|
if ($GuestTag) { $tag = $GuestTag }
|
|
21
21
|
|
|
22
|
+
Write-Host ''
|
|
23
|
+
Write-Host ' Claude в гостях' -ForegroundColor Magenta -NoNewline
|
|
24
|
+
Write-Host ' подготовка к запуску' -ForegroundColor DarkGray
|
|
25
|
+
|
|
22
26
|
try {
|
|
23
27
|
$npx = $null
|
|
24
28
|
$node = Get-Command node.exe -ErrorAction SilentlyContinue
|
|
@@ -37,7 +41,7 @@
|
|
|
37
41
|
$hash = $Matches[1]; $file = $Matches[2]; $name = $file -replace '\.zip$', ''
|
|
38
42
|
$dir = Join-Path $root $name
|
|
39
43
|
if (-not (Test-Path (Join-Path $dir 'node.exe'))) {
|
|
40
|
-
Write-Host "
|
|
44
|
+
Write-Host " · скачиваю Node.js ($name) - он нужен только для запуска, ставится в папку пользователя" -ForegroundColor DarkGray
|
|
41
45
|
New-Item -ItemType Directory -Force $root | Out-Null
|
|
42
46
|
Get-ChildItem $root -Directory -Filter 'node-v*' | Remove-Item -Recurse -Force # прежние копии
|
|
43
47
|
$zip = Join-Path $root $file
|
|
@@ -47,11 +51,13 @@
|
|
|
47
51
|
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
|
48
52
|
[IO.Compression.ZipFile]::ExtractToDirectory($zip, $root)
|
|
49
53
|
Remove-Item $zip
|
|
54
|
+
Write-Host ' √ Node.js готов' -ForegroundColor Green
|
|
50
55
|
}
|
|
51
56
|
$env:Path = "$dir;$env:Path"
|
|
52
57
|
$npx = Join-Path $dir 'npx.cmd'
|
|
53
58
|
}
|
|
54
59
|
$env:npm_config_update_notifier = 'false' # без рекламы новой версии npm
|
|
60
|
+
Write-Host ' · загружаю claude-guest - несколько секунд' -ForegroundColor DarkGray
|
|
55
61
|
& $npx --yes "claude-guest@$tag" @pkgArgs
|
|
56
62
|
} catch {
|
|
57
63
|
Write-Host ''
|