@downcity/workspace-ssh 0.0.0-stage → 0.1.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/LICENSE +183 -0
- package/bin/RemoteDirectoryProgram.d.ts +7 -0
- package/bin/RemoteDirectoryProgram.d.ts.map +1 -0
- package/bin/RemoteDirectoryProgram.js +66 -0
- package/bin/RemoteDirectoryProgram.js.map +1 -0
- package/bin/RemoteProgram.d.ts +7 -0
- package/bin/RemoteProgram.d.ts.map +1 -0
- package/bin/RemoteProgram.js +448 -0
- package/bin/RemoteProgram.js.map +1 -0
- package/bin/RemoteShellProgram.d.ts +3 -0
- package/bin/RemoteShellProgram.d.ts.map +1 -0
- package/bin/RemoteShellProgram.js +67 -0
- package/bin/RemoteShellProgram.js.map +1 -0
- package/bin/SshBrowseConfig.d.ts +11 -0
- package/bin/SshBrowseConfig.d.ts.map +1 -0
- package/bin/SshBrowseConfig.js +191 -0
- package/bin/SshBrowseConfig.js.map +1 -0
- package/bin/SshConnection.d.ts +32 -0
- package/bin/SshConnection.d.ts.map +1 -0
- package/bin/SshConnection.js +139 -0
- package/bin/SshConnection.js.map +1 -0
- package/bin/SshDirectoryBrowser.d.ts +17 -0
- package/bin/SshDirectoryBrowser.d.ts.map +1 -0
- package/bin/SshDirectoryBrowser.js +81 -0
- package/bin/SshDirectoryBrowser.js.map +1 -0
- package/bin/SshDirectorySetup.d.ts +10 -0
- package/bin/SshDirectorySetup.d.ts.map +1 -0
- package/bin/SshDirectorySetup.js +49 -0
- package/bin/SshDirectorySetup.js.map +1 -0
- package/bin/SshFileSystem.d.ts +37 -0
- package/bin/SshFileSystem.d.ts.map +1 -0
- package/bin/SshFileSystem.js +126 -0
- package/bin/SshFileSystem.js.map +1 -0
- package/bin/SshInitialization.d.ts +11 -0
- package/bin/SshInitialization.d.ts.map +1 -0
- package/bin/SshInitialization.js +92 -0
- package/bin/SshInitialization.js.map +1 -0
- package/bin/SshMedia.d.ts +7 -0
- package/bin/SshMedia.d.ts.map +1 -0
- package/bin/SshMedia.js +49 -0
- package/bin/SshMedia.js.map +1 -0
- package/bin/SshShell.d.ts +27 -0
- package/bin/SshShell.d.ts.map +1 -0
- package/bin/SshShell.js +227 -0
- package/bin/SshShell.js.map +1 -0
- package/bin/SshWorkspace.d.ts +31 -0
- package/bin/SshWorkspace.d.ts.map +1 -0
- package/bin/SshWorkspace.js +121 -0
- package/bin/SshWorkspace.js.map +1 -0
- package/bin/index.d.ts +8 -0
- package/bin/index.d.ts.map +1 -0
- package/bin/index.js +6 -0
- package/bin/index.js.map +1 -0
- package/bin/types/Ssh.d.ts +125 -0
- package/bin/types/Ssh.d.ts.map +1 -0
- package/bin/types/Ssh.js +2 -0
- package/bin/types/Ssh.js.map +1 -0
- package/bin/types/SshDirectory.d.ts +44 -0
- package/bin/types/SshDirectory.d.ts.map +1 -0
- package/bin/types/SshDirectory.js +2 -0
- package/bin/types/SshDirectory.js.map +1 -0
- package/package.json +30 -3
- package/README.md +0 -3
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 通过 python3 -c 临时执行的远端文件协议,不在远端写入程序或启动服务。
|
|
3
|
+
* 请求通过 stdin JSON 传递;文件路径以目录描述符逐段打开并拒绝 symlink 竞态。
|
|
4
|
+
* 只依赖已安装的 Python 3.8+、POSIX 文件系统和搜索时使用的 ripgrep。
|
|
5
|
+
*/
|
|
6
|
+
export const remote_program = String.raw `
|
|
7
|
+
import os, sys, json, stat, base64, hashlib, tempfile, datetime, subprocess, errno, fcntl, ctypes, shutil, codecs, signal
|
|
8
|
+
request = json.load(sys.stdin)
|
|
9
|
+
root = os.path.realpath(request['root'])
|
|
10
|
+
operation = request['operation']
|
|
11
|
+
arguments = request.get('arguments', {})
|
|
12
|
+
if (operation != 'validate' or not arguments.get('resolve_root', False)) and root != os.path.normpath(request['root']):
|
|
13
|
+
raise RuntimeError('Registered SSH root now resolves through a symbolic link; reconnect and verify the directory')
|
|
14
|
+
# 从 / 开始逐段 openat,关闭根路径祖先被替换为符号链接的竞态窗口。
|
|
15
|
+
root_fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
|
16
|
+
try:
|
|
17
|
+
for component in root.split('/'):
|
|
18
|
+
if not component: continue
|
|
19
|
+
next_fd = os.open(component, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=root_fd)
|
|
20
|
+
os.close(root_fd)
|
|
21
|
+
root_fd = next_fd
|
|
22
|
+
except:
|
|
23
|
+
os.close(root_fd)
|
|
24
|
+
raise
|
|
25
|
+
MAX_FILE = 64 * 1024 * 1024
|
|
26
|
+
MAX_WRITE = 1024 * 1024
|
|
27
|
+
MAX_WINDOW = 64 * 1024
|
|
28
|
+
|
|
29
|
+
def fail(code, message):
|
|
30
|
+
raise ValueError(code + ': ' + message)
|
|
31
|
+
|
|
32
|
+
def relative(value):
|
|
33
|
+
candidate = os.path.realpath(value if os.path.isabs(value) else os.path.join(root, value))
|
|
34
|
+
if os.path.commonpath([root, candidate]) != root:
|
|
35
|
+
fail('sandbox_denied', 'Path escapes remote Workspace')
|
|
36
|
+
return os.path.relpath(candidate, root)
|
|
37
|
+
|
|
38
|
+
def parent(value, create=False):
|
|
39
|
+
parts = relative(value).split('/')
|
|
40
|
+
descriptor = os.dup(root_fd)
|
|
41
|
+
try:
|
|
42
|
+
for part in parts[:-1]:
|
|
43
|
+
if part == '.': continue
|
|
44
|
+
if create:
|
|
45
|
+
try: os.mkdir(part, dir_fd=descriptor)
|
|
46
|
+
except FileExistsError: pass
|
|
47
|
+
next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=descriptor)
|
|
48
|
+
os.close(descriptor)
|
|
49
|
+
descriptor = next_fd
|
|
50
|
+
return descriptor, parts[-1]
|
|
51
|
+
except:
|
|
52
|
+
os.close(descriptor)
|
|
53
|
+
raise
|
|
54
|
+
|
|
55
|
+
def open_file(value):
|
|
56
|
+
descriptor, name = parent(value)
|
|
57
|
+
try:
|
|
58
|
+
result = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=descriptor)
|
|
59
|
+
if not stat.S_ISREG(os.fstat(result).st_mode):
|
|
60
|
+
os.close(result)
|
|
61
|
+
fail('not_a_file', 'Expected a regular file')
|
|
62
|
+
return os.fdopen(result, 'rb')
|
|
63
|
+
finally: os.close(descriptor)
|
|
64
|
+
|
|
65
|
+
def metadata(value):
|
|
66
|
+
descriptor, name = parent(value)
|
|
67
|
+
try:
|
|
68
|
+
info = os.stat(name, dir_fd=descriptor, follow_symlinks=False)
|
|
69
|
+
if stat.S_ISLNK(info.st_mode): fail('sandbox_denied', 'Symlink changed during access')
|
|
70
|
+
return {'size': info.st_size, 'modified_at': info.st_mtime * 1000, 'is_directory': stat.S_ISDIR(info.st_mode), 'is_file': stat.S_ISREG(info.st_mode)}
|
|
71
|
+
finally: os.close(descriptor)
|
|
72
|
+
|
|
73
|
+
def read_bytes(value):
|
|
74
|
+
with open_file(value) as stream:
|
|
75
|
+
if os.fstat(stream.fileno()).st_size > MAX_FILE: fail('file_too_large', 'File exceeds 64 MiB')
|
|
76
|
+
content = stream.read(MAX_FILE + 1)
|
|
77
|
+
if len(content) > MAX_FILE: fail('file_too_large', 'File exceeds 64 MiB')
|
|
78
|
+
return content
|
|
79
|
+
|
|
80
|
+
def write_atomic(value, content, overwrite=True, expected=None):
|
|
81
|
+
descriptor, name = parent(value, True)
|
|
82
|
+
if name == '.': fail('invalid_path', 'Cannot replace Workspace root')
|
|
83
|
+
temporary_name = '.downcity-' + os.urandom(16).hex()
|
|
84
|
+
try:
|
|
85
|
+
# 父目录锁协调本适配器的写事务,完整内容只在同目录原子替换时可见。
|
|
86
|
+
fcntl.flock(descriptor, fcntl.LOCK_EX)
|
|
87
|
+
mode = 0o666
|
|
88
|
+
exists = False
|
|
89
|
+
try:
|
|
90
|
+
info = os.stat(name, dir_fd=descriptor, follow_symlinks=False)
|
|
91
|
+
if not stat.S_ISREG(info.st_mode): fail('not_a_file', 'Expected a regular file')
|
|
92
|
+
exists = True
|
|
93
|
+
mode = stat.S_IMODE(info.st_mode)
|
|
94
|
+
except FileNotFoundError: pass
|
|
95
|
+
if exists and not overwrite: fail('file_exists', 'File already exists; use overwrite=true')
|
|
96
|
+
if expected == 'missing' and exists: fail('file_changed', 'File was created before commit')
|
|
97
|
+
if expected not in [None, 'missing'] and (not exists or hashlib.sha256(read_bytes(value)).hexdigest() != expected): fail('file_changed', 'File changed before commit')
|
|
98
|
+
temporary_fd = os.open(temporary_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode, dir_fd=descriptor)
|
|
99
|
+
with os.fdopen(temporary_fd, 'wb') as stream:
|
|
100
|
+
stream.write(content)
|
|
101
|
+
stream.flush()
|
|
102
|
+
os.fsync(stream.fileno())
|
|
103
|
+
if overwrite:
|
|
104
|
+
os.rename(temporary_name, name, src_dir_fd=descriptor, dst_dir_fd=descriptor)
|
|
105
|
+
else:
|
|
106
|
+
os.link(temporary_name, name, src_dir_fd=descriptor, dst_dir_fd=descriptor, follow_symlinks=False)
|
|
107
|
+
os.unlink(temporary_name, dir_fd=descriptor)
|
|
108
|
+
try: os.fsync(descriptor)
|
|
109
|
+
except OSError as error:
|
|
110
|
+
if error.errno != errno.EINVAL: raise
|
|
111
|
+
return exists
|
|
112
|
+
finally:
|
|
113
|
+
try: os.unlink(temporary_name, dir_fd=descriptor)
|
|
114
|
+
except FileNotFoundError: pass
|
|
115
|
+
os.close(descriptor)
|
|
116
|
+
|
|
117
|
+
def remove_entry(descriptor, name):
|
|
118
|
+
info = os.stat(name, dir_fd=descriptor, follow_symlinks=False)
|
|
119
|
+
if stat.S_ISDIR(info.st_mode):
|
|
120
|
+
child_fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=descriptor)
|
|
121
|
+
try:
|
|
122
|
+
for entry in os.listdir(child_fd): remove_entry(child_fd, entry)
|
|
123
|
+
finally: os.close(child_fd)
|
|
124
|
+
os.rmdir(name, dir_fd=descriptor)
|
|
125
|
+
else: os.unlink(name, dir_fd=descriptor)
|
|
126
|
+
|
|
127
|
+
def text_encoding(content):
|
|
128
|
+
if content.startswith(b'\xff\xfe'): return 'utf-16le', 'utf-16-le', 2
|
|
129
|
+
if content.startswith(b'\xfe\xff'): return 'utf-16be', 'utf-16-be', 2
|
|
130
|
+
return 'utf-8', 'utf-8', 3 if content.startswith(b'\xef\xbb\xbf') else 0
|
|
131
|
+
|
|
132
|
+
def raw_line(stream, limit, encoding):
|
|
133
|
+
if encoding == 'utf-8': return stream.readline(limit)
|
|
134
|
+
content = bytearray()
|
|
135
|
+
newline = b'\n\x00' if encoding == 'utf-16-le' else b'\x00\n'
|
|
136
|
+
while len(content) + 2 <= limit:
|
|
137
|
+
unit = stream.read(2)
|
|
138
|
+
if not unit: break
|
|
139
|
+
content.extend(unit)
|
|
140
|
+
if unit == newline: break
|
|
141
|
+
return bytes(content)
|
|
142
|
+
|
|
143
|
+
def file_action():
|
|
144
|
+
action = arguments['action']
|
|
145
|
+
data = arguments['input']
|
|
146
|
+
value = data['file_path']
|
|
147
|
+
absolute = os.path.join(root, relative(value))
|
|
148
|
+
if action == 'read':
|
|
149
|
+
with open_file(value) as stream:
|
|
150
|
+
info = os.fstat(stream.fileno())
|
|
151
|
+
version = '%s:%s:%s:%s:%s' % (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
|
|
152
|
+
selection = data.get('range') or {'type': 'lines'}
|
|
153
|
+
if selection.get('expected_version') and selection['expected_version'] != version: fail('file_changed', 'File changed; read from the beginning')
|
|
154
|
+
sample = stream.read(8192)
|
|
155
|
+
encoding_name, encoding, bom_size = text_encoding(sample)
|
|
156
|
+
binary = sample.startswith(b'%PDF-') or (encoding == 'utf-8' and b'\x00' in sample)
|
|
157
|
+
try: codecs.getincrementaldecoder(encoding)().decode(sample[bom_size:], final=False)
|
|
158
|
+
except UnicodeDecodeError: binary = True
|
|
159
|
+
if binary:
|
|
160
|
+
return dict(success=True, file_path=absolute, total_bytes=info.st_size, total_lines=0, start_line=0, end_line=-1, content='', truncated=False, type='binary', file_version=version)
|
|
161
|
+
stream.seek(bom_size)
|
|
162
|
+
start = max(0, int(selection.get('offset', 0)))
|
|
163
|
+
byte_mode = selection['type'] == 'bytes'
|
|
164
|
+
limit = min(2000, max(1, int(selection.get('limit', 500))))
|
|
165
|
+
newline = b'\n' if encoding == 'utf-8' else b'\n\x00' if encoding == 'utf-16-le' else b'\x00\n'
|
|
166
|
+
if byte_mode:
|
|
167
|
+
if encoding != 'utf-8' and start % 2: fail('encoding_error', 'UTF-16 byte offset must be aligned')
|
|
168
|
+
stream.seek(max(start, bom_size))
|
|
169
|
+
else:
|
|
170
|
+
for index in range(start):
|
|
171
|
+
skipped = raw_line(stream, MAX_WINDOW, encoding)
|
|
172
|
+
if not skipped: break
|
|
173
|
+
while skipped and not skipped.endswith(newline):
|
|
174
|
+
skipped = raw_line(stream, MAX_WINDOW, encoding)
|
|
175
|
+
if stream.tell() > MAX_FILE: fail('file_too_large', 'Line scan exceeds 64 MiB; use byte continuation')
|
|
176
|
+
if stream.tell() > MAX_FILE: fail('file_too_large', 'Line scan exceeds 64 MiB; use byte continuation')
|
|
177
|
+
start_byte = stream.tell()
|
|
178
|
+
output = b''
|
|
179
|
+
count = 0
|
|
180
|
+
while count < (2000 if byte_mode else limit) and len(output) < MAX_WINDOW:
|
|
181
|
+
chunk = raw_line(stream, MAX_WINDOW - len(output), encoding)
|
|
182
|
+
if not chunk: break
|
|
183
|
+
output += chunk
|
|
184
|
+
count += 1
|
|
185
|
+
# 增量解码器保留被截断的字符尾部,游标只推进已经披露的原始字节。
|
|
186
|
+
try:
|
|
187
|
+
decoder = codecs.getincrementaldecoder(encoding)()
|
|
188
|
+
text = decoder.decode(output, final=stream.tell() >= info.st_size)
|
|
189
|
+
remaining = decoder.getstate()[0]
|
|
190
|
+
if remaining: output = output[:-len(remaining)]
|
|
191
|
+
except UnicodeDecodeError: fail('encoding_error', 'Text contains invalid encoded characters')
|
|
192
|
+
# 输出预算按 UTF-8 文本字节计算;UTF-16 的 CJK 文本不能放大到超过披露上限。
|
|
193
|
+
encoded_text = text.encode('utf-8')
|
|
194
|
+
if len(encoded_text) > MAX_WINDOW:
|
|
195
|
+
budget_decoder = codecs.getincrementaldecoder('utf-8')()
|
|
196
|
+
text = budget_decoder.decode(encoded_text[:MAX_WINDOW], final=False)
|
|
197
|
+
output = text.encode(encoding)
|
|
198
|
+
next_byte = start_byte + len(output)
|
|
199
|
+
if version != '%s:%s:%s:%s:%s' % tuple(getattr(os.fstat(stream.fileno()), key) for key in ['st_dev', 'st_ino', 'st_size', 'st_mtime_ns', 'st_ctime_ns']): fail('file_changed', 'File changed while reading')
|
|
200
|
+
truncated = next_byte < info.st_size
|
|
201
|
+
result = dict(success=True, file_path=absolute, total_bytes=info.st_size, total_lines=None if truncated or start_byte > bom_size else len(text.splitlines()), start_line=-1 if byte_mode else start, end_line=-1 if byte_mode else start + len(text.splitlines()) - 1, content=text, truncated=truncated, type='text', encoding=encoding_name, file_version=version, start_byte=start_byte)
|
|
202
|
+
if truncated: result['next_byte_offset'] = next_byte
|
|
203
|
+
if not truncated and start_byte == bom_size: result['sha256'] = hashlib.sha256(sample[:bom_size] + output).hexdigest()
|
|
204
|
+
return result
|
|
205
|
+
if action == 'write':
|
|
206
|
+
content = data['content'].encode('utf-8')
|
|
207
|
+
if len(content) > MAX_WRITE: fail('content_too_large', 'Write exceeds 1 MiB')
|
|
208
|
+
overwritten = write_atomic(value, content, data.get('overwrite', False))
|
|
209
|
+
return dict(success=True, file_path=absolute, bytes_written=len(content), lines_written=len(data['content'].splitlines()), overwritten=overwritten, timestamp=datetime.datetime.now(datetime.timezone.utc).isoformat(), sha256=hashlib.sha256(content).hexdigest())
|
|
210
|
+
original = read_bytes(value)
|
|
211
|
+
previous_sha = hashlib.sha256(original).hexdigest()
|
|
212
|
+
if data.get('expected_sha256') and data['expected_sha256'] != previous_sha: fail('file_changed', 'SHA256 does not match')
|
|
213
|
+
_, encoding, bom_size = text_encoding(original)
|
|
214
|
+
if encoding == 'utf-8' and b'\x00' in original: fail('binary_file', 'Cannot edit binary content')
|
|
215
|
+
text = original[bom_size:].decode(encoding)
|
|
216
|
+
edits = data['edits']
|
|
217
|
+
if not edits: fail('no_edits', 'edits must not be empty')
|
|
218
|
+
if len(edits) > 10: fail('too_many_edits', 'At most ten edits')
|
|
219
|
+
regions, details = [], []
|
|
220
|
+
for index, edit in enumerate(edits):
|
|
221
|
+
old, new = edit['old_text'], edit['new_text']
|
|
222
|
+
if not old or len(old) > 10000 or len(new) > 50000: fail('edit_too_large', 'Invalid edit size')
|
|
223
|
+
count, position = 0, 0
|
|
224
|
+
while True:
|
|
225
|
+
position = text.find(old, position)
|
|
226
|
+
if position < 0: break
|
|
227
|
+
count += 1
|
|
228
|
+
position += 1
|
|
229
|
+
if count != 1: fail('duplicate_match' if count else 'not_found', 'Each old_text must match exactly once')
|
|
230
|
+
begin = text.index(old)
|
|
231
|
+
regions.append((begin, begin + len(old), new))
|
|
232
|
+
details.append(dict(index=index, status='applied', match_count=1, line_start=text[:begin].count('\n')))
|
|
233
|
+
regions.sort()
|
|
234
|
+
if any(regions[index][1] > regions[index + 1][0] for index in range(len(regions) - 1)): fail('overlapping_edits', 'Edit regions overlap')
|
|
235
|
+
for begin, end, new in reversed(regions): text = text[:begin] + new + text[end:]
|
|
236
|
+
content = original[:bom_size] + text.encode(encoding)
|
|
237
|
+
if len(content) > MAX_FILE: fail('content_too_large', 'Edited file exceeds 64 MiB')
|
|
238
|
+
write_atomic(value, content, True, previous_sha)
|
|
239
|
+
return dict(success=True, file_path=absolute, applied=len(edits), details=details, new_total_lines=len(text.splitlines()), previous_sha256=previous_sha, sha256=hashlib.sha256(content).hexdigest())
|
|
240
|
+
|
|
241
|
+
def search_action():
|
|
242
|
+
action, data = arguments['action'], arguments['input']
|
|
243
|
+
value = relative(data.get('path', '.'))
|
|
244
|
+
limit = min(2000, max(1, int(data.get('max_results', 200))))
|
|
245
|
+
descriptor, name = parent(value)
|
|
246
|
+
results, scanned, output_bytes, truncated = [], 0, 0, False
|
|
247
|
+
directory = None
|
|
248
|
+
try:
|
|
249
|
+
info = os.stat(name, dir_fd=descriptor, follow_symlinks=False)
|
|
250
|
+
if stat.S_ISDIR(info.st_mode):
|
|
251
|
+
directory = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=descriptor)
|
|
252
|
+
os.fchdir(directory)
|
|
253
|
+
candidate_command = ['rg', '--files', '--hidden', '--null']
|
|
254
|
+
if action == 'find': candidate_command.extend(['-g', data['pattern']])
|
|
255
|
+
else:
|
|
256
|
+
for pattern in data.get('glob', []): candidate_command.extend(['-g', pattern])
|
|
257
|
+
candidate_command.extend(['--', '.'])
|
|
258
|
+
process = subprocess.Popen(candidate_command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
|
|
259
|
+
try:
|
|
260
|
+
pending = b''
|
|
261
|
+
candidates = []
|
|
262
|
+
candidate_bytes = 0
|
|
263
|
+
while True:
|
|
264
|
+
chunk = process.stdout.read(16384)
|
|
265
|
+
if not chunk: break
|
|
266
|
+
pending += chunk
|
|
267
|
+
candidate_bytes += len(chunk)
|
|
268
|
+
if candidate_bytes > 2 * 1024 * 1024:
|
|
269
|
+
truncated = True
|
|
270
|
+
process.kill()
|
|
271
|
+
break
|
|
272
|
+
parts = pending.split(b'\x00')
|
|
273
|
+
pending = parts.pop()
|
|
274
|
+
candidates.extend(parts)
|
|
275
|
+
process.wait()
|
|
276
|
+
if process.returncode not in [0, 1] and not truncated: fail('search_failed', 'ripgrep file discovery failed')
|
|
277
|
+
finally:
|
|
278
|
+
if process.poll() is None: process.kill()
|
|
279
|
+
process.wait()
|
|
280
|
+
candidates = [os.path.normpath(os.path.join(value, item.decode('utf-8'))) for item in candidates]
|
|
281
|
+
elif stat.S_ISREG(info.st_mode) and action == 'grep': candidates = [value]
|
|
282
|
+
else: fail('not_a_directory', 'Search path must be a directory')
|
|
283
|
+
os.fchdir(root_fd)
|
|
284
|
+
for candidate in candidates:
|
|
285
|
+
# rg 只发现名称;真正读取使用 rooted openat,拒绝搜索期间被替换的越界符号链接。
|
|
286
|
+
try:
|
|
287
|
+
with open_file(candidate) as stream:
|
|
288
|
+
file_size = os.fstat(stream.fileno()).st_size
|
|
289
|
+
if action == 'find':
|
|
290
|
+
results.append(candidate)
|
|
291
|
+
if len(results) > limit:
|
|
292
|
+
truncated = True
|
|
293
|
+
break
|
|
294
|
+
continue
|
|
295
|
+
if file_size > MAX_FILE: continue
|
|
296
|
+
command = ['rg', '--json', '--max-count', str(limit), '--max-columns', '4096']
|
|
297
|
+
if not data.get('case_sensitive', False): command.append('-i')
|
|
298
|
+
if data.get('literal', True): command.append('-F')
|
|
299
|
+
command.extend(['--', data['query'], '-'])
|
|
300
|
+
# 已校验的描述符直接作为 rg stdin,不按名称再次打开项目文件。
|
|
301
|
+
search = subprocess.Popen(command, stdin=stream, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
|
|
302
|
+
scanned += 1
|
|
303
|
+
try:
|
|
304
|
+
while True:
|
|
305
|
+
line = search.stdout.readline(2 * 1024 * 1024 + 1)
|
|
306
|
+
if not line: break
|
|
307
|
+
output_bytes += len(line)
|
|
308
|
+
if output_bytes > 2 * 1024 * 1024:
|
|
309
|
+
truncated = True
|
|
310
|
+
break
|
|
311
|
+
record = json.loads(line)
|
|
312
|
+
if record['type'] != 'match': continue
|
|
313
|
+
item = record['data']
|
|
314
|
+
for match in item['submatches']:
|
|
315
|
+
results.append(dict(file_path=candidate, line_number=item['line_number'], column=match['start'] + 1, text=item['lines']['text'].rstrip('\n')[:4096], match_text=match['match'].get('text', '')[:4096], line_truncated=len(item['lines']['text']) > 4096))
|
|
316
|
+
if len(results) > limit:
|
|
317
|
+
truncated = True
|
|
318
|
+
break
|
|
319
|
+
if truncated: break
|
|
320
|
+
if truncated: search.kill()
|
|
321
|
+
search.wait()
|
|
322
|
+
if search.returncode not in [0, 1] and not truncated: fail('invalid_pattern', 'ripgrep rejected the query')
|
|
323
|
+
finally:
|
|
324
|
+
if search.poll() is None: search.kill()
|
|
325
|
+
search.wait()
|
|
326
|
+
if truncated: break
|
|
327
|
+
except (FileNotFoundError, PermissionError): continue
|
|
328
|
+
finally:
|
|
329
|
+
os.close(descriptor)
|
|
330
|
+
if directory is not None: os.close(directory)
|
|
331
|
+
base = dict(success=True, root_path=root, search_path=os.path.join(root, value), match_count=min(limit, len(results)), truncated=truncated)
|
|
332
|
+
if action == 'find': base.update(pattern=data['pattern'], files=sorted(results[:limit]))
|
|
333
|
+
else: base.update(query=data['query'], matches=results[:limit], files_searched=scanned)
|
|
334
|
+
return base
|
|
335
|
+
|
|
336
|
+
def dispatch():
|
|
337
|
+
value = arguments.get('path', '.')
|
|
338
|
+
if operation == 'validate':
|
|
339
|
+
if sys.version_info < (3, 8): fail('internal_error', 'SSH Workspace needs Python 3.8+; run SSH Workspace dependency initialization')
|
|
340
|
+
if sys.platform not in ['linux', 'darwin']: fail('internal_error', 'Only Linux/macOS SSH hosts are supported')
|
|
341
|
+
if shutil.which('ps') is None: fail('internal_error', 'SSH Workspace needs POSIX ps for process cleanup; run SSH Workspace dependency initialization')
|
|
342
|
+
if shutil.which('rg') is None: fail('rg_unavailable', 'SSH Workspace needs ripgrep (rg); run SSH Workspace dependency initialization')
|
|
343
|
+
if not os.access(root, os.R_OK | os.X_OK): fail('permission_denied', 'Remote directory is not readable')
|
|
344
|
+
return dict(root_path=root, platform=sys.platform, env={key: os.environ[key] for key in ['HOME', 'PATH', 'SHELL', 'LANG', 'USER', 'TMPDIR'] if key in os.environ})
|
|
345
|
+
if operation == 'file_action': return file_action()
|
|
346
|
+
if operation == 'search_action': return search_action()
|
|
347
|
+
if operation == 'media':
|
|
348
|
+
with open_file(value) as stream:
|
|
349
|
+
info = os.fstat(stream.fileno())
|
|
350
|
+
version = '%s:%s:%s:%s:%s' % (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
|
|
351
|
+
if version != arguments['expected_version']: fail('file_changed', 'Media changed before content capture')
|
|
352
|
+
if info.st_size > 2 * 1024 * 1024: fail('media_too_large', 'Media exceeds 2 MiB')
|
|
353
|
+
content = stream.read(2 * 1024 * 1024 + 1)
|
|
354
|
+
after = os.fstat(stream.fileno())
|
|
355
|
+
if len(content) > 2 * 1024 * 1024 or (info.st_size, info.st_mtime_ns, info.st_ctime_ns) != (after.st_size, after.st_mtime_ns, after.st_ctime_ns): fail('file_changed', 'Media changed during capture')
|
|
356
|
+
return base64.b64encode(content).decode('ascii')
|
|
357
|
+
if operation == 'stat': return metadata(value)
|
|
358
|
+
if operation == 'read': return base64.b64encode(read_bytes(value)).decode('ascii')
|
|
359
|
+
if operation == 'list':
|
|
360
|
+
descriptor, name = parent(value)
|
|
361
|
+
try:
|
|
362
|
+
directory = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=descriptor)
|
|
363
|
+
try:
|
|
364
|
+
result = []
|
|
365
|
+
for item in os.scandir(directory):
|
|
366
|
+
if len(result) >= 10000: fail('file_too_large', 'Directory exceeds 10000 entries')
|
|
367
|
+
info = item.stat(follow_symlinks=False)
|
|
368
|
+
if stat.S_ISLNK(info.st_mode): continue
|
|
369
|
+
result.append(dict(name=item.name, is_directory=stat.S_ISDIR(info.st_mode), is_file=stat.S_ISREG(info.st_mode), size=info.st_size, modified_at=info.st_mtime * 1000))
|
|
370
|
+
return result
|
|
371
|
+
finally: os.close(directory)
|
|
372
|
+
finally: os.close(descriptor)
|
|
373
|
+
if operation == 'mkdir':
|
|
374
|
+
descriptor, name = parent(os.path.join(value, '.downcity-directory-marker'), True)
|
|
375
|
+
os.close(descriptor)
|
|
376
|
+
return None
|
|
377
|
+
if operation == 'write':
|
|
378
|
+
content = base64.b64decode(arguments['content'])
|
|
379
|
+
if len(content) > MAX_FILE: fail('content_too_large', 'Write exceeds 64 MiB')
|
|
380
|
+
write_atomic(value, content)
|
|
381
|
+
return None
|
|
382
|
+
if operation == 'append':
|
|
383
|
+
try:
|
|
384
|
+
original = read_bytes(value)
|
|
385
|
+
expected = hashlib.sha256(original).hexdigest()
|
|
386
|
+
except FileNotFoundError:
|
|
387
|
+
original = b''
|
|
388
|
+
expected = 'missing'
|
|
389
|
+
content = original + base64.b64decode(arguments['content'])
|
|
390
|
+
if len(content) > MAX_FILE: fail('content_too_large', 'Append exceeds 64 MiB')
|
|
391
|
+
write_atomic(value, content, True, expected)
|
|
392
|
+
return None
|
|
393
|
+
if operation == 'remove':
|
|
394
|
+
descriptor, name = parent(value)
|
|
395
|
+
try:
|
|
396
|
+
if name == '.': fail('invalid_path', 'Cannot delete Workspace root')
|
|
397
|
+
try: remove_entry(descriptor, name)
|
|
398
|
+
except FileNotFoundError: pass
|
|
399
|
+
finally: os.close(descriptor)
|
|
400
|
+
return None
|
|
401
|
+
if operation == 'move':
|
|
402
|
+
source_fd, source_name = parent(value)
|
|
403
|
+
target_fd, target_name = parent(arguments['target'])
|
|
404
|
+
try:
|
|
405
|
+
if source_name == '.' or target_name == '.': fail('invalid_path', 'Cannot move Workspace root')
|
|
406
|
+
try:
|
|
407
|
+
os.stat(target_name, dir_fd=target_fd, follow_symlinks=False)
|
|
408
|
+
fail('file_exists', 'Move target exists')
|
|
409
|
+
except FileNotFoundError: pass
|
|
410
|
+
# 内核原子 no-replace;不能用先检查再 rename 的窗口覆盖外部新文件。
|
|
411
|
+
library = ctypes.CDLL(None, use_errno=True)
|
|
412
|
+
if sys.platform == 'linux':
|
|
413
|
+
rename = library.renameat2
|
|
414
|
+
flag = 1
|
|
415
|
+
else:
|
|
416
|
+
rename = library.renameatx_np
|
|
417
|
+
flag = 4
|
|
418
|
+
rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]
|
|
419
|
+
rename.restype = ctypes.c_int
|
|
420
|
+
if rename(source_fd, os.fsencode(source_name), target_fd, os.fsencode(target_name), flag) != 0:
|
|
421
|
+
error = ctypes.get_errno()
|
|
422
|
+
raise OSError(error, os.strerror(error))
|
|
423
|
+
finally:
|
|
424
|
+
os.close(source_fd)
|
|
425
|
+
os.close(target_fd)
|
|
426
|
+
return None
|
|
427
|
+
fail('internal_error', 'Unknown remote operation')
|
|
428
|
+
|
|
429
|
+
def cancel_request(*unused):
|
|
430
|
+
raise InterruptedError('SSH channel closed; operation result may be unknown')
|
|
431
|
+
signal.signal(signal.SIGHUP, cancel_request)
|
|
432
|
+
signal.signal(signal.SIGTERM, cancel_request)
|
|
433
|
+
|
|
434
|
+
try:
|
|
435
|
+
result = dispatch()
|
|
436
|
+
print(json.dumps({'ok': True, 'result': result}, ensure_ascii=True))
|
|
437
|
+
except Exception as error:
|
|
438
|
+
code = 'internal_error'
|
|
439
|
+
if isinstance(error, FileNotFoundError): code = 'file_not_found'
|
|
440
|
+
elif isinstance(error, FileExistsError): code = 'file_exists'
|
|
441
|
+
elif isinstance(error, OSError) and error.errno == errno.ELOOP: code = 'sandbox_denied'
|
|
442
|
+
elif isinstance(error, PermissionError): code = 'permission_denied'
|
|
443
|
+
elif isinstance(error, UnicodeError): code = 'encoding_error'
|
|
444
|
+
elif isinstance(error, ValueError): code = str(error).split(':', 1)[0]
|
|
445
|
+
print(json.dumps({'ok': False, 'code': code, 'message': str(error)}, ensure_ascii=True))
|
|
446
|
+
finally: os.close(root_fd)
|
|
447
|
+
`;
|
|
448
|
+
//# sourceMappingURL=RemoteProgram.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RemoteProgram.js","sourceRoot":"","sources":["../src/RemoteProgram.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAybxC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RemoteShellProgram.d.ts","sourceRoot":"","sources":["../src/RemoteShellProgram.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,eAAO,MAAM,oBAAoB,QAgEhC,CAAC"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/** 临时远端命令监督进程:通道 EOF 或取消时终止子进程组;不安装远程服务。 */
|
|
2
|
+
export const remote_shell_program = String.raw `
|
|
3
|
+
import os, sys, json, base64, subprocess, select, signal, pty, fcntl, termios, struct
|
|
4
|
+
config = json.loads(base64.b64decode(sys.argv[1]))
|
|
5
|
+
os.chdir(config['cwd'])
|
|
6
|
+
environment = dict(os.environ)
|
|
7
|
+
environment.update(config.get('env', {}))
|
|
8
|
+
command = [config.get('shell') or environment.get('SHELL') or '/bin/sh', '-lc' if config.get('login') else '-c', config['cmd']]
|
|
9
|
+
terminal = config.get('terminal', False)
|
|
10
|
+
master = slave = None
|
|
11
|
+
if terminal:
|
|
12
|
+
master, slave = pty.openpty()
|
|
13
|
+
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', config.get('rows', 40), config.get('cols', 120), 0, 0))
|
|
14
|
+
def setup():
|
|
15
|
+
os.setsid()
|
|
16
|
+
fcntl.ioctl(slave, termios.TIOCSCTTY, 0)
|
|
17
|
+
process = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=slave, env=environment, preexec_fn=setup)
|
|
18
|
+
os.close(slave)
|
|
19
|
+
else:
|
|
20
|
+
process = subprocess.Popen(command, stdin=subprocess.PIPE, env=environment, start_new_session=True)
|
|
21
|
+
def terminate(*unused):
|
|
22
|
+
# zsh 等解释器会给后台作业另建进程组;按本命令的独立 session 清理,而非仅杀前台组。
|
|
23
|
+
try:
|
|
24
|
+
listing = subprocess.run(['ps', '-A', '-o', 'pid='], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=3)
|
|
25
|
+
for raw in listing.stdout.split():
|
|
26
|
+
try:
|
|
27
|
+
pid = int(raw)
|
|
28
|
+
if pid != os.getpid() and os.getsid(pid) == process.pid:
|
|
29
|
+
os.kill(pid, signal.SIGKILL)
|
|
30
|
+
except (ProcessLookupError, PermissionError): pass
|
|
31
|
+
except (OSError, subprocess.TimeoutExpired): pass
|
|
32
|
+
try: os.killpg(process.pid, signal.SIGKILL)
|
|
33
|
+
except ProcessLookupError: pass
|
|
34
|
+
signal.signal(signal.SIGHUP, terminate)
|
|
35
|
+
signal.signal(signal.SIGTERM, terminate)
|
|
36
|
+
try:
|
|
37
|
+
while process.poll() is None:
|
|
38
|
+
readable, _, _ = select.select([0] + ([master] if terminal else []), [], [], 0.1)
|
|
39
|
+
if 0 in readable:
|
|
40
|
+
content = os.read(0, 65536)
|
|
41
|
+
if not content:
|
|
42
|
+
terminate()
|
|
43
|
+
break
|
|
44
|
+
if terminal: os.write(master, content)
|
|
45
|
+
else:
|
|
46
|
+
try:
|
|
47
|
+
process.stdin.write(content)
|
|
48
|
+
process.stdin.flush()
|
|
49
|
+
except BrokenPipeError: pass
|
|
50
|
+
if terminal and master in readable:
|
|
51
|
+
try: content = os.read(master, 65536)
|
|
52
|
+
except OSError: content = b''
|
|
53
|
+
if content: os.write(1, content)
|
|
54
|
+
if terminal:
|
|
55
|
+
while select.select([master], [], [], 0)[0]:
|
|
56
|
+
try: content = os.read(master, 65536)
|
|
57
|
+
except OSError: break
|
|
58
|
+
if not content: break
|
|
59
|
+
os.write(1, content)
|
|
60
|
+
finally:
|
|
61
|
+
# Shell 退出后也清理同进程组内留下的子进程;主动 setsid 脱离者不在此监督范围。
|
|
62
|
+
terminate()
|
|
63
|
+
process.wait()
|
|
64
|
+
if master is not None: os.close(master)
|
|
65
|
+
sys.exit(process.returncode if process.returncode >= 0 else 128 - process.returncode)
|
|
66
|
+
`;
|
|
67
|
+
//# sourceMappingURL=RemoteShellProgram.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RemoteShellProgram.js","sourceRoot":"","sources":["../src/RemoteShellProgram.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,MAAM,CAAC,MAAM,oBAAoB,GAAG,MAAM,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgE9C,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 返回临时配置和清理函数;测试可提供隔离配置根,Renderer 不接受这些本机路径。
|
|
3
|
+
* 完成快照后才允许 OpenSSH 启动,读取期间取消也会清理所有临时文件。
|
|
4
|
+
*/
|
|
5
|
+
export declare function create_ssh_browse_config(signal: AbortSignal, home_path?: string, system_path?: string): Promise<{
|
|
6
|
+
/** 交给系统 OpenSSH -F 的临时绝对配置路径。 */
|
|
7
|
+
config_path: string;
|
|
8
|
+
/** 关闭连接后删除快照及其所在临时目录。 */
|
|
9
|
+
dispose(): Promise<void>;
|
|
10
|
+
}>;
|
|
11
|
+
//# sourceMappingURL=SshBrowseConfig.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SshBrowseConfig.d.ts","sourceRoot":"","sources":["../src/SshBrowseConfig.ts"],"names":[],"mappings":"AA2CA;;;GAGG;AACH,wBAAsB,wBAAwB,CAAC,MAAM,EAAE,WAAW,EAAE,SAAS,SAAY,EAAE,WAAW,SAAwB,GAAG,OAAO,CAAC;IACrI,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,yBAAyB;IACzB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5B,CAAC,CA8FD"}
|