@downcity/workspace-ssh 0.0.0-stage → 0.1.1

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 (63) hide show
  1. package/LICENSE +183 -0
  2. package/bin/RemoteDirectoryProgram.d.ts +7 -0
  3. package/bin/RemoteDirectoryProgram.d.ts.map +1 -0
  4. package/bin/RemoteDirectoryProgram.js +66 -0
  5. package/bin/RemoteDirectoryProgram.js.map +1 -0
  6. package/bin/RemoteProgram.d.ts +7 -0
  7. package/bin/RemoteProgram.d.ts.map +1 -0
  8. package/bin/RemoteProgram.js +507 -0
  9. package/bin/RemoteProgram.js.map +1 -0
  10. package/bin/RemoteShellProgram.d.ts +3 -0
  11. package/bin/RemoteShellProgram.d.ts.map +1 -0
  12. package/bin/RemoteShellProgram.js +67 -0
  13. package/bin/RemoteShellProgram.js.map +1 -0
  14. package/bin/SshBrowseConfig.d.ts +11 -0
  15. package/bin/SshBrowseConfig.d.ts.map +1 -0
  16. package/bin/SshBrowseConfig.js +191 -0
  17. package/bin/SshBrowseConfig.js.map +1 -0
  18. package/bin/SshConnection.d.ts +32 -0
  19. package/bin/SshConnection.d.ts.map +1 -0
  20. package/bin/SshConnection.js +139 -0
  21. package/bin/SshConnection.js.map +1 -0
  22. package/bin/SshDirectoryBrowser.d.ts +17 -0
  23. package/bin/SshDirectoryBrowser.d.ts.map +1 -0
  24. package/bin/SshDirectoryBrowser.js +81 -0
  25. package/bin/SshDirectoryBrowser.js.map +1 -0
  26. package/bin/SshDirectorySetup.d.ts +10 -0
  27. package/bin/SshDirectorySetup.d.ts.map +1 -0
  28. package/bin/SshDirectorySetup.js +49 -0
  29. package/bin/SshDirectorySetup.js.map +1 -0
  30. package/bin/SshFileSystem.d.ts +39 -0
  31. package/bin/SshFileSystem.d.ts.map +1 -0
  32. package/bin/SshFileSystem.js +171 -0
  33. package/bin/SshFileSystem.js.map +1 -0
  34. package/bin/SshInitialization.d.ts +11 -0
  35. package/bin/SshInitialization.d.ts.map +1 -0
  36. package/bin/SshInitialization.js +92 -0
  37. package/bin/SshInitialization.js.map +1 -0
  38. package/bin/SshMedia.d.ts +7 -0
  39. package/bin/SshMedia.d.ts.map +1 -0
  40. package/bin/SshMedia.js +49 -0
  41. package/bin/SshMedia.js.map +1 -0
  42. package/bin/SshShell.d.ts +29 -0
  43. package/bin/SshShell.d.ts.map +1 -0
  44. package/bin/SshShell.js +233 -0
  45. package/bin/SshShell.js.map +1 -0
  46. package/bin/SshWorkspace.d.ts +31 -0
  47. package/bin/SshWorkspace.d.ts.map +1 -0
  48. package/bin/SshWorkspace.js +121 -0
  49. package/bin/SshWorkspace.js.map +1 -0
  50. package/bin/index.d.ts +8 -0
  51. package/bin/index.d.ts.map +1 -0
  52. package/bin/index.js +6 -0
  53. package/bin/index.js.map +1 -0
  54. package/bin/types/Ssh.d.ts +133 -0
  55. package/bin/types/Ssh.d.ts.map +1 -0
  56. package/bin/types/Ssh.js +2 -0
  57. package/bin/types/Ssh.js.map +1 -0
  58. package/bin/types/SshDirectory.d.ts +44 -0
  59. package/bin/types/SshDirectory.d.ts.map +1 -0
  60. package/bin/types/SshDirectory.js +2 -0
  61. package/bin/types/SshDirectory.js.map +1 -0
  62. package/package.json +35 -3
  63. package/README.md +0 -3
