dsh-remote-deck 0.0.0-stage → 1.46.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.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +227 -2
  3. package/README.zh-CN.md +201 -0
  4. package/client.js +8645 -0
  5. package/cordis.patch.yml +6 -0
  6. package/icon.svg +19 -0
  7. package/index.js +701 -0
  8. package/lib/api.js +1452 -0
  9. package/lib/bash-result.js +93 -0
  10. package/lib/connection.js +1133 -0
  11. package/lib/delete.js +199 -0
  12. package/lib/drafts.js +299 -0
  13. package/lib/encoding.js +247 -0
  14. package/lib/file-edit.js +339 -0
  15. package/lib/file-ops.js +402 -0
  16. package/lib/forwards.js +186 -0
  17. package/lib/fs-actions.js +235 -0
  18. package/lib/guide.js +162 -0
  19. package/lib/metrics.js +523 -0
  20. package/lib/remote-shells.js +320 -0
  21. package/lib/remote-terminal.js +427 -0
  22. package/lib/routing.js +695 -0
  23. package/lib/ssh-config.js +118 -0
  24. package/lib/terminal.js +123 -0
  25. package/lib/tool-forward.js +185 -0
  26. package/lib/transfer.js +235 -0
  27. package/lib/upload-chunks.js +306 -0
  28. package/lib/util.js +154 -0
  29. package/locale/README.md +160 -0
  30. package/locale/en-ui.json +477 -0
  31. package/locale/en.json +6 -0
  32. package/locale/zh.json +6 -0
  33. package/package.json +63 -4
  34. package/vendor/codemirror/LICENSE +21 -0
  35. package/vendor/codemirror/README.md +18 -0
  36. package/vendor/codemirror/addon/edit/closebrackets.min.js +8 -0
  37. package/vendor/codemirror/addon/edit/matchbrackets.min.js +8 -0
  38. package/vendor/codemirror/addon/search/search.min.js +8 -0
  39. package/vendor/codemirror/addon/search/searchcursor.min.js +8 -0
  40. package/vendor/codemirror/addon/selection/active-line.min.js +8 -0
  41. package/vendor/codemirror/lib/codemirror.css +344 -0
  42. package/vendor/codemirror/lib/codemirror.min.js +8 -0
  43. package/vendor/codemirror/mode/clike/clike.min.js +8 -0
  44. package/vendor/codemirror/mode/css/css.min.js +8 -0
  45. package/vendor/codemirror/mode/go/go.min.js +8 -0
  46. package/vendor/codemirror/mode/htmlmixed/htmlmixed.min.js +8 -0
  47. package/vendor/codemirror/mode/javascript/javascript.min.js +8 -0
  48. package/vendor/codemirror/mode/markdown/markdown.min.js +8 -0
  49. package/vendor/codemirror/mode/python/python.min.js +8 -0
  50. package/vendor/codemirror/mode/rust/rust.min.js +8 -0
  51. package/vendor/codemirror/mode/shell/shell.min.js +8 -0
  52. package/vendor/codemirror/mode/xml/xml.min.js +8 -0
  53. package/vendor/codemirror/mode/yaml/yaml.min.js +8 -0
  54. package/vendor/node_modules/asn1/Jenkinsfile +65 -0
  55. package/vendor/node_modules/asn1/LICENSE +19 -0
  56. package/vendor/node_modules/asn1/README.md +50 -0
  57. package/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
  58. package/vendor/node_modules/asn1/lib/ber/index.js +27 -0
  59. package/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
  60. package/vendor/node_modules/asn1/lib/ber/types.js +36 -0
  61. package/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
  62. package/vendor/node_modules/asn1/lib/index.js +20 -0
  63. package/vendor/node_modules/asn1/package.json +31 -0
  64. package/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
  65. package/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
  66. package/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
  67. package/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
  68. package/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
  69. package/vendor/node_modules/safer-buffer/LICENSE +21 -0
  70. package/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
  71. package/vendor/node_modules/safer-buffer/Readme.md +156 -0
  72. package/vendor/node_modules/safer-buffer/dangerous.js +58 -0
  73. package/vendor/node_modules/safer-buffer/package.json +34 -0
  74. package/vendor/node_modules/safer-buffer/safer.js +77 -0
  75. package/vendor/node_modules/safer-buffer/tests.js +406 -0
  76. package/vendor/node_modules/ssh2/LICENSE +19 -0
  77. package/vendor/node_modules/ssh2/README.md +1529 -0
  78. package/vendor/node_modules/ssh2/SFTP.md +413 -0
  79. package/vendor/node_modules/ssh2/lib/Channel.js +295 -0
  80. package/vendor/node_modules/ssh2/lib/agent.js +1123 -0
  81. package/vendor/node_modules/ssh2/lib/client.js +2176 -0
  82. package/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
  83. package/vendor/node_modules/ssh2/lib/index.js +44 -0
  84. package/vendor/node_modules/ssh2/lib/keygen.js +582 -0
  85. package/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
  86. package/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
  87. package/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
  88. package/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
  89. package/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
  90. package/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
  91. package/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
  92. package/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
  93. package/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
  94. package/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
  95. package/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
  96. package/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
  97. package/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
  98. package/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
  99. package/vendor/node_modules/ssh2/lib/server.js +1380 -0
  100. package/vendor/node_modules/ssh2/lib/utils.js +336 -0
  101. package/vendor/node_modules/ssh2/package.json +49 -0
  102. package/vendor/node_modules/tweetnacl/AUTHORS.md +28 -0
  103. package/vendor/node_modules/tweetnacl/CHANGELOG.md +221 -0
  104. package/vendor/node_modules/tweetnacl/LICENSE +24 -0
  105. package/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
  106. package/vendor/node_modules/tweetnacl/README.md +459 -0
  107. package/vendor/node_modules/tweetnacl/nacl-fast.js +2388 -0
  108. package/vendor/node_modules/tweetnacl/nacl-fast.min.js +2 -0
  109. package/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
  110. package/vendor/node_modules/tweetnacl/nacl.js +1175 -0
  111. package/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
  112. package/vendor/node_modules/tweetnacl/package.json +58 -0
  113. package/vendor/xterm/LICENSE.addon-fit +19 -0
  114. package/vendor/xterm/LICENSE.xterm +21 -0
  115. package/vendor/xterm/README.md +9 -0
  116. package/vendor/xterm/addon-fit.js +2 -0
  117. package/vendor/xterm/xterm.css +218 -0
  118. package/vendor/xterm/xterm.js +2 -0
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Text encodings and line endings, so an editor never rewrites bytes it did not
3
+ * intend to touch.
4
+ *
5
+ * Reading is free: the running Node ships a full ICU, so `TextDecoder` knows
6
+ * GB18030, GBK, Big5, Shift_JIS and the rest. Writing is not: `Buffer.from`
7
+ * only encodes UTF-8 and Latin-1, and a file that was decoded as GBK must be
8
+ * saved back as GBK or the Chinese text becomes mojibake. `gbkReverseTable`
9
+ * builds that encoder by walking the decoder once, which keeps the plugin free
10
+ * of a bundled codec dependency.
11
+ *
12
+ * The contract the editor relies on: decode tells you the exact `encoding` and
13
+ * `eol` it used, and encode refuses anything it cannot reproduce byte for byte
14
+ * rather than silently falling back to UTF-8.
15
+ */
16
+
17
+ export const ENCODING_UTF8 = 'utf-8'
18
+ export const ENCODING_GB18030 = 'gb18030'
19
+ export const ENCODING_BIG5 = 'big5'
20
+ export const ENCODING_SHIFT_JIS = 'shift_jis'
21
+ export const ENCODING_UTF16LE = 'utf-16le'
22
+ export const ENCODING_UTF16BE = 'utf-16be'
23
+
24
+ /** Every encoding a read may answer with; a write must name one of these. */
25
+ export const EDIT_ENCODINGS = Object.freeze([
26
+ ENCODING_UTF8,
27
+ ENCODING_GB18030,
28
+ ENCODING_BIG5,
29
+ ENCODING_SHIFT_JIS,
30
+ ENCODING_UTF16LE,
31
+ ENCODING_UTF16BE,
32
+ ])
33
+
34
+ /** Legacy decoders tried after strict UTF-8 fails, in order of likelihood. */
35
+ const LEGACY_DECODERS = Object.freeze([ENCODING_GB18030, ENCODING_BIG5, ENCODING_SHIFT_JIS])
36
+
37
+ export const EOL_LF = 'lf'
38
+ export const EOL_CRLF = 'crlf'
39
+
40
+ export const EDIT_BAD_ENCODING_CODE = 'UNSUPPORTED_ENCODING'
41
+
42
+ /**
43
+ * Which EOL the buffer predominantly uses.
44
+ *
45
+ * Mixed files report the majority so a save normalises instead of dropping
46
+ * lines, and `mixed` tells the editor to warn instead of pretending the file
47
+ * was uniform.
48
+ */
49
+ export function detectEol(text) {
50
+ let crlf = 0
51
+ let lf = 0
52
+ for (let index = 0; index < text.length; index += 1) {
53
+ if (text.charCodeAt(index) !== 10) continue
54
+ if (index > 0 && text.charCodeAt(index - 1) === 13) crlf += 1
55
+ else lf += 1
56
+ }
57
+ const total = crlf + lf
58
+ if (total === 0) return { eol: EOL_LF, mixed: false, crlf, lf }
59
+ return { eol: crlf > lf ? EOL_CRLF : EOL_LF, mixed: crlf > 0 && lf > 0, crlf, lf }
60
+ }
61
+
62
+ /** Decode strictly; `null` means these bytes are not valid in that encoding. */
63
+ function decodeStrict(buffer, encoding) {
64
+ try {
65
+ return new TextDecoder(encoding, { fatal: true }).decode(buffer)
66
+ } catch {
67
+ return null
68
+ }
69
+ }
70
+
71
+ function decodeLenient(buffer, encoding) {
72
+ try {
73
+ return new TextDecoder(encoding, { fatal: false }).decode(buffer)
74
+ } catch {
75
+ return null
76
+ }
77
+ }
78
+
79
+ function startsWith(buffer, bytes) {
80
+ if (buffer.length < bytes.length) return false
81
+ for (let index = 0; index < bytes.length; index += 1) {
82
+ if (buffer[index] !== bytes[index]) return false
83
+ }
84
+ return true
85
+ }
86
+
87
+ /**
88
+ * Decide how to read these bytes.
89
+ *
90
+ * Only a strict UTF-8 decode (or a BOM) is trusted, and only that result is
91
+ * writable. The reason is that GB18030 accepts nearly every two-byte pair, so
92
+ * "it decoded as GB18030" is not evidence: a Big5 or Shift_JIS file passes that
93
+ * test too, and treating the guess as reliable is exactly how an editor rewrites
94
+ * one legacy file as another. Anything short of UTF-8 comes back as a named
95
+ * guess with `exact: false`, which the client shows read-only until the reader
96
+ * says which encoding it actually is (`decodeText(buffer, { encoding })`).
97
+ *
98
+ * @param {Buffer} buffer the bytes in the read window
99
+ * @param {{ encoding?: string }} [options] an encoding the reader chose explicitly
100
+ * @returns {{ encoding: string, text: string, exact: boolean }}
101
+ */
102
+ export function decodeText(buffer, options = {}) {
103
+ const chosen = typeof options.encoding === 'string' ? options.encoding.toLowerCase() : ''
104
+ if (chosen.length > 0) {
105
+ const text = decodeStrict(buffer, chosen)
106
+ if (text !== null) return { encoding: chosen, text, exact: true }
107
+ // An explicit choice that does not decode is still the best guess available.
108
+ const lenient = decodeLenient(buffer, chosen)
109
+ return { encoding: chosen, text: lenient === null ? '' : lenient, exact: false }
110
+ }
111
+ if (startsWith(buffer, [0xef, 0xbb, 0xbf])) {
112
+ const text = decodeStrict(buffer.subarray(3), ENCODING_UTF8)
113
+ if (text !== null) return { encoding: ENCODING_UTF8, text, exact: true }
114
+ }
115
+ if (startsWith(buffer, [0xff, 0xfe])) {
116
+ const text = decodeStrict(buffer.subarray(2), ENCODING_UTF16LE)
117
+ if (text !== null) return { encoding: ENCODING_UTF16LE, text, exact: true }
118
+ }
119
+ if (startsWith(buffer, [0xfe, 0xff])) {
120
+ const text = decodeStrict(buffer.subarray(2), ENCODING_UTF16BE)
121
+ if (text !== null) return { encoding: ENCODING_UTF16BE, text, exact: true }
122
+ }
123
+ const utf8 = decodeStrict(buffer, ENCODING_UTF8)
124
+ if (utf8 !== null) return { encoding: ENCODING_UTF8, text: utf8, exact: true }
125
+ // Not UTF-8. Offer GB18030's reading because it is by far the most likely
126
+ // answer on a Chinese server, but keep `exact: false`: the reader has to
127
+ // confirm the encoding before anything may be written.
128
+ const guessed = decodeLenient(buffer, ENCODING_GB18030)
129
+ return { encoding: ENCODING_GB18030, text: guessed === null ? '' : guessed, exact: false }
130
+ }
131
+
132
+ /**
133
+ * A GBK/GB18030 reverse table, built once by driving the decoder.
134
+ *
135
+ * GB18030's four-byte range is deliberately not walked: it costs over a million
136
+ * decodes and only covers rare CJK extensions, and a character missing from this
137
+ * table makes the save fail loudly instead of writing the wrong glyph.
138
+ */
139
+ let gbkReverse = null
140
+
141
+ function gbkTable() {
142
+ if (gbkReverse !== null) return gbkReverse
143
+ const decoder = new TextDecoder(ENCODING_GB18030, { fatal: true })
144
+ const table = new Map()
145
+ const pair = new Uint8Array(2)
146
+ for (let lead = 0x81; lead <= 0xfe; lead += 1) {
147
+ for (let trail = 0x40; trail <= 0xfe; trail += 1) {
148
+ if (trail === 0x7f) continue
149
+ pair[0] = lead
150
+ pair[1] = trail
151
+ let char = null
152
+ try {
153
+ char = decoder.decode(pair)
154
+ } catch {
155
+ continue
156
+ }
157
+ if (char.length !== 1 || char === '\ufffd') continue
158
+ if (!table.has(char)) table.set(char, [lead, trail])
159
+ }
160
+ }
161
+ for (let code = 0; code < 0x80; code += 1) table.set(String.fromCharCode(code), [code])
162
+ gbkReverse = table
163
+ return table
164
+ }
165
+
166
+ /** Exposed for tests: the number of characters this encoder can reproduce. */
167
+ export function gbkTableSize() {
168
+ return gbkTable().size
169
+ }
170
+
171
+ function encodeGbk(text) {
172
+ const table = gbkTable()
173
+ const out = Buffer.allocUnsafe(text.length * 2)
174
+ let written = 0
175
+ for (const char of text) {
176
+ const bytes = table.get(char)
177
+ if (bytes === undefined) {
178
+ return { ok: false, char }
179
+ }
180
+ for (const byte of bytes) {
181
+ out[written] = byte
182
+ written += 1
183
+ }
184
+ }
185
+ return { ok: true, buffer: out.subarray(0, written) }
186
+ }
187
+
188
+ /**
189
+ * Encode text for a save, using the encoding the read reported.
190
+ *
191
+ * @returns {{ ok: true, buffer: Buffer } | { ok: false, code: string, message: string }}
192
+ */
193
+ export function encodeText(text, encoding) {
194
+ const name = typeof encoding === 'string' ? encoding.toLowerCase() : ''
195
+ if (!EDIT_ENCODINGS.includes(name)) {
196
+ return {
197
+ ok: false,
198
+ code: EDIT_BAD_ENCODING_CODE,
199
+ message: 'Refusing to save without a known encoding: ' + String(encoding),
200
+ }
201
+ }
202
+ if (name === ENCODING_UTF8) return { ok: true, buffer: Buffer.from(text, 'utf8') }
203
+ if (name === ENCODING_UTF16LE) return { ok: true, buffer: Buffer.from(text, 'utf16le') }
204
+ if (name === ENCODING_UTF16BE) {
205
+ const little = Buffer.from(text, 'utf16le')
206
+ const big = Buffer.allocUnsafe(little.length)
207
+ for (let index = 0; index + 1 < little.length; index += 2) {
208
+ big[index] = little[index + 1]
209
+ big[index + 1] = little[index]
210
+ }
211
+ return { ok: true, buffer: big }
212
+ }
213
+ if (name === ENCODING_GB18030) {
214
+ const encoded = encodeGbk(text)
215
+ if (encoded.ok === true) return { ok: true, buffer: encoded.buffer }
216
+ return {
217
+ ok: false,
218
+ code: EDIT_BAD_ENCODING_CODE,
219
+ message: 'This character cannot be written as GBK: ' + JSON.stringify(encoded.char),
220
+ }
221
+ }
222
+ // Big5 and Shift_JIS have no reverse table; saving would need a codec the
223
+ // plugin does not bundle, so the editor keeps those files read-only.
224
+ return {
225
+ ok: false,
226
+ code: EDIT_BAD_ENCODING_CODE,
227
+ message: 'Saving ' + name + ' is not supported yet; the file is read-only.',
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Apply the EOL the read reported, so a CRLF file keeps its CRLFs.
233
+ *
234
+ * The editor always hands over LF text (that is what the browser and CodeMirror
235
+ * normalise to); the file's own convention is restored here.
236
+ */
237
+ export function applyEol(text, eol) {
238
+ const normalised = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
239
+ if (eol === EOL_CRLF) return normalised.replace(/\n/g, '\r\n')
240
+ return normalised
241
+ }
242
+
243
+ /** True when this encoding can be written back (and so may be edited). */
244
+ export function canWriteEncoding(encoding) {
245
+ const name = typeof encoding === 'string' ? encoding.toLowerCase() : ''
246
+ return name === ENCODING_UTF8 || name === ENCODING_UTF16LE || name === ENCODING_UTF16BE || name === ENCODING_GB18030
247
+ }
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Read and write one remote text file, for the plugin's own editor.
3
+ *
4
+ * DSH's built-in file preview is read-only ("Preview, not editing."), so
5
+ * double-clicking a file has to be served here.
6
+ *
7
+ * Decisions worth knowing:
8
+ *
9
+ * - **A read is bounded.** The default window is 2 MiB and nothing reads more
10
+ * than 8 MiB; a longer file answers with `truncated: true` and the text of the
11
+ * window it did read, which is what the browser half turns into "too large,
12
+ * saving disabled".
13
+ * - **Binary is decided by a NUL byte** in the window that was read: such a file
14
+ * answers without `text` at all. Invalid UTF-8 is never an error — Node's
15
+ * decoder substitutes U+FFFD, so a stray byte cannot fail the request.
16
+ * - **A write never truncates the original in place.** The content goes to a
17
+ * sibling temp file first and is then renamed over the target (the same
18
+ * `replaceRemoteFile` the plugin's `ctx.fs` patch uses, with the OpenSSH
19
+ * posix-rename extension when the server offers it), so a failed save leaves
20
+ * the previous content untouched. The temp file is removed either way.
21
+ * - **`expectedMtime` is a conflict check**, not a lock: a mismatch answers
22
+ * `STALE` with the current mtime and writes nothing.
23
+ * - Cancellation (the client aborted the request) is asked before every
24
+ * operation and while a read is streaming.
25
+ */
26
+ import { posix } from 'node:path'
27
+ import { applyEol, canWriteEncoding, decodeText, detectEol, ENCODING_UTF8, encodeText, EOL_LF } from './encoding.js'
28
+ import { canonicalRemotePath, entryKind, isPlainRemotePath } from './file-ops.js'
29
+ import { replaceRemoteFile } from './routing.js'
30
+ import { sftpCall } from './util.js'
31
+
32
+ /** Window read when the request asks for nothing. */
33
+ export const READ_DEFAULT_MAX_BYTES = 8 * 1024 * 1024
34
+ /** Hard ceiling for one read, whatever the request asks for. */
35
+ export const READ_MAX_BYTES = 32 * 1024 * 1024
36
+ /** Largest content one write may carry. */
37
+ export const WRITE_MAX_BYTES = 8 * 1024 * 1024
38
+
39
+ export const EDIT_INVALID_CODE = 'NOT_REMOTE_PATH'
40
+ export const EDIT_NOT_FILE_CODE = 'NOT_REGULAR_FILE'
41
+ export const EDIT_MISSING_CODE = 'NOT_FOUND'
42
+ export const EDIT_TOO_LARGE_CODE = 'TOO_LARGE'
43
+ export const EDIT_STALE_CODE = 'STALE'
44
+ export const EDIT_CANCELLED_CODE = 'REMOTE_DECK_EDIT_CANCELLED'
45
+
46
+ const FS_NOT_FOUND = 'FS_NOT_FOUND'
47
+ const SFTP_NO_SUCH_FILE = 2
48
+
49
+ function coded(code, message) {
50
+ const error = new Error(message)
51
+ error.code = code
52
+ return error
53
+ }
54
+
55
+ function refuse(code, message) {
56
+ return { ok: false, code, message }
57
+ }
58
+
59
+ function isMissing(error) {
60
+ return Boolean(error) && (error.code === FS_NOT_FOUND || error.code === SFTP_NO_SUCH_FILE)
61
+ }
62
+
63
+ function errorText(error) {
64
+ return error instanceof Error ? error.message : String(error)
65
+ }
66
+
67
+ /** The request was cancelled by the client going away. */
68
+ export function isEditCancelled(error) {
69
+ return Boolean(error) && error.code === EDIT_CANCELLED_CODE
70
+ }
71
+
72
+ /** ssh2 reports mtime in seconds; the browser half works in milliseconds. */
73
+ export function mtimeMsOf(attrs) {
74
+ const seconds = Number(attrs?.mtime)
75
+ return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1000) : 0
76
+ }
77
+
78
+ /** Size of an attrs record, missing or nonsense values folded to 0. */
79
+ function sizeOf(attrs) {
80
+ const size = Number(attrs?.size)
81
+ return Number.isFinite(size) && size > 0 ? Math.floor(size) : 0
82
+ }
83
+
84
+ /**
85
+ * Validate one remote file path.
86
+ *
87
+ * Reuses the file page's rules: absolute POSIX, no `..`, no `//`, and something
88
+ * left to name. The parent is not checked here — a missing directory is a
89
+ * write failure, not a malformed request.
90
+ *
91
+ * @param {unknown} value
92
+ * @returns {{ ok: true, path: string } | { ok: false, code: string, message: string }}
93
+ */
94
+ export function parseFileTarget(value) {
95
+ if (!isPlainRemotePath(value)) return refuse(EDIT_INVALID_CODE, 'A remote POSIX file path is required.')
96
+ const path = canonicalRemotePath(value)
97
+ if (posix.basename(path) === '') return refuse(EDIT_INVALID_CODE, 'Cannot edit that path.')
98
+ return { ok: true, path }
99
+ }
100
+
101
+ /**
102
+ * The read window: default when absent or nonsense, capped at
103
+ * {@link READ_MAX_BYTES} when larger.
104
+ */
105
+ export function parseReadLimit(value) {
106
+ const requested = typeof value === 'number' ? value : Number(value)
107
+ if (!Number.isFinite(requested) || requested <= 0) return READ_DEFAULT_MAX_BYTES
108
+ return Math.min(READ_MAX_BYTES, Math.floor(requested))
109
+ }
110
+
111
+ /**
112
+ * Validate a write body.
113
+ *
114
+ * @param {unknown} body parsed JSON body
115
+ * @returns {{ ok: true, path: string, content: string, expectedMtime?: number } | { ok: false, code: string, message: string }}
116
+ */
117
+ export function parseWriteRequest(body) {
118
+ const source = body !== null && typeof body === 'object' ? body : {}
119
+ const target = parseFileTarget(source.path)
120
+ if (target.ok !== true) return target
121
+ if (typeof source.content !== 'string') return refuse(EDIT_INVALID_CODE, 'Content must be a string.')
122
+ if (Buffer.byteLength(source.content, 'utf8') > WRITE_MAX_BYTES) {
123
+ return refuse(EDIT_TOO_LARGE_CODE, `Content is larger than ${Math.round(WRITE_MAX_BYTES / 1024 / 1024)} MB.`)
124
+ }
125
+ const expectedMtime = typeof source.expectedMtime === 'number' && Number.isFinite(source.expectedMtime)
126
+ ? Math.round(source.expectedMtime)
127
+ : undefined
128
+ // The encoding and line ending are optional for compatibility with older
129
+ // callers, which get UTF-8/LF — the behaviour before encodings existed. A
130
+ // client that read a GBK file must name it here or the save would be wrong.
131
+ const encoding = typeof source.encoding === 'string' ? source.encoding.toLowerCase() : ''
132
+ const eol = source.eol === 'crlf' ? 'crlf' : source.eol === 'lf' ? 'lf' : ''
133
+ return {
134
+ ok: true,
135
+ path: target.path,
136
+ content: source.content,
137
+ expectedMtime,
138
+ encoding: encoding.length > 0 ? encoding : undefined,
139
+ eol: eol.length > 0 ? eol : undefined,
140
+ }
141
+ }
142
+
143
+ /** Collect at most `length` bytes from the first `length` bytes of a file. */
144
+ function readBytes({ sftp, path, length, guard, isCancelled }) {
145
+ return new Promise((resolve, reject) => {
146
+ let settled = false
147
+ let stream = null
148
+ const finish = (error, value) => {
149
+ if (settled) return
150
+ settled = true
151
+ try {
152
+ stream?.destroy()
153
+ } catch {
154
+ /* already gone */
155
+ }
156
+ if (error === null || error === undefined) resolve(value)
157
+ else reject(error)
158
+ }
159
+ try {
160
+ stream = sftp.createReadStream(path, { start: 0, end: length - 1 })
161
+ } catch (error) {
162
+ finish(error)
163
+ return
164
+ }
165
+ const chunks = []
166
+ stream.on('data', (chunk) => {
167
+ if (settled) return
168
+ if (isCancelled()) {
169
+ finish(coded(EDIT_CANCELLED_CODE, 'The read was cancelled.'))
170
+ return
171
+ }
172
+ chunks.push(Buffer.from(chunk))
173
+ })
174
+ stream.on('error', (error) => finish(error))
175
+ stream.on('end', () => finish(null, Buffer.concat(chunks)))
176
+ stream.on('close', () => finish(null, Buffer.concat(chunks)))
177
+ })
178
+ }
179
+
180
+ /**
181
+ * Read one remote text file.
182
+ *
183
+ * @param {object} input
184
+ * @param {object} input.sftp connected SFTP session
185
+ * @param {unknown} input.path requested remote path
186
+ * @param {unknown} [input.maxBytes] requested window
187
+ * @param {() => boolean} [input.isCancelled] asked before every operation
188
+ * @param {Function} [input.call] `sftpCall`, injectable for tests
189
+ * @returns {Promise<{ ok: true, file: object } | { ok: false, code: string, message: string }>}
190
+ * @throws a coded `REMOTE_DECK_EDIT_CANCELLED` when the client is gone
191
+ */
192
+ export async function readRemoteFile({ sftp, path, maxBytes, encoding, isCancelled, call } = {}) {
193
+ const invoke = typeof call === 'function' ? call : sftpCall
194
+ const cancelled = typeof isCancelled === 'function' ? isCancelled : () => false
195
+ const guard = () => {
196
+ if (cancelled()) throw coded(EDIT_CANCELLED_CODE, 'The read was cancelled.')
197
+ }
198
+
199
+ const target = parseFileTarget(path)
200
+ if (target.ok !== true) return target
201
+
202
+ guard()
203
+ let attrs
204
+ try {
205
+ // `stat`, so a link to a file is edited through the link, like every editor.
206
+ attrs = await invoke(sftp, 'stat', target.path)
207
+ } catch (error) {
208
+ if (isMissing(error)) return refuse(EDIT_MISSING_CODE, 'No such remote path.')
209
+ throw error
210
+ }
211
+ if (entryKind(attrs) !== 'file') return refuse(EDIT_NOT_FILE_CODE, 'Only a regular file can be read.')
212
+
213
+ const size = sizeOf(attrs)
214
+ const mtime = mtimeMsOf(attrs)
215
+ const window = Math.min(size, parseReadLimit(maxBytes))
216
+ const truncated = size > window
217
+ if (window === 0) {
218
+ return {
219
+ ok: true,
220
+ file: {
221
+ path: target.path, size, mtime, text: '', truncated, binary: false,
222
+ encoding: ENCODING_UTF8, exact: true, writable: true, eol: EOL_LF, mixedEol: false,
223
+ },
224
+ }
225
+ }
226
+ guard()
227
+ const buffer = await readBytes({ sftp, path: target.path, length: window, guard, isCancelled: cancelled })
228
+ // A NUL byte in the window is the binary signal; the rest of the file is
229
+ // never inspected, which is what keeps an 8 MiB read bounded.
230
+ if (buffer.includes(0)) return { ok: true, file: { binary: true, size, mtime } }
231
+ const decoded = decodeText(buffer, { encoding: typeof encoding === 'string' && encoding.length > 0 ? encoding : undefined })
232
+ const eol = detectEol(decoded.text)
233
+ // A window that cut the file in half can end mid-character, so an exact
234
+ // decode is only promised for a complete read; a truncated read keeps its
235
+ // encoding but is never writable.
236
+ const writable = decoded.exact === true && truncated !== true && canWriteEncoding(decoded.encoding)
237
+ return {
238
+ ok: true,
239
+ file: {
240
+ path: target.path,
241
+ size,
242
+ mtime,
243
+ text: decoded.text,
244
+ truncated,
245
+ binary: false,
246
+ encoding: decoded.encoding,
247
+ exact: decoded.exact === true,
248
+ writable,
249
+ eol: eol.eol,
250
+ mixedEol: eol.mixed,
251
+ },
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Write one remote text file.
257
+ *
258
+ * @param {object} input
259
+ * @param {object} input.sftp connected SFTP session
260
+ * @param {string} input.path already validated absolute path
261
+ * @param {string} input.content already validated string
262
+ * @param {number} [input.expectedMtime] mtime the editor loaded, in milliseconds
263
+ * @param {string} [input.encoding] the encoding the read reported; UTF-8 by default
264
+ * @param {string} [input.eol] `lf` or `crlf`; the file's own convention wins
265
+ * @param {() => boolean} [input.isCancelled] asked before every operation
266
+ * @param {Function} [input.call] `sftpCall`, injectable for tests
267
+ * @returns {Promise<{ ok: true, file: { size: number, mtime: number } } | { ok: false, code: string, message: string, mtime?: number | null }>}
268
+ * @throws a coded `REMOTE_DECK_EDIT_CANCELLED` when the client is gone
269
+ */
270
+ export async function writeRemoteFile({ sftp, path, content, expectedMtime, encoding, eol, isCancelled, call } = {}) {
271
+ const invoke = typeof call === 'function' ? call : sftpCall
272
+ const cancelled = typeof isCancelled === 'function' ? isCancelled : () => false
273
+ const guard = () => {
274
+ if (cancelled()) throw coded(EDIT_CANCELLED_CODE, 'The write was cancelled.')
275
+ }
276
+
277
+ guard()
278
+ let current = null
279
+ try {
280
+ current = await invoke(sftp, 'stat', path)
281
+ } catch (error) {
282
+ if (!isMissing(error)) throw error
283
+ }
284
+ if (current !== null && entryKind(current) !== 'file') {
285
+ return refuse(EDIT_NOT_FILE_CODE, 'Only a regular file can be written.')
286
+ }
287
+ const mtime = current === null ? null : mtimeMsOf(current)
288
+ if (expectedMtime !== undefined && (current === null || mtime !== expectedMtime)) {
289
+ return {
290
+ ok: false,
291
+ code: EDIT_STALE_CODE,
292
+ message: current === null
293
+ ? 'The file is no longer there.'
294
+ : 'The file changed on the remote host since it was read.',
295
+ mtime,
296
+ }
297
+ }
298
+
299
+ // The client must say which encoding it read; guessing here is what turns a
300
+ // GBK file into mojibake.
301
+ const targetEncoding = typeof encoding === 'string' && encoding.length > 0 ? encoding : ENCODING_UTF8
302
+ const encoded = encodeText(applyEol(content, eol), targetEncoding)
303
+ if (encoded.ok !== true) return refuse(encoded.code, encoded.message)
304
+ const buffer = encoded.buffer
305
+
306
+ // Saving through a symlink must not replace the link with a regular file: the
307
+ // bytes belong to the target, so resolve it first. `realpath` answers for a
308
+ // live link; a dangling one is resolved by hand, which creates the file it
309
+ // points at instead of clobbering the link.
310
+ let written = path
311
+ try {
312
+ const real = await invoke(sftp, 'realpath', path)
313
+ if (typeof real === 'string' && real.length > 0) written = real
314
+ } catch {
315
+ const link = await invoke(sftp, 'readlink', path).catch(() => null)
316
+ if (typeof link === 'string' && link.length > 0) {
317
+ written = posix.isAbsolute(link) ? link : posix.join(posix.dirname(path), link)
318
+ }
319
+ }
320
+
321
+ const temp = posix.join(posix.dirname(written), `.dsh-tmp-${Date.now()}-${Math.random().toString(16).slice(2)}`)
322
+ guard()
323
+ await invoke(sftp, 'writeFile', temp, buffer)
324
+ try {
325
+ guard()
326
+ await replaceRemoteFile(sftp, temp, written, buffer)
327
+ } catch (error) {
328
+ if (isEditCancelled(error)) throw error
329
+ throw coded('REMOTE_DECK_EDIT_WRITE_FAILED', errorText(error))
330
+ } finally {
331
+ await invoke(sftp, 'unlink', temp).catch(() => {})
332
+ }
333
+
334
+ guard()
335
+ const after = await invoke(sftp, 'stat', written)
336
+ const file = { size: sizeOf(after), mtime: mtimeMsOf(after) }
337
+ if (written !== path) file.wroteThrough = written
338
+ return { ok: true, file }
339
+ }