@@ -0,0 +1,507 @@
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, time
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 info_version(info):
81
+ return '%s:%s:%s:%s:%s' % (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
82
+
83
+ def current_version(value):
84
+ try:
85
+ with open_file(value) as stream: return info_version(os.fstat(stream.fileno()))
86
+ except FileNotFoundError: return None
87
+
88
+ def changed_file():
89
+ fail('file_changed', 'Read this file again, review its content, then retry with the latest version. Do not overwrite to bypass a conflict.')
90
+
91
+ def write_atomic(value, content, overwrite=True, expected=None, expected_version=None):
92
+ descriptor, name = parent(value, True)
93
+ if name == '.': fail('invalid_path', 'Cannot replace Workspace root')
94
+ temporary_name = '.downcity-' + os.urandom(16).hex()
95
+ try:
96
+ # 父目录锁协调本适配器的写事务,完整内容只在同目录原子替换时可见。
97
+ fcntl.flock(descriptor, fcntl.LOCK_EX)
98
+ mode = 0o666
99
+ exists = False
100
+ try:
101
+ info = os.stat(name, dir_fd=descriptor, follow_symlinks=False)
102
+ if not stat.S_ISREG(info.st_mode): fail('not_a_file', 'Expected a regular file')
103
+ exists = True
104
+ mode = stat.S_IMODE(info.st_mode)
105
+ except FileNotFoundError: pass
106
+ if exists and not overwrite: fail('file_exists', 'File already exists; use overwrite=true')
107
+ if expected == 'missing' and exists: fail('file_changed', 'File was created before commit')
108
+ if expected not in [None, 'missing'] and (not exists or hashlib.sha256(read_bytes(value)).hexdigest() != expected): fail('file_changed', 'File changed before commit')
109
+ temporary_fd = os.open(temporary_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode, dir_fd=descriptor)
110
+ with os.fdopen(temporary_fd, 'wb') as stream:
111
+ stream.write(content)
112
+ stream.flush()
113
+ os.fsync(stream.fileno())
114
+ if exists: os.fchmod(stream.fileno(), mode)
115
+ # 临时文件落盘后、提交前复核;外部编辑器不遵循工具锁,仍不构成 OS CAS。
116
+ if expected_version and current_version(value) != expected_version: changed_file()
117
+ if expected == 'missing' and current_version(value) is not None: changed_file()
118
+ if expected not in [None, 'missing'] and hashlib.sha256(read_bytes(value)).hexdigest() != expected: changed_file()
119
+ if overwrite:
120
+ os.rename(temporary_name, name, src_dir_fd=descriptor, dst_dir_fd=descriptor)
121
+ else:
122
+ os.link(temporary_name, name, src_dir_fd=descriptor, dst_dir_fd=descriptor, follow_symlinks=False)
123
+ os.unlink(temporary_name, dir_fd=descriptor)
124
+ committed_version = info_version(os.fstat(stream.fileno()))
125
+ try: os.fsync(descriptor)
126
+ except OSError as error:
127
+ if error.errno != errno.EINVAL: raise
128
+ return exists, committed_version
129
+ finally:
130
+ try: os.unlink(temporary_name, dir_fd=descriptor)
131
+ except FileNotFoundError: pass
132
+ os.close(descriptor)
133
+
134
+ def remove_entry(descriptor, name):
135
+ info = os.stat(name, dir_fd=descriptor, follow_symlinks=False)
136
+ if stat.S_ISDIR(info.st_mode):
137
+ child_fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=descriptor)
138
+ try:
139
+ for entry in os.listdir(child_fd): remove_entry(child_fd, entry)
140
+ finally: os.close(child_fd)
141
+ os.rmdir(name, dir_fd=descriptor)
142
+ else: os.unlink(name, dir_fd=descriptor)
143
+
144
+ def text_encoding(content):
145
+ if content.startswith(b'\xff\xfe'): return 'utf-16le', 'utf-16-le', 2
146
+ if content.startswith(b'\xfe\xff'): return 'utf-16be', 'utf-16-be', 2
147
+ return 'utf-8', 'utf-8', 3 if content.startswith(b'\xef\xbb\xbf') else 0
148
+
149
+ def raw_line(stream, limit, encoding):
150
+ if encoding == 'utf-8': return stream.readline(limit)
151
+ content = bytearray()
152
+ newline = b'\n\x00' if encoding == 'utf-16-le' else b'\x00\n'
153
+ while len(content) + 2 <= limit:
154
+ unit = stream.read(2)
155
+ if not unit: break
156
+ content.extend(unit)
157
+ if unit == newline: break
158
+ return bytes(content)
159
+
160
+ def file_action():
161
+ value = arguments['input']['file_path']
162
+ absolute = os.path.join(root, relative(value))
163
+ lock_root = os.path.join(tempfile.gettempdir(), 'downcity-file-actions-' + str(os.getuid()))
164
+ os.makedirs(lock_root, mode=0o700, exist_ok=True)
165
+ lock_path = os.path.join(lock_root, hashlib.sha256(absolute.encode('utf-8')).hexdigest() + '.flock')
166
+ # 固定 inode 的 flock,进程退出自动释放;锁文件不能 unlink,避免出现两把锁。
167
+ descriptor = os.open(lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
168
+ try:
169
+ deadline = time.monotonic() + 10
170
+ while True:
171
+ try:
172
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
173
+ break
174
+ except BlockingIOError:
175
+ if time.monotonic() >= deadline: fail('internal_error', 'Remote file tool lock timed out')
176
+ time.sleep(0.02)
177
+ if os.path.join(root, relative(value)) != absolute: changed_file()
178
+ result = file_action_unlocked()
179
+ if result.get('file_version') != current_version(value): changed_file()
180
+ return result
181
+ finally: os.close(descriptor)
182
+
183
+ def file_action_unlocked():
184
+ action = arguments['action']
185
+ data = arguments['input']
186
+ allowed = {'read': {'file_path', 'range'}, 'write': {'file_path', 'content', 'overwrite', 'expected_version'}, 'edit': {'file_path', 'edits', 'expected_version'}}
187
+ if action not in allowed or set(data) - allowed[action]: fail('invalid_path', 'Invalid file action input fields')
188
+ if data.get('expected_version') is not None and (not isinstance(data['expected_version'], str) or not data['expected_version']): fail('invalid_path', 'expected_version must be a non-empty file_version')
189
+ value = data['file_path']
190
+ absolute = os.path.join(root, relative(value))
191
+ if action == 'read':
192
+ with open_file(value) as stream:
193
+ info = os.fstat(stream.fileno())
194
+ version = '%s:%s:%s:%s:%s' % (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
195
+ selection = data.get('range') or {'type': 'lines'}
196
+ if selection.get('expected_version') and selection['expected_version'] != version: fail('file_changed', 'File changed; read from the beginning')
197
+ sample = stream.read(8192)
198
+ encoding_name, encoding, bom_size = text_encoding(sample)
199
+ binary = sample.startswith(b'%PDF-') or (encoding == 'utf-8' and b'\x00' in sample)
200
+ try: codecs.getincrementaldecoder(encoding)().decode(sample[bom_size:], final=False)
201
+ except UnicodeDecodeError: binary = True
202
+ if binary:
203
+ 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)
204
+ stream.seek(bom_size)
205
+ start = max(0, int(selection.get('offset', 0)))
206
+ byte_mode = selection['type'] == 'bytes'
207
+ limit = min(2000, max(1, int(selection.get('limit', 500))))
208
+ newline = b'\n' if encoding == 'utf-8' else b'\n\x00' if encoding == 'utf-16-le' else b'\x00\n'
209
+ if byte_mode:
210
+ if encoding != 'utf-8' and start % 2: fail('encoding_error', 'UTF-16 byte offset must be aligned')
211
+ stream.seek(max(start, bom_size))
212
+ else:
213
+ for index in range(start):
214
+ skipped = raw_line(stream, MAX_WINDOW, encoding)
215
+ if not skipped: break
216
+ while skipped and not skipped.endswith(newline):
217
+ skipped = raw_line(stream, MAX_WINDOW, encoding)
218
+ if stream.tell() > MAX_FILE: fail('file_too_large', 'Line scan exceeds 64 MiB; use byte continuation')
219
+ if stream.tell() > MAX_FILE: fail('file_too_large', 'Line scan exceeds 64 MiB; use byte continuation')
220
+ start_byte = stream.tell()
221
+ output = b''
222
+ count = 0
223
+ while count < (2000 if byte_mode else limit) and len(output) < MAX_WINDOW:
224
+ chunk = raw_line(stream, MAX_WINDOW - len(output), encoding)
225
+ if not chunk: break
226
+ output += chunk
227
+ count += 1
228
+ # 增量解码器保留被截断的字符尾部,游标只推进已经披露的原始字节。
229
+ try:
230
+ decoder = codecs.getincrementaldecoder(encoding)()
231
+ text = decoder.decode(output, final=stream.tell() >= info.st_size)
232
+ remaining = decoder.getstate()[0]
233
+ if remaining: output = output[:-len(remaining)]
234
+ except UnicodeDecodeError: fail('encoding_error', 'Text contains invalid encoded characters')
235
+ # 输出预算按 UTF-8 文本字节计算;UTF-16 的 CJK 文本不能放大到超过披露上限。
236
+ encoded_text = text.encode('utf-8')
237
+ if len(encoded_text) > MAX_WINDOW:
238
+ budget_decoder = codecs.getincrementaldecoder('utf-8')()
239
+ text = budget_decoder.decode(encoded_text[:MAX_WINDOW], final=False)
240
+ output = text.encode(encoding)
241
+ next_byte = start_byte + len(output)
242
+ 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')
243
+ truncated = next_byte < info.st_size
244
+ 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)
245
+ if truncated: result['next_byte_offset'] = next_byte
246
+ if not truncated and start_byte == bom_size: result['sha256'] = hashlib.sha256(sample[:bom_size] + output).hexdigest()
247
+ return result
248
+ if action == 'write':
249
+ content = data['content'].encode('utf-8')
250
+ if len(content) > MAX_WRITE: fail('content_too_large', 'Write exceeds 1 MiB')
251
+ previous_version = current_version(value)
252
+ if previous_version is not None and not data.get('overwrite', False): fail('file_exists', 'File already exists; use overwrite=true')
253
+ if previous_version is not None and (not data.get('expected_version') or data['expected_version'] != previous_version): changed_file()
254
+ if previous_version is None and data.get('expected_version'): changed_file()
255
+ overwritten, committed_version = write_atomic(value, content, data.get('overwrite', False), None if previous_version else 'missing', previous_version)
256
+ 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(), file_version=committed_version, sha256=hashlib.sha256(content).hexdigest())
257
+ previous_version = current_version(value)
258
+ if not data.get('expected_version') or data['expected_version'] != previous_version: changed_file()
259
+ original = read_bytes(value)
260
+ if current_version(value) != previous_version: changed_file()
261
+ previous_sha = hashlib.sha256(original).hexdigest()
262
+ _, encoding, bom_size = text_encoding(original)
263
+ if encoding == 'utf-8' and b'\x00' in original: fail('binary_file', 'Cannot edit binary content')
264
+ text = original[bom_size:].decode(encoding)
265
+ edits = data['edits']
266
+ if not edits: fail('no_edits', 'edits must not be empty')
267
+ if len(edits) > 10: fail('too_many_edits', 'At most ten edits')
268
+ regions, details = [], []
269
+ for index, edit in enumerate(edits):
270
+ old, new = edit['old_text'], edit['new_text']
271
+ if not old or len(old) > 10000 or len(new) > 50000: fail('edit_too_large', 'Invalid edit size')
272
+ count, position = 0, 0
273
+ while True:
274
+ position = text.find(old, position)
275
+ if position < 0: break
276
+ count += 1
277
+ position += 1
278
+ if count != 1: fail('duplicate_match' if count else 'not_found', 'Each old_text must match exactly once')
279
+ begin = text.index(old)
280
+ regions.append((begin, begin + len(old), new))
281
+ details.append(dict(index=index, status='applied', match_count=1, line_start=text[:begin].count('\n')))
282
+ regions.sort()
283
+ if any(regions[index][1] > regions[index + 1][0] for index in range(len(regions) - 1)): fail('overlapping_edits', 'Edit regions overlap')
284
+ for begin, end, new in reversed(regions): text = text[:begin] + new + text[end:]
285
+ content = original[:bom_size] + text.encode(encoding)
286
+ if len(content) > MAX_FILE: fail('content_too_large', 'Edited file exceeds 64 MiB')
287
+ _, committed_version = write_atomic(value, content, True, previous_sha, previous_version)
288
+ return dict(success=True, file_path=absolute, applied=len(edits), details=details, new_total_lines=len(text.splitlines()), file_version=committed_version, previous_sha256=previous_sha, sha256=hashlib.sha256(content).hexdigest())
289
+
290
+ def search_action():
291
+ action, data = arguments['action'], arguments['input']
292
+ value = relative(data.get('path', '.'))
293
+ limit = min(2000, max(1, int(data.get('max_results', 200))))
294
+ descriptor, name = parent(value)
295
+ results, scanned, output_bytes, truncated = [], 0, 0, False
296
+ directory = None
297
+ try:
298
+ info = os.stat(name, dir_fd=descriptor, follow_symlinks=False)
299
+ if stat.S_ISDIR(info.st_mode):
300
+ directory = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=descriptor)
301
+ os.fchdir(directory)
302
+ candidate_command = ['rg', '--files', '--hidden', '--null']
303
+ if action == 'find': candidate_command.extend(['-g', data['pattern']])
304
+ else:
305
+ for pattern in data.get('glob', []): candidate_command.extend(['-g', pattern])
306
+ candidate_command.extend(['--', '.'])
307
+ process = subprocess.Popen(candidate_command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
308
+ try:
309
+ pending = b''
310
+ candidates = []
311
+ candidate_bytes = 0
312
+ while True:
313
+ chunk = process.stdout.read(16384)
314
+ if not chunk: break
315
+ pending += chunk
316
+ candidate_bytes += len(chunk)
317
+ if candidate_bytes > 2 * 1024 * 1024:
318
+ truncated = True
319
+ process.kill()
320
+ break
321
+ parts = pending.split(b'\x00')
322
+ pending = parts.pop()
323
+ candidates.extend(parts)
324
+ process.wait()
325
+ if process.returncode not in [0, 1] and not truncated: fail('search_failed', 'ripgrep file discovery failed')
326
+ finally:
327
+ if process.poll() is None: process.kill()
328
+ process.wait()
329
+ candidates = [os.path.normpath(os.path.join(value, item.decode('utf-8'))) for item in candidates]
330
+ elif stat.S_ISREG(info.st_mode) and action == 'grep': candidates = [value]
331
+ else: fail('not_a_directory', 'Search path must be a directory')
332
+ os.fchdir(root_fd)
333
+ for candidate in candidates:
334
+ # rg 只发现名称;真正读取使用 rooted openat,拒绝搜索期间被替换的越界符号链接。
335
+ try:
336
+ with open_file(candidate) as stream:
337
+ file_size = os.fstat(stream.fileno()).st_size
338
+ if action == 'find':
339
+ results.append(candidate)
340
+ if len(results) > limit:
341
+ truncated = True
342
+ break
343
+ continue
344
+ if file_size > MAX_FILE: continue
345
+ command = ['rg', '--json', '--max-count', str(limit), '--max-columns', '4096']
346
+ if not data.get('case_sensitive', False): command.append('-i')
347
+ if data.get('literal', True): command.append('-F')
348
+ command.extend(['--', data['query'], '-'])
349
+ # 已校验的描述符直接作为 rg stdin,不按名称再次打开项目文件。
350
+ search = subprocess.Popen(command, stdin=stream, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
351
+ scanned += 1
352
+ try:
353
+ while True:
354
+ line = search.stdout.readline(2 * 1024 * 1024 + 1)
355
+ if not line: break
356
+ output_bytes += len(line)
357
+ if output_bytes > 2 * 1024 * 1024:
358
+ truncated = True
359
+ break
360
+ record = json.loads(line)
361
+ if record['type'] != 'match': continue
362
+ item = record['data']
363
+ for match in item['submatches']:
364
+ 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))
365
+ if len(results) > limit:
366
+ truncated = True
367
+ break
368
+ if truncated: break
369
+ if truncated: search.kill()
370
+ search.wait()
371
+ if search.returncode not in [0, 1] and not truncated: fail('invalid_pattern', 'ripgrep rejected the query')
372
+ finally:
373
+ if search.poll() is None: search.kill()
374
+ search.wait()
375
+ if truncated: break
376
+ except (FileNotFoundError, PermissionError): continue
377
+ finally:
378
+ os.close(descriptor)
379
+ if directory is not None: os.close(directory)
380
+ base = dict(success=True, root_path=root, search_path=os.path.join(root, value), match_count=min(limit, len(results)), truncated=truncated)
381
+ if action == 'find': base.update(pattern=data['pattern'], files=sorted(results[:limit]))
382
+ else: base.update(query=data['query'], matches=results[:limit], files_searched=scanned)
383
+ return base
384
+
385
+ def dispatch():
386
+ value = arguments.get('path', '.')
387
+ if operation == 'validate':
388
+ if sys.version_info < (3, 8): fail('internal_error', 'SSH Workspace needs Python 3.8+; run SSH Workspace dependency initialization')
389
+ if sys.platform not in ['linux', 'darwin']: fail('internal_error', 'Only Linux/macOS SSH hosts are supported')
390
+ if shutil.which('ps') is None: fail('internal_error', 'SSH Workspace needs POSIX ps for process cleanup; run SSH Workspace dependency initialization')
391
+ if shutil.which('rg') is None: fail('rg_unavailable', 'SSH Workspace needs ripgrep (rg); run SSH Workspace dependency initialization')
392
+ if not os.access(root, os.R_OK | os.X_OK): fail('permission_denied', 'Remote directory is not readable')
393
+ 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})
394
+ if operation == 'canonical_path': return os.path.join(root, relative(value))
395
+ if operation == 'file_action': return file_action()
396
+ if operation == 'search_action': return search_action()
397
+ if operation == 'media':
398
+ with open_file(value) as stream:
399
+ info = os.fstat(stream.fileno())
400
+ version = '%s:%s:%s:%s:%s' % (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
401
+ if version != arguments['expected_version']: fail('file_changed', 'Media changed before content capture')
402
+ if info.st_size > 2 * 1024 * 1024: fail('media_too_large', 'Media exceeds 2 MiB')
403
+ content = stream.read(2 * 1024 * 1024 + 1)
404
+ after = os.fstat(stream.fileno())
405
+ 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')
406
+ return base64.b64encode(content).decode('ascii')
407
+ if operation == 'stat': return metadata(value)
408
+ if operation == 'read': return base64.b64encode(read_bytes(value)).decode('ascii')
409
+ if operation == 'read_bounded':
410
+ maximum = arguments.get('max_bytes')
411
+ if not isinstance(maximum, int) or maximum < 1 or maximum > 8 * 1024 * 1024: fail('invalid_path', 'Invalid resource budget')
412
+ with open_file(value) as stream:
413
+ info = os.fstat(stream.fileno())
414
+ if not stat.S_ISREG(info.st_mode) or info.st_size > maximum: fail('file_too_large', 'Resource is not a bounded regular file')
415
+ content = stream.read(maximum + 1)
416
+ if len(content) != info.st_size or len(content) > maximum: fail('file_changed', 'Resource changed during reading')
417
+ return base64.b64encode(content).decode('ascii')
418
+ if operation == 'list':
419
+ descriptor, name = parent(value)
420
+ try:
421
+ directory = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=descriptor)
422
+ try:
423
+ result = []
424
+ for item in os.scandir(directory):
425
+ if len(result) >= 10000: fail('file_too_large', 'Directory exceeds 10000 entries')
426
+ info = item.stat(follow_symlinks=False)
427
+ if stat.S_ISLNK(info.st_mode): continue
428
+ 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))
429
+ return result
430
+ finally: os.close(directory)
431
+ finally: os.close(descriptor)
432
+ if operation == 'mkdir':
433
+ descriptor, name = parent(os.path.join(value, '.downcity-directory-marker'), True)
434
+ os.close(descriptor)
435
+ return None
436
+ if operation == 'write':
437
+ content = base64.b64decode(arguments['content'])
438
+ if len(content) > MAX_FILE: fail('content_too_large', 'Write exceeds 64 MiB')
439
+ write_atomic(value, content)
440
+ return None
441
+ if operation == 'append':
442
+ try:
443
+ original = read_bytes(value)
444
+ expected = hashlib.sha256(original).hexdigest()
445
+ except FileNotFoundError:
446
+ original = b''
447
+ expected = 'missing'
448
+ content = original + base64.b64decode(arguments['content'])
449
+ if len(content) > MAX_FILE: fail('content_too_large', 'Append exceeds 64 MiB')
450
+ write_atomic(value, content, True, expected)
451
+ return None
452
+ if operation == 'remove':
453
+ descriptor, name = parent(value)
454
+ try:
455
+ if name == '.': fail('invalid_path', 'Cannot delete Workspace root')
456
+ try: remove_entry(descriptor, name)
457
+ except FileNotFoundError: pass
458
+ finally: os.close(descriptor)
459
+ return None
460
+ if operation == 'move':
461
+ source_fd, source_name = parent(value)
462
+ target_fd, target_name = parent(arguments['target'])
463
+ try:
464
+ if source_name == '.' or target_name == '.': fail('invalid_path', 'Cannot move Workspace root')
465
+ try:
466
+ os.stat(target_name, dir_fd=target_fd, follow_symlinks=False)
467
+ fail('file_exists', 'Move target exists')
468
+ except FileNotFoundError: pass
469
+ # 内核原子 no-replace;不能用先检查再 rename 的窗口覆盖外部新文件。
470
+ library = ctypes.CDLL(None, use_errno=True)
471
+ if sys.platform == 'linux':
472
+ rename = library.renameat2
473
+ flag = 1
474
+ else:
475
+ rename = library.renameatx_np
476
+ flag = 4
477
+ rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]
478
+ rename.restype = ctypes.c_int
479
+ if rename(source_fd, os.fsencode(source_name), target_fd, os.fsencode(target_name), flag) != 0:
480
+ error = ctypes.get_errno()
481
+ raise OSError(error, os.strerror(error))
482
+ finally:
483
+ os.close(source_fd)
484
+ os.close(target_fd)
485
+ return None
486
+ fail('internal_error', 'Unknown remote operation')
487
+
488
+ def cancel_request(*unused):
489
+ raise InterruptedError('SSH channel closed; operation result may be unknown')
490
+ signal.signal(signal.SIGHUP, cancel_request)
491
+ signal.signal(signal.SIGTERM, cancel_request)
492
+
493
+ try:
494
+ result = dispatch()
495
+ print(json.dumps({'ok': True, 'result': result}, ensure_ascii=True))
496
+ except Exception as error:
497
+ code = 'internal_error'
498
+ if isinstance(error, FileNotFoundError): code = 'file_not_found'
499
+ elif isinstance(error, FileExistsError): code = 'file_exists'
500
+ elif isinstance(error, OSError) and error.errno == errno.ELOOP: code = 'sandbox_denied'
501
+ elif isinstance(error, PermissionError): code = 'permission_denied'
502
+ elif isinstance(error, UnicodeError): code = 'encoding_error'
503
+ elif isinstance(error, ValueError): code = str(error).split(':', 1)[0]
504
+ print(json.dumps({'ok': False, 'code': code, 'message': str(error)}, ensure_ascii=True))
505
+ finally: os.close(root_fd)
506
+ `;
507
+ //# 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAofxC,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** 临时远端命令监督进程:通道 EOF 或取消时终止子进程组;不安装远程服务。 */
2
+ export declare const remote_shell_program: string;
3
+ //# sourceMappingURL=RemoteShellProgram.d.ts.map
@@ -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"}