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.
- package/LICENSE +21 -0
- package/README.md +227 -2
- package/README.zh-CN.md +201 -0
- package/client.js +8645 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +19 -0
- package/index.js +701 -0
- package/lib/api.js +1452 -0
- package/lib/bash-result.js +93 -0
- package/lib/connection.js +1133 -0
- package/lib/delete.js +199 -0
- package/lib/drafts.js +299 -0
- package/lib/encoding.js +247 -0
- package/lib/file-edit.js +339 -0
- package/lib/file-ops.js +402 -0
- package/lib/forwards.js +186 -0
- package/lib/fs-actions.js +235 -0
- package/lib/guide.js +162 -0
- package/lib/metrics.js +523 -0
- package/lib/remote-shells.js +320 -0
- package/lib/remote-terminal.js +427 -0
- package/lib/routing.js +695 -0
- package/lib/ssh-config.js +118 -0
- package/lib/terminal.js +123 -0
- package/lib/tool-forward.js +185 -0
- package/lib/transfer.js +235 -0
- package/lib/upload-chunks.js +306 -0
- package/lib/util.js +154 -0
- package/locale/README.md +160 -0
- package/locale/en-ui.json +477 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +63 -4
- package/vendor/codemirror/LICENSE +21 -0
- package/vendor/codemirror/README.md +18 -0
- package/vendor/codemirror/addon/edit/closebrackets.min.js +8 -0
- package/vendor/codemirror/addon/edit/matchbrackets.min.js +8 -0
- package/vendor/codemirror/addon/search/search.min.js +8 -0
- package/vendor/codemirror/addon/search/searchcursor.min.js +8 -0
- package/vendor/codemirror/addon/selection/active-line.min.js +8 -0
- package/vendor/codemirror/lib/codemirror.css +344 -0
- package/vendor/codemirror/lib/codemirror.min.js +8 -0
- package/vendor/codemirror/mode/clike/clike.min.js +8 -0
- package/vendor/codemirror/mode/css/css.min.js +8 -0
- package/vendor/codemirror/mode/go/go.min.js +8 -0
- package/vendor/codemirror/mode/htmlmixed/htmlmixed.min.js +8 -0
- package/vendor/codemirror/mode/javascript/javascript.min.js +8 -0
- package/vendor/codemirror/mode/markdown/markdown.min.js +8 -0
- package/vendor/codemirror/mode/python/python.min.js +8 -0
- package/vendor/codemirror/mode/rust/rust.min.js +8 -0
- package/vendor/codemirror/mode/shell/shell.min.js +8 -0
- package/vendor/codemirror/mode/xml/xml.min.js +8 -0
- package/vendor/codemirror/mode/yaml/yaml.min.js +8 -0
- package/vendor/node_modules/asn1/Jenkinsfile +65 -0
- package/vendor/node_modules/asn1/LICENSE +19 -0
- package/vendor/node_modules/asn1/README.md +50 -0
- package/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
- package/vendor/node_modules/asn1/lib/ber/index.js +27 -0
- package/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
- package/vendor/node_modules/asn1/lib/ber/types.js +36 -0
- package/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
- package/vendor/node_modules/asn1/lib/index.js +20 -0
- package/vendor/node_modules/asn1/package.json +31 -0
- package/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
- package/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
- package/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
- package/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
- package/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
- package/vendor/node_modules/safer-buffer/LICENSE +21 -0
- package/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
- package/vendor/node_modules/safer-buffer/Readme.md +156 -0
- package/vendor/node_modules/safer-buffer/dangerous.js +58 -0
- package/vendor/node_modules/safer-buffer/package.json +34 -0
- package/vendor/node_modules/safer-buffer/safer.js +77 -0
- package/vendor/node_modules/safer-buffer/tests.js +406 -0
- package/vendor/node_modules/ssh2/LICENSE +19 -0
- package/vendor/node_modules/ssh2/README.md +1529 -0
- package/vendor/node_modules/ssh2/SFTP.md +413 -0
- package/vendor/node_modules/ssh2/lib/Channel.js +295 -0
- package/vendor/node_modules/ssh2/lib/agent.js +1123 -0
- package/vendor/node_modules/ssh2/lib/client.js +2176 -0
- package/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
- package/vendor/node_modules/ssh2/lib/index.js +44 -0
- package/vendor/node_modules/ssh2/lib/keygen.js +582 -0
- package/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
- package/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
- package/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
- package/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
- package/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
- package/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
- package/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
- package/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
- package/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
- package/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
- package/vendor/node_modules/ssh2/lib/server.js +1380 -0
- package/vendor/node_modules/ssh2/lib/utils.js +336 -0
- package/vendor/node_modules/ssh2/package.json +49 -0
- package/vendor/node_modules/tweetnacl/AUTHORS.md +28 -0
- package/vendor/node_modules/tweetnacl/CHANGELOG.md +221 -0
- package/vendor/node_modules/tweetnacl/LICENSE +24 -0
- package/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
- package/vendor/node_modules/tweetnacl/README.md +459 -0
- package/vendor/node_modules/tweetnacl/nacl-fast.js +2388 -0
- package/vendor/node_modules/tweetnacl/nacl-fast.min.js +2 -0
- package/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
- package/vendor/node_modules/tweetnacl/nacl.js +1175 -0
- package/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
- package/vendor/node_modules/tweetnacl/package.json +58 -0
- package/vendor/xterm/LICENSE.addon-fit +19 -0
- package/vendor/xterm/LICENSE.xterm +21 -0
- package/vendor/xterm/README.md +9 -0
- package/vendor/xterm/addon-fit.js +2 -0
- package/vendor/xterm/xterm.css +218 -0
- package/vendor/xterm/xterm.js +2 -0
package/lib/api.js
ADDED
|
@@ -0,0 +1,1452 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loopback JSON API used by the browser half.
|
|
3
|
+
*
|
|
4
|
+
* The server binds an ephemeral port on 127.0.0.1 and requires a per-session
|
|
5
|
+
* token, injected into the page by the host half. No terminal or file endpoint
|
|
6
|
+
* is reachable without it.
|
|
7
|
+
*/
|
|
8
|
+
import http from 'node:http'
|
|
9
|
+
import { spawn } from 'node:child_process'
|
|
10
|
+
import { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
11
|
+
import { homedir } from 'node:os'
|
|
12
|
+
import { extname, join as joinPath, posix, resolve, sep } from 'node:path'
|
|
13
|
+
import {
|
|
14
|
+
MAX_TRANSFER_BYTES,
|
|
15
|
+
ensureRemoteDir,
|
|
16
|
+
errorText,
|
|
17
|
+
normalizeRemotePath,
|
|
18
|
+
readJsonFile,
|
|
19
|
+
safeRemoteName,
|
|
20
|
+
sftpCall,
|
|
21
|
+
writeJsonFile,
|
|
22
|
+
} from './util.js'
|
|
23
|
+
import {
|
|
24
|
+
DELETE_MISSING_CODE,
|
|
25
|
+
DELETE_ROOT_CODE,
|
|
26
|
+
emptyDeleteCounts,
|
|
27
|
+
isDeleteCancelled,
|
|
28
|
+
isDeleteMissing,
|
|
29
|
+
isProtectedDeleteRoot,
|
|
30
|
+
parseDeleteTarget,
|
|
31
|
+
removeRemoteTree,
|
|
32
|
+
} from './delete.js'
|
|
33
|
+
import {
|
|
34
|
+
EDIT_MISSING_CODE,
|
|
35
|
+
EDIT_STALE_CODE,
|
|
36
|
+
WRITE_MAX_BYTES,
|
|
37
|
+
isEditCancelled,
|
|
38
|
+
parseWriteRequest,
|
|
39
|
+
readRemoteFile,
|
|
40
|
+
writeRemoteFile,
|
|
41
|
+
} from './file-edit.js'
|
|
42
|
+
import { transferRemotePaths } from './file-ops.js'
|
|
43
|
+
import {
|
|
44
|
+
FS_ACTION_BAD_NAME_CODE,
|
|
45
|
+
FS_ACTION_EXISTS_CODE,
|
|
46
|
+
FS_ACTION_INVALID_PATH_CODE,
|
|
47
|
+
FS_ACTION_MISSING_CODE,
|
|
48
|
+
mkdirRemotePath,
|
|
49
|
+
parseNameRequest,
|
|
50
|
+
renameRemotePath,
|
|
51
|
+
touchRemotePath,
|
|
52
|
+
} from './fs-actions.js'
|
|
53
|
+
import { DRAFT_DIR_NAME, DraftStore, parseDraftPath, parseDraftWrite } from './drafts.js'
|
|
54
|
+
import {
|
|
55
|
+
UPLOAD_BAD_OFFSET_CODE,
|
|
56
|
+
UPLOAD_EMPTY_PART_CODE,
|
|
57
|
+
UPLOAD_EXISTS_CODE,
|
|
58
|
+
UPLOAD_MISSING_CODE,
|
|
59
|
+
UPLOAD_OFFSET_MISMATCH_CODE,
|
|
60
|
+
UPLOAD_PART_MAX_BYTES,
|
|
61
|
+
UPLOAD_PART_TOO_LARGE_CODE,
|
|
62
|
+
abortUpload,
|
|
63
|
+
commitUpload,
|
|
64
|
+
parseUploadOffset,
|
|
65
|
+
parseUploadTarget,
|
|
66
|
+
readUploadStatus,
|
|
67
|
+
writeUploadPart,
|
|
68
|
+
} from './upload-chunks.js'
|
|
69
|
+
import { archiveCommand, archivePathsCommand, parseScanOutput, scanCommand } from './transfer.js'
|
|
70
|
+
import { MetricsManager, migrateSettings, normalizeMonitorConfig, normalizeSettings } from './metrics.js'
|
|
71
|
+
|
|
72
|
+
const TOKEN_HEADER = 'x-dsh-remote-token'
|
|
73
|
+
const DOWNLOAD_ROOT = joinPath(homedir(), 'Downloads', 'Remote Deck')
|
|
74
|
+
// The remote scan is time-boxed on both ends: `timeout` on the far side and
|
|
75
|
+
// this abort, which covers a remote that has no `timeout` at all.
|
|
76
|
+
const SCAN_TIMEOUT_MS = 20000
|
|
77
|
+
const SCAN_MAX_BYTES = 256 * 1024
|
|
78
|
+
/** How many selected paths one archive request may carry. */
|
|
79
|
+
const ARCHIVE_MAX_PATHS = 200
|
|
80
|
+
/** Every JSON route but the editor's save stays under this. */
|
|
81
|
+
const JSON_BODY_LIMIT = 131072
|
|
82
|
+
// JSON escaping can inflate text (a quote or a control character costs six
|
|
83
|
+
// bytes), so the editor's 8 MiB of content gets room to arrive intact.
|
|
84
|
+
const WRITE_BODY_LIMIT = WRITE_MAX_BYTES * 6 + 65536
|
|
85
|
+
/** The HTTP meaning of every `lib/fs-actions.js` refusal. */
|
|
86
|
+
const FS_ACTION_STATUS = Object.freeze({
|
|
87
|
+
[FS_ACTION_INVALID_PATH_CODE]: 400,
|
|
88
|
+
[FS_ACTION_BAD_NAME_CODE]: 400,
|
|
89
|
+
[FS_ACTION_MISSING_CODE]: 404,
|
|
90
|
+
[FS_ACTION_EXISTS_CODE]: 409,
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
/** The HTTP meaning of every `lib/upload-chunks.js` refusal. */
|
|
94
|
+
const UPLOAD_ROUTE_STATUS = Object.freeze({
|
|
95
|
+
[UPLOAD_BAD_OFFSET_CODE]: 400,
|
|
96
|
+
[UPLOAD_EMPTY_PART_CODE]: 400,
|
|
97
|
+
[UPLOAD_PART_TOO_LARGE_CODE]: 400,
|
|
98
|
+
[UPLOAD_OFFSET_MISMATCH_CODE]: 409,
|
|
99
|
+
[UPLOAD_EXISTS_CODE]: 409,
|
|
100
|
+
[UPLOAD_MISSING_CODE]: 404,
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Every CodeMirror file the file editor may load, by exact path inside
|
|
105
|
+
* `vendor/codemirror`. The editor's imports and this list are edited together:
|
|
106
|
+
* a file that is not named here is not reachable from the page at all.
|
|
107
|
+
*/
|
|
108
|
+
export const CODEMIRROR_ASSET_FILES = Object.freeze([
|
|
109
|
+
'lib/codemirror.min.js',
|
|
110
|
+
'lib/codemirror.css',
|
|
111
|
+
'mode/javascript/javascript.min.js',
|
|
112
|
+
'mode/xml/xml.min.js',
|
|
113
|
+
'mode/css/css.min.js',
|
|
114
|
+
'mode/htmlmixed/htmlmixed.min.js',
|
|
115
|
+
'mode/markdown/markdown.min.js',
|
|
116
|
+
'mode/python/python.min.js',
|
|
117
|
+
'mode/shell/shell.min.js',
|
|
118
|
+
'mode/yaml/yaml.min.js',
|
|
119
|
+
'mode/clike/clike.min.js',
|
|
120
|
+
'mode/rust/rust.min.js',
|
|
121
|
+
'mode/go/go.min.js',
|
|
122
|
+
'addon/edit/closebrackets.min.js',
|
|
123
|
+
'addon/edit/matchbrackets.min.js',
|
|
124
|
+
'addon/search/search.min.js',
|
|
125
|
+
'addon/search/searchcursor.min.js',
|
|
126
|
+
'addon/selection/active-line.min.js',
|
|
127
|
+
])
|
|
128
|
+
|
|
129
|
+
const MIME = {
|
|
130
|
+
'.md': 'text/markdown; charset=utf-8',
|
|
131
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
132
|
+
'.json': 'application/json; charset=utf-8',
|
|
133
|
+
'.png': 'image/png',
|
|
134
|
+
'.jpg': 'image/jpeg',
|
|
135
|
+
'.jpeg': 'image/jpeg',
|
|
136
|
+
'.gif': 'image/gif',
|
|
137
|
+
'.webp': 'image/webp',
|
|
138
|
+
'.svg': 'image/svg+xml',
|
|
139
|
+
'.pdf': 'application/pdf',
|
|
140
|
+
'.zip': 'application/zip',
|
|
141
|
+
'.tgz': 'application/gzip',
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function mimeFor(name) {
|
|
145
|
+
return MIME[extname(name).toLowerCase()] || 'application/octet-stream'
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* The display kind of one directory entry: dir, link, fifo, socket, char, block
|
|
150
|
+
* or file.
|
|
151
|
+
*
|
|
152
|
+
* The POSIX type bits decide first — a real host reports them for everything,
|
|
153
|
+
* while ssh2's predicates are not reliable for every type: measured against ws,
|
|
154
|
+
* a unix socket (`mode` 140775) and a block device (`mode` 060660) both report
|
|
155
|
+
* `isSocket()`/`isBlockDevice()` false and would otherwise be filed as ordinary
|
|
156
|
+
* files. A symlink is never followed: its own bits win, so a link to a directory
|
|
157
|
+
* (or a dangling one) stays a link.
|
|
158
|
+
*
|
|
159
|
+
* The predicate chain remains as the fallback for a server that reports no mode,
|
|
160
|
+
* and anything unrecognised is a plain file.
|
|
161
|
+
*/
|
|
162
|
+
export function entryKind(attrs) {
|
|
163
|
+
const mode = Number(attrs?.mode)
|
|
164
|
+
if (Number.isFinite(mode)) {
|
|
165
|
+
switch (mode & 0o170000) {
|
|
166
|
+
case 0o120000: return 'link'
|
|
167
|
+
case 0o040000: return 'dir'
|
|
168
|
+
case 0o010000: return 'fifo'
|
|
169
|
+
case 0o140000: return 'socket'
|
|
170
|
+
case 0o020000: return 'char'
|
|
171
|
+
case 0o060000: return 'block'
|
|
172
|
+
case 0o100000: return 'file'
|
|
173
|
+
default: break
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const flag = (name) => typeof attrs?.[name] === 'function' && attrs[name]() === true
|
|
177
|
+
if (flag('isSymbolicLink')) return 'link'
|
|
178
|
+
if (flag('isDirectory')) return 'dir'
|
|
179
|
+
if (flag('isFIFO')) return 'fifo'
|
|
180
|
+
if (flag('isSocket')) return 'socket'
|
|
181
|
+
if (flag('isCharacterDevice')) return 'char'
|
|
182
|
+
if (flag('isBlockDevice')) return 'block'
|
|
183
|
+
return 'file'
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function safeLocalName(value) {
|
|
187
|
+
const cleaned = String(value).replace(/[\x00-\x1f<>:"|?*\\]/g, '_').replace(/^[. ]+|[. ]+$/g, '')
|
|
188
|
+
return cleaned.length > 0 && cleaned !== '.' && cleaned !== '..' ? cleaned : 'file'
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function localTarget(root, hostName, remotePath) {
|
|
192
|
+
const hostDir = safeLocalName(hostName || 'host')
|
|
193
|
+
const segments = remotePath
|
|
194
|
+
.split('/')
|
|
195
|
+
.filter((part) => part.length > 0)
|
|
196
|
+
.map(safeLocalName)
|
|
197
|
+
const fileName = segments.pop() || 'file'
|
|
198
|
+
const dir = joinPath(root, hostDir, ...segments)
|
|
199
|
+
mkdirSync(dir, { recursive: true })
|
|
200
|
+
const dot = fileName.lastIndexOf('.')
|
|
201
|
+
const stem = dot > 0 ? fileName.slice(0, dot) : fileName
|
|
202
|
+
const ext = dot > 0 ? fileName.slice(dot) : ''
|
|
203
|
+
let candidate = joinPath(dir, fileName)
|
|
204
|
+
let index = 2
|
|
205
|
+
while (existsSync(candidate)) {
|
|
206
|
+
candidate = joinPath(dir, `${stem} (${index})${ext}`)
|
|
207
|
+
index += 1
|
|
208
|
+
}
|
|
209
|
+
return candidate
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function insideDownloadRoot(candidate) {
|
|
213
|
+
const root = DOWNLOAD_ROOT + sep
|
|
214
|
+
return typeof candidate === 'string' && candidate.startsWith(root)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Only the local DSH page may read loopback API responses. The desktop build
|
|
219
|
+
* serves the app from its custom `dsh-app://app` scheme, so that origin must be
|
|
220
|
+
* accepted alongside loopback HTTP(S); the token still guards every route.
|
|
221
|
+
*/
|
|
222
|
+
export function localOrigin(value) {
|
|
223
|
+
if (typeof value !== 'string' || value.length === 0) return null
|
|
224
|
+
try {
|
|
225
|
+
const url = new URL(value)
|
|
226
|
+
if (url.protocol === 'dsh-app:') return value
|
|
227
|
+
if ((url.protocol === 'http:' || url.protocol === 'https:') && (url.hostname === '127.0.0.1' || url.hostname === 'localhost')) return value
|
|
228
|
+
} catch {
|
|
229
|
+
/* ignore */
|
|
230
|
+
}
|
|
231
|
+
return null
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function createApi({ token, store, secrets, hostFor, dropHost, listHosts, routing, getRegistry, build, dataDir, readSshConfig, testConnection, terminals, forwards, assetDir, assetDirs, diagnostics, homeDir, transferLimitBytes }) {
|
|
235
|
+
// An explicit option wins; otherwise the cap comes from the settings document,
|
|
236
|
+
// read per transfer so a change in Settings applies to the next upload or
|
|
237
|
+
// archive without restarting the Host.
|
|
238
|
+
const configuredTransferLimit = Number.isFinite(transferLimitBytes) && transferLimitBytes > 0
|
|
239
|
+
? Math.floor(transferLimitBytes)
|
|
240
|
+
: null
|
|
241
|
+
const transferLimitNow = () => {
|
|
242
|
+
if (configuredTransferLimit !== null) return configuredTransferLimit
|
|
243
|
+
try {
|
|
244
|
+
const value = readSettings().transfer?.limitBytes
|
|
245
|
+
return Number.isFinite(value) && value > 0 ? Math.floor(value) : MAX_TRANSFER_BYTES
|
|
246
|
+
} catch {
|
|
247
|
+
return MAX_TRANSFER_BYTES
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const transferLimitText = () => `${Math.round(transferLimitNow() / 1024 / 1024)} MB`
|
|
251
|
+
|
|
252
|
+
// Metric probes are cached per connection for a few seconds, so a polling
|
|
253
|
+
// UI cannot hammer a remote host; see lib/metrics.js.
|
|
254
|
+
const metrics = new MetricsManager({
|
|
255
|
+
hostFor,
|
|
256
|
+
onLog: (...args) => {
|
|
257
|
+
if (process.env.DSH_REMOTE_DECK_DEBUG === '1') console.error('[remote-deck]', ...args)
|
|
258
|
+
},
|
|
259
|
+
})
|
|
260
|
+
const monitorFile = typeof dataDir === 'string' && dataDir.length > 0 ? joinPath(dataDir, 'monitor.json') : null
|
|
261
|
+
const settingsFile = typeof dataDir === 'string' && dataDir.length > 0 ? joinPath(dataDir, 'settings.json') : null
|
|
262
|
+
// Editor drafts live beside the settings: one JSON file per connection+path.
|
|
263
|
+
const drafts = new DraftStore({
|
|
264
|
+
dir: typeof dataDir === 'string' && dataDir.length > 0 ? joinPath(dataDir, DRAFT_DIR_NAME) : null,
|
|
265
|
+
})
|
|
266
|
+
// The unified settings document supersedes monitor.json; a data directory
|
|
267
|
+
// that only holds the old file still reads its monitor section back here.
|
|
268
|
+
const readSettings = () =>
|
|
269
|
+
settingsFile === null
|
|
270
|
+
? normalizeSettings(null)
|
|
271
|
+
: migrateSettings(readJsonFile(settingsFile, null), readJsonFile(monitorFile, null))
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* The registered workspace roots of one connection. Deleting exactly one of
|
|
275
|
+
* them is the only delete the browser half asks about twice (`force: true`):
|
|
276
|
+
* a mis-click there would remove the folder the Session itself lives in.
|
|
277
|
+
*/
|
|
278
|
+
const workspaceRootsFor = (connectionId) => {
|
|
279
|
+
try {
|
|
280
|
+
const rows = typeof routing.listWorkspaces === 'function' ? routing.listWorkspaces() : []
|
|
281
|
+
return rows
|
|
282
|
+
.filter((row) => row !== null
|
|
283
|
+
&& typeof row === 'object'
|
|
284
|
+
&& row.connectionId === connectionId
|
|
285
|
+
&& typeof row.path === 'string'
|
|
286
|
+
&& row.path.length > 0)
|
|
287
|
+
.map((row) => row.path)
|
|
288
|
+
} catch {
|
|
289
|
+
return []
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Whether the browser walked away from a request in flight.
|
|
294
|
+
*
|
|
295
|
+
* A POST body is complete — and its IncomingMessage closed — before the
|
|
296
|
+
* handler runs, so `request` itself says nothing about the client. The
|
|
297
|
+
* response (closed unfinished only when the connection went away) and the
|
|
298
|
+
* socket do.
|
|
299
|
+
*/
|
|
300
|
+
const clientGone = (request, response, controller) => () => controller.signal.aborted === true
|
|
301
|
+
|| response.destroyed === true
|
|
302
|
+
|| (request.socket !== null && request.socket !== undefined && request.socket.destroyed === true)
|
|
303
|
+
|
|
304
|
+
/** The connection a flat `/draft` request names, if it names one at all. */
|
|
305
|
+
const flatDraftConnectionId = (body, requestUrl) => {
|
|
306
|
+
const fromBody = body !== null && typeof body === 'object' && typeof body.connectionId === 'string' ? body.connectionId : ''
|
|
307
|
+
return fromBody.length > 0 ? fromBody : requestUrl.searchParams.get('connectionId') || ''
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* One draft request, shared by the flat `/draft` routes and the
|
|
312
|
+
* connection-scoped `/connections/<id>/draft` the editor actually calls.
|
|
313
|
+
*
|
|
314
|
+
* Every visit also sweeps what has aged out, which is the only moment the
|
|
315
|
+
* draft directory is worth looking at.
|
|
316
|
+
*/
|
|
317
|
+
const handleDraft = (connectionId, method, requestUrl, body) => {
|
|
318
|
+
if (drafts.available !== true) return { status: 500, body: { ok: false, message: 'draft storage is unavailable' } }
|
|
319
|
+
drafts.sweep()
|
|
320
|
+
if (method === 'POST') {
|
|
321
|
+
const parsed = parseDraftWrite({ ...body, connectionId })
|
|
322
|
+
if (parsed.ok !== true) return { status: 400, body: { ok: false, code: parsed.code, message: parsed.message } }
|
|
323
|
+
return { status: 200, body: { ok: true, savedAt: drafts.save(parsed.draft).savedAt } }
|
|
324
|
+
}
|
|
325
|
+
if (method !== 'GET' && method !== 'DELETE') return { status: 404, body: { ok: false, message: 'not found' } }
|
|
326
|
+
const requested = requestUrl.searchParams.get('path') ?? (body !== null && typeof body === 'object' ? body.path : undefined)
|
|
327
|
+
const target = parseDraftPath(requested)
|
|
328
|
+
if (target.ok !== true) return { status: 400, body: { ok: false, code: target.code, message: target.message } }
|
|
329
|
+
if (method === 'DELETE') {
|
|
330
|
+
drafts.remove({ connectionId, path: target.path })
|
|
331
|
+
return { status: 200, body: { ok: true } }
|
|
332
|
+
}
|
|
333
|
+
return { status: 200, body: { ok: true, draft: drafts.read({ connectionId, path: target.path }) } }
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Resolve one extra vendor asset by exact relative path.
|
|
338
|
+
*
|
|
339
|
+
* Each root carries its own allow-list and a request must match one entry
|
|
340
|
+
* character for character, so neither `..` nor an absolute name can reach a
|
|
341
|
+
* file outside the directory and an unlisted file is simply not found.
|
|
342
|
+
*/
|
|
343
|
+
const additionalAsset = (name) => {
|
|
344
|
+
const roots = Array.isArray(assetDirs) ? assetDirs : []
|
|
345
|
+
for (const root of roots) {
|
|
346
|
+
if (root === null || typeof root !== 'object') continue
|
|
347
|
+
if (typeof root.dir !== 'string' || !Array.isArray(root.files)) continue
|
|
348
|
+
if (root.files.includes(name)) return { dir: root.dir, name }
|
|
349
|
+
}
|
|
350
|
+
return null
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const handle = async (request, response) => {
|
|
354
|
+
const allowOrigin = localOrigin(request.headers.origin)
|
|
355
|
+
const headers = {
|
|
356
|
+
...(allowOrigin === null ? {} : { 'access-control-allow-origin': allowOrigin, vary: 'Origin' }),
|
|
357
|
+
'access-control-allow-methods': 'GET,POST,DELETE,OPTIONS',
|
|
358
|
+
'access-control-allow-headers': `content-type, ${TOKEN_HEADER}`,
|
|
359
|
+
'access-control-max-age': '600',
|
|
360
|
+
'content-type': 'application/json; charset=utf-8',
|
|
361
|
+
'cache-control': 'no-store',
|
|
362
|
+
}
|
|
363
|
+
const send = (status, body) => {
|
|
364
|
+
response.writeHead(status, headers)
|
|
365
|
+
response.end(JSON.stringify(body))
|
|
366
|
+
}
|
|
367
|
+
if (request.method === 'OPTIONS') {
|
|
368
|
+
response.writeHead(204, headers)
|
|
369
|
+
response.end()
|
|
370
|
+
return
|
|
371
|
+
}
|
|
372
|
+
const url = new URL(request.url || '/', 'http://127.0.0.1')
|
|
373
|
+
const pathname = url.pathname
|
|
374
|
+
// Browser tags cannot send headers, so the streaming GETs accept the token
|
|
375
|
+
// as a query parameter; every JSON route stays header-only.
|
|
376
|
+
const queryToken =
|
|
377
|
+
(pathname.startsWith('/assets/') || pathname.endsWith('/download') || pathname.endsWith('/archive')) &&
|
|
378
|
+
url.searchParams.get('token') === token
|
|
379
|
+
const authorized = request.headers[TOKEN_HEADER] === token || queryToken
|
|
380
|
+
if (!authorized) {
|
|
381
|
+
send(403, { ok: false, message: 'forbidden' })
|
|
382
|
+
return
|
|
383
|
+
}
|
|
384
|
+
try {
|
|
385
|
+
// The whole-file upload and one chunk of a chunked upload stream raw
|
|
386
|
+
// bytes; every other POST carries JSON, and reading that here keeps the
|
|
387
|
+
// route handlers free of body parsing.
|
|
388
|
+
const isRawBody = request.method === 'POST' && (pathname.endsWith('/upload') || pathname.endsWith('/upload/part'))
|
|
389
|
+
const bodyLimit = pathname.endsWith('/write') || pathname === '/draft' ? WRITE_BODY_LIMIT : JSON_BODY_LIMIT
|
|
390
|
+
const body = request.method === 'POST' && !isRawBody ? await readJsonBody(request, bodyLimit) : {}
|
|
391
|
+
|
|
392
|
+
if (request.method === 'GET' && pathname === '/local/download') {
|
|
393
|
+
const requested = String(url.searchParams.get('path') || '')
|
|
394
|
+
const home = typeof homeDir === 'string' ? resolve(homeDir) : ''
|
|
395
|
+
const target = resolve(requested)
|
|
396
|
+
if (home.length === 0 || (target !== home && !target.startsWith(home + sep))) {
|
|
397
|
+
return send(400, { ok: false, code: 'LOCAL_PATH_DENIED', message: 'Path is outside DSH_HOME.' })
|
|
398
|
+
}
|
|
399
|
+
try {
|
|
400
|
+
const info = statSync(target)
|
|
401
|
+
if (!info.isFile()) return send(400, { ok: false, code: 'NOT_A_FILE', message: 'Not a file.' })
|
|
402
|
+
const name = posix.basename(target.replace(/\\/g, '/'))
|
|
403
|
+
response.writeHead(200, {
|
|
404
|
+
'content-type': mimeFor(name),
|
|
405
|
+
'content-length': String(info.size),
|
|
406
|
+
'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
|
|
407
|
+
'cache-control': 'no-store',
|
|
408
|
+
...(allowOrigin === null ? {} : { 'access-control-allow-origin': allowOrigin }),
|
|
409
|
+
})
|
|
410
|
+
const stream = createReadStream(target)
|
|
411
|
+
stream.on('error', () => response.destroy())
|
|
412
|
+
response.on('close', () => stream.destroy())
|
|
413
|
+
stream.pipe(response)
|
|
414
|
+
return
|
|
415
|
+
} catch {
|
|
416
|
+
return send(404, { ok: false, code: 'FS_NOT_FOUND', message: 'No such file.' })
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
if (request.method === 'GET' && pathname.startsWith('/assets/')) {
|
|
421
|
+
const name = pathname.slice('/assets/'.length)
|
|
422
|
+
const vendor = /^(xterm\.js|xterm\.css|addon-fit\.js)$/.test(name) && typeof assetDir === 'string'
|
|
423
|
+
? { dir: assetDir, name }
|
|
424
|
+
: additionalAsset(name)
|
|
425
|
+
if (vendor === null) {
|
|
426
|
+
return send(404, { ok: false, message: 'not found' })
|
|
427
|
+
}
|
|
428
|
+
try {
|
|
429
|
+
const data = readFileSync(posix.join(vendor.dir, vendor.name))
|
|
430
|
+
response.writeHead(200, {
|
|
431
|
+
'content-type': vendor.name.endsWith('.css') ? 'text/css; charset=utf-8' : 'text/javascript; charset=utf-8',
|
|
432
|
+
'cache-control': 'public, max-age=3600',
|
|
433
|
+
...(allowOrigin === null ? {} : { 'access-control-allow-origin': allowOrigin }),
|
|
434
|
+
})
|
|
435
|
+
response.end(data)
|
|
436
|
+
return
|
|
437
|
+
} catch {
|
|
438
|
+
return send(404, { ok: false, message: 'not found' })
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
if (request.method === 'GET' && pathname === '/health') return send(200, { ok: true, build })
|
|
443
|
+
if (request.method === 'POST' && pathname === '/debug/report' && process.env.DSH_REMOTE_DECK_DEBUG === '1') {
|
|
444
|
+
writeFileSync(posix.join(dataDir, 'probe.json'), JSON.stringify(body, null, 2), 'utf8')
|
|
445
|
+
return send(200, { ok: true })
|
|
446
|
+
}
|
|
447
|
+
if (request.method === 'GET' && pathname === '/state') {
|
|
448
|
+
const connections = []
|
|
449
|
+
for (const record of store.list()) connections.push(await connectionView(record))
|
|
450
|
+
const workspaces = routing.listWorkspaces().map((row) => {
|
|
451
|
+
const record = store.get(row.connectionId)
|
|
452
|
+
return {
|
|
453
|
+
...row,
|
|
454
|
+
host: record?.name ?? row.host,
|
|
455
|
+
color: record?.color ?? row.color,
|
|
456
|
+
connected: (hostFor(row.connectionId)?.state ?? 'disconnected') === 'connected',
|
|
457
|
+
}
|
|
458
|
+
})
|
|
459
|
+
const counts = new Map()
|
|
460
|
+
for (const row of workspaces) counts.set(row.connectionId, (counts.get(row.connectionId) ?? 0) + 1)
|
|
461
|
+
return send(200, {
|
|
462
|
+
ok: true,
|
|
463
|
+
ready: true,
|
|
464
|
+
build,
|
|
465
|
+
dataDir,
|
|
466
|
+
connections: connections.map((row) => ({ ...row, workspaceCount: counts.get(row.id) ?? 0 })),
|
|
467
|
+
workspaces,
|
|
468
|
+
forwards: forwards !== undefined ? forwards.list() : [],
|
|
469
|
+
diagnostics: diagnostics ?? null,
|
|
470
|
+
})
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// ---------------------------------------------------- settings
|
|
474
|
+
// The unified settings document (terminal appearance, monitoring and the
|
|
475
|
+
// transfer cap) replaced the monitor-only file. `/monitor` below stays
|
|
476
|
+
// for an older browser half and maps onto `settings.monitor`.
|
|
477
|
+
if (request.method === 'GET' && pathname === '/settings') {
|
|
478
|
+
if (settingsFile === null) return send(500, { ok: false, message: 'settings storage is unavailable' })
|
|
479
|
+
return send(200, { ok: true, config: readSettings() })
|
|
480
|
+
}
|
|
481
|
+
if (request.method === 'POST' && pathname === '/settings') {
|
|
482
|
+
if (settingsFile === null) return send(500, { ok: false, message: 'settings storage is unavailable' })
|
|
483
|
+
const incoming = body.config !== undefined ? body.config : body
|
|
484
|
+
const config = normalizeSettings(incoming, readSettings())
|
|
485
|
+
writeJsonFile(settingsFile, config)
|
|
486
|
+
return send(200, { ok: true, config })
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// ---------------------------------------------------- monitoring
|
|
490
|
+
// Superseded by GET/POST /settings (settings.monitor); kept so an older
|
|
491
|
+
// browser half keeps working. Both endpoints read and write the unified
|
|
492
|
+
// document, migrating a legacy monitor.json on the first read.
|
|
493
|
+
if (request.method === 'GET' && pathname === '/monitor') {
|
|
494
|
+
if (settingsFile === null) return send(500, { ok: false, message: 'monitor storage is unavailable' })
|
|
495
|
+
return send(200, { ok: true, config: readSettings().monitor })
|
|
496
|
+
}
|
|
497
|
+
if (request.method === 'POST' && pathname === '/monitor') {
|
|
498
|
+
if (settingsFile === null) return send(500, { ok: false, message: 'monitor storage is unavailable' })
|
|
499
|
+
const current = readSettings()
|
|
500
|
+
const config = normalizeMonitorConfig(body.config !== undefined ? body.config : body, current.monitor)
|
|
501
|
+
writeJsonFile(settingsFile, { ...current, monitor: config })
|
|
502
|
+
return send(200, { ok: true, config })
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// ---------------------------------------------------- terminals
|
|
506
|
+
if (terminals !== undefined) {
|
|
507
|
+
if (request.method === 'GET' && pathname === '/terminals') return send(200, { ok: true, terminals: terminals.list() })
|
|
508
|
+
if (request.method === 'POST' && pathname === '/terminals') {
|
|
509
|
+
const opened = await terminals.open(String(body.connectionId || ''), { cols: body.cols, rows: body.rows, title: body.title })
|
|
510
|
+
return send(200, { ok: true, ...opened })
|
|
511
|
+
}
|
|
512
|
+
const termMatch = /^\/terminals\/([^/]+)(?:\/(stream|input|resize))?$/.exec(pathname)
|
|
513
|
+
if (termMatch !== null) {
|
|
514
|
+
const terminalId = decodeURIComponent(termMatch[1])
|
|
515
|
+
const action = termMatch[2]
|
|
516
|
+
if (request.method === 'GET' && action === 'stream') {
|
|
517
|
+
response.writeHead(200, {
|
|
518
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
519
|
+
'cache-control': 'no-store',
|
|
520
|
+
connection: 'keep-alive',
|
|
521
|
+
...(allowOrigin === null ? {} : { 'access-control-allow-origin': allowOrigin }),
|
|
522
|
+
'x-accel-buffering': 'no',
|
|
523
|
+
})
|
|
524
|
+
response.write(': connected\n\n')
|
|
525
|
+
const detach = terminals.attach(terminalId, (event) => {
|
|
526
|
+
try {
|
|
527
|
+
response.write('data: ' + JSON.stringify(event) + '\n\n')
|
|
528
|
+
} catch {
|
|
529
|
+
/* client vanished */
|
|
530
|
+
}
|
|
531
|
+
})
|
|
532
|
+
if (detach === null) {
|
|
533
|
+
response.end()
|
|
534
|
+
return
|
|
535
|
+
}
|
|
536
|
+
const keepAlive = setInterval(() => {
|
|
537
|
+
try {
|
|
538
|
+
response.write(': ping\n\n')
|
|
539
|
+
} catch {
|
|
540
|
+
/* ignore */
|
|
541
|
+
}
|
|
542
|
+
}, 15000)
|
|
543
|
+
if (typeof keepAlive.unref === 'function') keepAlive.unref()
|
|
544
|
+
request.on('close', () => {
|
|
545
|
+
clearInterval(keepAlive)
|
|
546
|
+
detach()
|
|
547
|
+
})
|
|
548
|
+
return
|
|
549
|
+
}
|
|
550
|
+
if (request.method === 'POST' && action === 'input') {
|
|
551
|
+
terminals.write(terminalId, String(body.data || ''))
|
|
552
|
+
return send(200, { ok: true })
|
|
553
|
+
}
|
|
554
|
+
if (request.method === 'POST' && action === 'resize') {
|
|
555
|
+
terminals.resize(terminalId, Number(body.cols) || 0, Number(body.rows) || 0)
|
|
556
|
+
return send(200, { ok: true })
|
|
557
|
+
}
|
|
558
|
+
if (request.method === 'DELETE' && action === undefined) {
|
|
559
|
+
terminals.close(terminalId)
|
|
560
|
+
return send(200, { ok: true })
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// ---------------------------------------------------- port forwarding
|
|
566
|
+
if (forwards !== undefined) {
|
|
567
|
+
if (request.method === 'GET' && pathname === '/forwards') return send(200, { ok: true, forwards: forwards.list() })
|
|
568
|
+
if (request.method === 'POST' && pathname === '/forwards') {
|
|
569
|
+
const started = await forwards.start(
|
|
570
|
+
String(body.connectionId || ''),
|
|
571
|
+
Number(body.remotePort),
|
|
572
|
+
Number(body.localPort) || 0,
|
|
573
|
+
body.origin === 'agent' ? 'agent' : 'user',
|
|
574
|
+
)
|
|
575
|
+
return send(200, { ok: true, forward: started })
|
|
576
|
+
}
|
|
577
|
+
const forwardMatch = /^\/forwards\/([^/]+)$/.exec(pathname)
|
|
578
|
+
if (forwardMatch !== null && request.method === 'DELETE') {
|
|
579
|
+
const removed = forwards.stop(decodeURIComponent(forwardMatch[1]))
|
|
580
|
+
return send(removed ? 200 : 404, removed ? { ok: true } : { ok: false, message: 'forward not found' })
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
const portMatch = /^\/connections\/([^/]+)\/ports$/.exec(pathname)
|
|
585
|
+
if (portMatch !== null && request.method === 'GET' && forwards !== undefined) {
|
|
586
|
+
const ports = await forwards.detect(decodeURIComponent(portMatch[1]))
|
|
587
|
+
return send(200, { ok: true, ports })
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// ---------------------------------------------------- connections
|
|
591
|
+
if (request.method === 'GET' && pathname === '/ssh-config') {
|
|
592
|
+
if (typeof readSshConfig !== 'function') return send(200, { ok: true, path: '', exists: false, hosts: [], keys: [] })
|
|
593
|
+
return send(200, { ok: true, ...readSshConfig() })
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
if (request.method === 'POST' && pathname === '/connections/test') {
|
|
597
|
+
if (typeof testConnection !== 'function') return send(501, { ok: false, message: 'connection test unavailable' })
|
|
598
|
+
const result = await testConnection(body)
|
|
599
|
+
return send(200, { ok: true, ...result })
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
if (request.method === 'POST' && pathname === '/connections') {
|
|
603
|
+
const previous = typeof body.id === 'string' ? store.get(body.id) : undefined
|
|
604
|
+
const record = store.upsert(body)
|
|
605
|
+
if (typeof body.password === 'string' && body.password.length > 0) await secrets.set(record.id, 'PASSWORD', body.password)
|
|
606
|
+
if (body.clearPassword === true) await secrets.clear(record.id, 'PASSWORD')
|
|
607
|
+
if (typeof body.passphrase === 'string' && body.passphrase.length > 0) await secrets.set(record.id, 'PASSPHRASE', body.passphrase)
|
|
608
|
+
if (body.clearPassphrase === true) await secrets.clear(record.id, 'PASSPHRASE')
|
|
609
|
+
if (previous !== undefined) {
|
|
610
|
+
const identity = ['host', 'port', 'username', 'authType', 'privateKeyPath']
|
|
611
|
+
const identityChanged = identity.some((key) => previous[key] !== record[key])
|
|
612
|
+
const secretChanged =
|
|
613
|
+
(typeof body.password === 'string' && body.password.length > 0) || body.clearPassword === true ||
|
|
614
|
+
(typeof body.passphrase === 'string' && body.passphrase.length > 0) || body.clearPassphrase === true
|
|
615
|
+
if (identityChanged || secretChanged) {
|
|
616
|
+
const existing = hostFor(record.id)
|
|
617
|
+
if (existing !== undefined && existing.state === 'connected') {
|
|
618
|
+
existing.disconnect()
|
|
619
|
+
await existing.connect(secrets).catch(() => {})
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
return send(200, { ok: true, connection: await connectionView(record) })
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
// ---------------------------------------------------- metrics
|
|
627
|
+
// A collection failure stays inside a 200 so the browser half can show
|
|
628
|
+
// "unavailable" for a host that cannot answer instead of an error toast.
|
|
629
|
+
const metricsMatch = /^\/connections\/([^/]+)\/metrics$/.exec(pathname)
|
|
630
|
+
if (metricsMatch !== null && request.method === 'GET') {
|
|
631
|
+
const id = decodeURIComponent(metricsMatch[1])
|
|
632
|
+
if (store.get(id) === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
633
|
+
const host = hostFor(id)
|
|
634
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
635
|
+
try {
|
|
636
|
+
await host.ensure(secrets)
|
|
637
|
+
const snapshot = await metrics.read(id, url.searchParams.get('path') || '')
|
|
638
|
+
return send(200, { ok: true, ...snapshot })
|
|
639
|
+
} catch (error) {
|
|
640
|
+
return send(200, { ok: true, error: errorText(error) })
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// ---------------------------------------------------- editor drafts
|
|
645
|
+
// An unsaved editor buffer is kept on disk, so closing the tab — or DSH
|
|
646
|
+
// itself — does not lose it. Every visit also sweeps what has aged out.
|
|
647
|
+
if (pathname === '/draft' || pathname === '/draft/delete' || pathname === '/drafts') {
|
|
648
|
+
if (drafts.available !== true) return send(500, { ok: false, message: 'draft storage is unavailable' })
|
|
649
|
+
if (pathname === '/drafts') {
|
|
650
|
+
drafts.sweep()
|
|
651
|
+
if (request.method === 'GET') return send(200, { ok: true, drafts: drafts.list() })
|
|
652
|
+
if (request.method === 'DELETE') return send(200, { ok: true, removed: drafts.clear() })
|
|
653
|
+
return send(404, { ok: false, message: 'not found' })
|
|
654
|
+
}
|
|
655
|
+
const connectionId = flatDraftConnectionId(body, url)
|
|
656
|
+
// `POST /draft/delete` is the same request as `DELETE /draft`.
|
|
657
|
+
const method = pathname === '/draft/delete' && request.method === 'POST' ? 'DELETE' : request.method
|
|
658
|
+
const outcome = handleDraft(connectionId, method, url, body)
|
|
659
|
+
return send(outcome.status, outcome.body)
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// ------------------------------------------- resumable (chunked) upload
|
|
663
|
+
// One file may arrive in several `part` requests; `status` says how much
|
|
664
|
+
// the remote already has, `commit` renames the temporary file onto the
|
|
665
|
+
// destination and `abort` throws it away. The client asks `status` after
|
|
666
|
+
// a dropped connection, which is how a large upload continues across a
|
|
667
|
+
// reconnect instead of starting over. The rules live in
|
|
668
|
+
// `lib/upload-chunks.js`; this block owns only their HTTP meaning.
|
|
669
|
+
const uploadChunkMatch = /^\/connections\/([^/]+)\/upload\/(status|part|commit|abort)$/.exec(pathname)
|
|
670
|
+
if (uploadChunkMatch !== null) {
|
|
671
|
+
const id = decodeURIComponent(uploadChunkMatch[1])
|
|
672
|
+
const operation = uploadChunkMatch[2]
|
|
673
|
+
// status is the only read; the other three change the remote.
|
|
674
|
+
if (request.method !== (operation === 'status' ? 'GET' : 'POST')) {
|
|
675
|
+
return send(404, { ok: false, message: 'not found' })
|
|
676
|
+
}
|
|
677
|
+
if (store.get(id) === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
678
|
+
const host = hostFor(id)
|
|
679
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
680
|
+
const parsed = parseUploadTarget({
|
|
681
|
+
path: url.searchParams.get('path') ?? '',
|
|
682
|
+
name: url.searchParams.get('name') ?? '',
|
|
683
|
+
})
|
|
684
|
+
if (parsed.ok !== true) return send(400, { ok: false, code: parsed.code, message: parsed.message })
|
|
685
|
+
const offset = operation === 'part' ? parseUploadOffset(url.searchParams.get('offset')) : null
|
|
686
|
+
if (offset !== null && offset.ok !== true) {
|
|
687
|
+
return send(400, { ok: false, code: offset.code, message: offset.message })
|
|
688
|
+
}
|
|
689
|
+
const partTooLarge = `A part cannot be larger than ${Math.round(UPLOAD_PART_MAX_BYTES / 1024 / 1024)} MiB.`
|
|
690
|
+
// Refuse an oversized part before a possibly slow reconnect: the body
|
|
691
|
+
// is only buffered once the connection is known to be worth having.
|
|
692
|
+
const declaredPart = Number(request.headers['content-length'])
|
|
693
|
+
if (operation === 'part' && Number.isFinite(declaredPart) && declaredPart > UPLOAD_PART_MAX_BYTES) {
|
|
694
|
+
request.resume()
|
|
695
|
+
return send(400, { ok: false, code: UPLOAD_PART_TOO_LARGE_CODE, message: partTooLarge })
|
|
696
|
+
}
|
|
697
|
+
// `host.ensure` is also what puts a dropped SSH connection back before
|
|
698
|
+
// this request runs, so the retry after a disconnect lands on a live
|
|
699
|
+
// SFTP session without the client opening anything.
|
|
700
|
+
await host.ensure(secrets)
|
|
701
|
+
// A POST body is complete — and its IncomingMessage already destroyed —
|
|
702
|
+
// before this handler runs, so only the response and the socket say
|
|
703
|
+
// whether the client is still there. Same liveness check as the
|
|
704
|
+
// rename/mkdir/touch and delete routes above.
|
|
705
|
+
const controller = new AbortController()
|
|
706
|
+
response.on('close', () => {
|
|
707
|
+
if (response.writableEnded !== true) controller.abort()
|
|
708
|
+
})
|
|
709
|
+
const isCancelled = clientGone(request, response, controller)
|
|
710
|
+
|
|
711
|
+
if (operation === 'part') {
|
|
712
|
+
const raw = await readRawUploadBody(request, UPLOAD_PART_MAX_BYTES)
|
|
713
|
+
// Nobody to answer, and nothing worth writing: a part whose client
|
|
714
|
+
// left mid-body is simply dropped.
|
|
715
|
+
if (raw.aborted === true || isCancelled()) return
|
|
716
|
+
if (raw.tooLarge === true) {
|
|
717
|
+
request.resume()
|
|
718
|
+
return send(400, { ok: false, code: UPLOAD_PART_TOO_LARGE_CODE, message: partTooLarge })
|
|
719
|
+
}
|
|
720
|
+
const outcome = await writeUploadPart({
|
|
721
|
+
sftp: host.requireSftp(),
|
|
722
|
+
dir: parsed.dir,
|
|
723
|
+
name: parsed.name,
|
|
724
|
+
offset: offset.offset,
|
|
725
|
+
data: raw.data,
|
|
726
|
+
})
|
|
727
|
+
// The client walked away while SFTP was writing; never write into a
|
|
728
|
+
// dead socket. The bytes are on the remote, and the next status (or
|
|
729
|
+
// the same part retried at the reported offset) continues from them.
|
|
730
|
+
if (isCancelled()) return
|
|
731
|
+
if (outcome.ok !== true) {
|
|
732
|
+
return send(UPLOAD_ROUTE_STATUS[outcome.code] ?? 400, {
|
|
733
|
+
ok: false,
|
|
734
|
+
code: outcome.code,
|
|
735
|
+
message: outcome.message,
|
|
736
|
+
...(typeof outcome.received === 'number' ? { received: outcome.received } : {}),
|
|
737
|
+
})
|
|
738
|
+
}
|
|
739
|
+
return send(200, { ok: true, received: outcome.received })
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
if (operation === 'status') {
|
|
743
|
+
const outcome = await readUploadStatus({ sftp: host.requireSftp(), dir: parsed.dir, name: parsed.name })
|
|
744
|
+
if (isCancelled()) return
|
|
745
|
+
if (outcome.ok !== true) {
|
|
746
|
+
return send(UPLOAD_ROUTE_STATUS[outcome.code] ?? 400, { ok: false, code: outcome.code, message: outcome.message })
|
|
747
|
+
}
|
|
748
|
+
return send(200, { ok: true, exists: outcome.exists, received: outcome.received })
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
const outcome = operation === 'commit'
|
|
752
|
+
? await commitUpload({
|
|
753
|
+
sftp: host.requireSftp(),
|
|
754
|
+
dir: parsed.dir,
|
|
755
|
+
name: parsed.name,
|
|
756
|
+
overwrite: url.searchParams.get('overwrite') === '1',
|
|
757
|
+
})
|
|
758
|
+
: await abortUpload({ sftp: host.requireSftp(), dir: parsed.dir, name: parsed.name })
|
|
759
|
+
if (isCancelled()) return
|
|
760
|
+
if (outcome.ok !== true) {
|
|
761
|
+
return send(UPLOAD_ROUTE_STATUS[outcome.code] ?? 400, { ok: false, code: outcome.code, message: outcome.message })
|
|
762
|
+
}
|
|
763
|
+
return send(200, operation === 'commit' ? { ok: true, path: outcome.path } : { ok: true })
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
const match = /^\/connections\/([^/]+)(?:\/(action|dirs|mkdir|rename|touch|workspaces|probe|files|scan|delete|transfer|read|write|draft|auto-connect|download|archive|upload|save-local|reveal))?$/.exec(pathname)
|
|
767
|
+
if (match !== null) {
|
|
768
|
+
const id = decodeURIComponent(match[1])
|
|
769
|
+
const action = match[2]
|
|
770
|
+
const record = store.get(id)
|
|
771
|
+
if (record === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
772
|
+
|
|
773
|
+
if (request.method === 'DELETE' && action === undefined) {
|
|
774
|
+
const host = hostFor(id)
|
|
775
|
+
host?.disconnect()
|
|
776
|
+
dropHost?.(id)
|
|
777
|
+
store.remove(id)
|
|
778
|
+
await secrets.clear(id, 'PASSWORD')
|
|
779
|
+
await secrets.clear(id, 'PASSPHRASE')
|
|
780
|
+
if (forwards !== undefined) forwards.stopForConnection(id)
|
|
781
|
+
routing.invalidate()
|
|
782
|
+
return send(200, { ok: true })
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
if (request.method === 'POST' && action === 'action') {
|
|
786
|
+
const name = String(body.action || '')
|
|
787
|
+
const host = hostFor(id)
|
|
788
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
789
|
+
if (name === 'connect' || name === 'reconnect') {
|
|
790
|
+
if (name === 'reconnect') host.disconnect()
|
|
791
|
+
await host.connect(secrets)
|
|
792
|
+
return send(200, { ok: true, connection: await connectionView(record) })
|
|
793
|
+
}
|
|
794
|
+
if (name === 'disconnect') {
|
|
795
|
+
host.disconnect()
|
|
796
|
+
return send(200, { ok: true, connection: await connectionView(record) })
|
|
797
|
+
}
|
|
798
|
+
if (name === 'probe') {
|
|
799
|
+
await host.ensure(secrets)
|
|
800
|
+
await host.probe()
|
|
801
|
+
return send(200, { ok: true, connection: await connectionView(record) })
|
|
802
|
+
}
|
|
803
|
+
return send(400, { ok: false, message: 'Unknown action.' })
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// The editor talks to the draft store through its connection, which is
|
|
807
|
+
// also what keys the stored file.
|
|
808
|
+
if (action === 'draft' && (request.method === 'POST' || request.method === 'GET' || request.method === 'DELETE')) {
|
|
809
|
+
const outcome = handleDraft(id, request.method, url, body)
|
|
810
|
+
return send(outcome.status, outcome.body)
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
if (request.method === 'POST' && action === 'auto-connect') {
|
|
814
|
+
const updated = store.upsert({ ...record, autoConnect: body.enabled === true })
|
|
815
|
+
return send(200, { ok: true, connection: await connectionView(updated) })
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
if (request.method === 'GET' && action === 'dirs') {
|
|
819
|
+
const host = hostFor(id)
|
|
820
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
821
|
+
await host.ensure(secrets)
|
|
822
|
+
const sftp = host.requireSftp()
|
|
823
|
+
let target = url.searchParams.get('path') || '~'
|
|
824
|
+
if (target === '~') target = '.'
|
|
825
|
+
const resolved = await sftpCall(sftp, 'realpath', target)
|
|
826
|
+
const entries = await sftpCall(sftp, 'readdir', resolved)
|
|
827
|
+
const dirs = entries
|
|
828
|
+
.filter((entry) => entry.attrs.isDirectory && entry.attrs.isDirectory())
|
|
829
|
+
.map((entry) => ({
|
|
830
|
+
name: entry.filename,
|
|
831
|
+
path: posix.join(resolved, entry.filename),
|
|
832
|
+
mtime: (entry.attrs.mtime || 0) * 1000,
|
|
833
|
+
}))
|
|
834
|
+
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
835
|
+
const parent = resolved === '/' ? null : posix.dirname(resolved)
|
|
836
|
+
return send(200, { ok: true, connectionId: id, path: resolved, parent, dirs })
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
if (request.method === 'GET' && action === 'files') {
|
|
840
|
+
const host = hostFor(id)
|
|
841
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
842
|
+
await host.ensure(secrets)
|
|
843
|
+
const sftp = host.requireSftp()
|
|
844
|
+
let target = url.searchParams.get('path') || '~'
|
|
845
|
+
if (target === '~' || target === '') target = '.'
|
|
846
|
+
const resolved = await sftpCall(sftp, 'realpath', target)
|
|
847
|
+
const entries = await sftpCall(sftp, 'readdir', resolved)
|
|
848
|
+
const rows = (await Promise.all(entries
|
|
849
|
+
.map(async (entry) => {
|
|
850
|
+
const row = {
|
|
851
|
+
name: entry.filename,
|
|
852
|
+
path: posix.join(resolved, entry.filename),
|
|
853
|
+
type: entry.attrs.isDirectory && entry.attrs.isDirectory() ? 'dir' : 'file',
|
|
854
|
+
kind: entryKind(entry.attrs),
|
|
855
|
+
size: entry.attrs.size || 0,
|
|
856
|
+
mtime: (entry.attrs.mtime || 0) * 1000,
|
|
857
|
+
link: Boolean(entry.attrs.isSymbolicLink && entry.attrs.isSymbolicLink()),
|
|
858
|
+
}
|
|
859
|
+
// A link is useless to browse without knowing where it points:
|
|
860
|
+
// `readlink` names the target and `stat` (which follows) says
|
|
861
|
+
// whether it is a directory, a file, or dangling.
|
|
862
|
+
if (row.kind !== 'link') return row
|
|
863
|
+
const target = await sftpCall(sftp, 'readlink', row.path).catch(() => null)
|
|
864
|
+
if (typeof target === 'string' && target.length > 0) row.linkTarget = target
|
|
865
|
+
const followed = await sftpCall(sftp, 'stat', row.path).catch(() => null)
|
|
866
|
+
row.linkKind = followed === null ? 'broken' : entryKind(followed) === 'dir' ? 'dir' : 'other'
|
|
867
|
+
if (followed !== null && entryKind(followed) !== 'dir') {
|
|
868
|
+
row.linkKind = 'file'
|
|
869
|
+
row.size = followed.size || row.size
|
|
870
|
+
row.mtime = (followed.mtime || 0) * 1000 || row.mtime
|
|
871
|
+
}
|
|
872
|
+
return row
|
|
873
|
+
})))
|
|
874
|
+
rows.sort((a, b) => (a.type === b.type ? (a.name < b.name ? -1 : a.name > b.name ? 1 : 0) : a.type === 'dir' ? -1 : 1))
|
|
875
|
+
const parent = resolved === '/' ? null : posix.dirname(resolved)
|
|
876
|
+
return send(200, { ok: true, connectionId: id, path: resolved, parent, entries: rows })
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
if (request.method === 'GET' && action === 'scan') {
|
|
880
|
+
const host = hostFor(id)
|
|
881
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
882
|
+
await host.ensure(secrets)
|
|
883
|
+
const requested = String(url.searchParams.get('path') || '/')
|
|
884
|
+
if (!requested.startsWith('/')) {
|
|
885
|
+
return send(400, { ok: false, code: 'NOT_REMOTE_PATH', message: 'Not a remote POSIX path.' })
|
|
886
|
+
}
|
|
887
|
+
const target = normalizeRemotePath(requested)
|
|
888
|
+
const attrs = await sftpCall(host.requireSftp(), 'stat', target)
|
|
889
|
+
if (!(attrs.isDirectory && attrs.isDirectory())) {
|
|
890
|
+
return send(400, { ok: false, message: 'Only a folder can be scanned.' })
|
|
891
|
+
}
|
|
892
|
+
const started = Date.now()
|
|
893
|
+
const controller = new AbortController()
|
|
894
|
+
const timer = setTimeout(() => controller.abort(), SCAN_TIMEOUT_MS)
|
|
895
|
+
let result
|
|
896
|
+
try {
|
|
897
|
+
result = await host.runCommand(scanCommand(target), null, {
|
|
898
|
+
maxBytes: SCAN_MAX_BYTES,
|
|
899
|
+
signal: controller.signal,
|
|
900
|
+
})
|
|
901
|
+
} finally {
|
|
902
|
+
clearTimeout(timer)
|
|
903
|
+
}
|
|
904
|
+
// A timeout cuts the read short, but what did arrive is still worth
|
|
905
|
+
// reporting — `complete` stays false unless the remote finished.
|
|
906
|
+
return send(200, {
|
|
907
|
+
ok: true,
|
|
908
|
+
...parseScanOutput(result.stdout),
|
|
909
|
+
path: target,
|
|
910
|
+
durationMs: Date.now() - started,
|
|
911
|
+
})
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
if (request.method === 'POST' && action === 'delete') {
|
|
915
|
+
const host = hostFor(id)
|
|
916
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
917
|
+
await host.ensure(secrets)
|
|
918
|
+
const target = parseDeleteTarget(body.path)
|
|
919
|
+
if (target.ok !== true) return send(400, { ok: false, code: target.code, message: target.message })
|
|
920
|
+
if (body.force !== true && isProtectedDeleteRoot(target.path, workspaceRootsFor(id))) {
|
|
921
|
+
return send(400, {
|
|
922
|
+
ok: false,
|
|
923
|
+
code: DELETE_ROOT_CODE,
|
|
924
|
+
message: 'That folder is a workspace root; send "force": true to delete it.',
|
|
925
|
+
})
|
|
926
|
+
}
|
|
927
|
+
// A POST body is complete — and its IncomingMessage already destroyed —
|
|
928
|
+
// before this handler runs (verified against Node 20), so
|
|
929
|
+
// `request.destroyed` and `request.on('close')` say nothing about the
|
|
930
|
+
// client. The socket and the response do: the browser cancels by
|
|
931
|
+
// aborting the request, which closes the response unfinished.
|
|
932
|
+
const controller = new AbortController()
|
|
933
|
+
response.on('close', () => {
|
|
934
|
+
if (response.writableEnded !== true) controller.abort()
|
|
935
|
+
})
|
|
936
|
+
const isCancelled = () => controller.signal.aborted === true
|
|
937
|
+
|| response.destroyed === true
|
|
938
|
+
|| (request.socket !== null && request.socket !== undefined && request.socket.destroyed === true)
|
|
939
|
+
const counts = emptyDeleteCounts()
|
|
940
|
+
try {
|
|
941
|
+
await removeRemoteTree({ sftp: host.requireSftp(), path: target.path, counts, isCancelled })
|
|
942
|
+
} catch (error) {
|
|
943
|
+
// The client is gone; never write into a dead socket.
|
|
944
|
+
if (isDeleteCancelled(error)) return
|
|
945
|
+
if (isDeleteMissing(error)) {
|
|
946
|
+
return send(404, { ok: false, code: DELETE_MISSING_CODE, message: errorText(error) })
|
|
947
|
+
}
|
|
948
|
+
// Partially deleted: report the tally so the client can say
|
|
949
|
+
// "N items were removed, then it failed".
|
|
950
|
+
return send(200, { ok: false, error: errorText(error), deleted: counts })
|
|
951
|
+
}
|
|
952
|
+
return send(200, { ok: true, deleted: counts })
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
if (request.method === 'POST' && action === 'transfer') {
|
|
956
|
+
const host = hostFor(id)
|
|
957
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
958
|
+
await host.ensure(secrets)
|
|
959
|
+
// A batch of copies can run long, and the browser cancels it by
|
|
960
|
+
// aborting the request, which closes the response unfinished. The
|
|
961
|
+
// liveness signals are the delete route's: a POST body is already
|
|
962
|
+
// consumed here, so `request` itself says nothing about the client.
|
|
963
|
+
const controller = new AbortController()
|
|
964
|
+
response.on('close', () => {
|
|
965
|
+
if (response.writableEnded !== true) controller.abort()
|
|
966
|
+
})
|
|
967
|
+
const isCancelled = () => controller.signal.aborted === true
|
|
968
|
+
|| response.destroyed === true
|
|
969
|
+
|| (request.socket !== null && request.socket !== undefined && request.socket.destroyed === true)
|
|
970
|
+
const outcome = await transferRemotePaths({ sftp: host.requireSftp(), body, isCancelled })
|
|
971
|
+
// The client is gone: never write into a dead socket.
|
|
972
|
+
if (outcome.cancelled === true) return
|
|
973
|
+
if (outcome.ok !== true) return send(400, { ok: false, code: outcome.code, message: outcome.message })
|
|
974
|
+
return send(200, { ok: true, results: outcome.results })
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
if (request.method === 'GET' && action === 'read') {
|
|
978
|
+
const host = hostFor(id)
|
|
979
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
980
|
+
await host.ensure(secrets)
|
|
981
|
+
const controller = new AbortController()
|
|
982
|
+
response.on('close', () => {
|
|
983
|
+
if (response.writableEnded !== true) controller.abort()
|
|
984
|
+
})
|
|
985
|
+
try {
|
|
986
|
+
const outcome = await readRemoteFile({
|
|
987
|
+
sftp: host.requireSftp(),
|
|
988
|
+
path: url.searchParams.get('path') || '',
|
|
989
|
+
maxBytes: url.searchParams.get('maxBytes'),
|
|
990
|
+
// Only set when the reader picked an encoding themselves; without
|
|
991
|
+
// it a non-UTF-8 file answers read-only.
|
|
992
|
+
encoding: url.searchParams.get('encoding') || '',
|
|
993
|
+
isCancelled: clientGone(request, response, controller),
|
|
994
|
+
})
|
|
995
|
+
if (outcome.ok !== true) {
|
|
996
|
+
const status = outcome.code === EDIT_MISSING_CODE ? 404 : 400
|
|
997
|
+
return send(status, { ok: false, code: outcome.code, message: outcome.message })
|
|
998
|
+
}
|
|
999
|
+
return send(200, { ok: true, ...outcome.file })
|
|
1000
|
+
} catch (error) {
|
|
1001
|
+
// The client is gone; never write into a dead socket.
|
|
1002
|
+
if (isEditCancelled(error)) return
|
|
1003
|
+
throw error
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
if (request.method === 'POST' && action === 'write') {
|
|
1008
|
+
const host = hostFor(id)
|
|
1009
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
1010
|
+
await host.ensure(secrets)
|
|
1011
|
+
const parsed = parseWriteRequest(body)
|
|
1012
|
+
if (parsed.ok !== true) return send(400, { ok: false, code: parsed.code, message: parsed.message })
|
|
1013
|
+
const controller = new AbortController()
|
|
1014
|
+
response.on('close', () => {
|
|
1015
|
+
if (response.writableEnded !== true) controller.abort()
|
|
1016
|
+
})
|
|
1017
|
+
let outcome
|
|
1018
|
+
try {
|
|
1019
|
+
outcome = await writeRemoteFile({
|
|
1020
|
+
sftp: host.requireSftp(),
|
|
1021
|
+
path: parsed.path,
|
|
1022
|
+
content: parsed.content,
|
|
1023
|
+
expectedMtime: parsed.expectedMtime,
|
|
1024
|
+
encoding: parsed.encoding,
|
|
1025
|
+
eol: parsed.eol,
|
|
1026
|
+
isCancelled: clientGone(request, response, controller),
|
|
1027
|
+
})
|
|
1028
|
+
} catch (error) {
|
|
1029
|
+
if (isEditCancelled(error)) return
|
|
1030
|
+
throw error
|
|
1031
|
+
}
|
|
1032
|
+
if (outcome.ok !== true) {
|
|
1033
|
+
const status = outcome.code === EDIT_STALE_CODE ? 409 : 400
|
|
1034
|
+
const payload = { ok: false, code: outcome.code, message: outcome.message }
|
|
1035
|
+
if (outcome.mtime !== undefined) payload.mtime = outcome.mtime
|
|
1036
|
+
return send(status, payload)
|
|
1037
|
+
}
|
|
1038
|
+
return send(200, { ok: true, ...outcome.file })
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
if (request.method === 'GET' && action === 'download') {
|
|
1042
|
+
const host = hostFor(id)
|
|
1043
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
1044
|
+
await host.ensure(secrets)
|
|
1045
|
+
const sftp = host.requireSftp()
|
|
1046
|
+
const requested = String(url.searchParams.get('path') || '/')
|
|
1047
|
+
if (!requested.startsWith('/')) {
|
|
1048
|
+
return send(400, { ok: false, code: 'NOT_REMOTE_PATH', message: 'Not a remote POSIX path.' })
|
|
1049
|
+
}
|
|
1050
|
+
const target = normalizeRemotePath(requested)
|
|
1051
|
+
const attrs = await sftpCall(sftp, 'stat', target)
|
|
1052
|
+
if (attrs.isDirectory && attrs.isDirectory()) return send(400, { ok: false, message: 'Cannot download a folder.' })
|
|
1053
|
+
const name = posix.basename(target)
|
|
1054
|
+
response.writeHead(200, {
|
|
1055
|
+
'content-type': mimeFor(name),
|
|
1056
|
+
'content-length': String(attrs.size || 0),
|
|
1057
|
+
'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
|
|
1058
|
+
'cache-control': 'no-store',
|
|
1059
|
+
...(allowOrigin === null ? {} : { 'access-control-allow-origin': allowOrigin }),
|
|
1060
|
+
})
|
|
1061
|
+
const stream = sftp.createReadStream(target)
|
|
1062
|
+
stream.on('error', () => response.destroy())
|
|
1063
|
+
response.on('close', () => stream.destroy())
|
|
1064
|
+
stream.pipe(response)
|
|
1065
|
+
return
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
if (request.method === 'GET' && action === 'archive') {
|
|
1069
|
+
const host = hostFor(id)
|
|
1070
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
1071
|
+
await host.ensure(secrets)
|
|
1072
|
+
const requestedPaths = url.searchParams.getAll('path')
|
|
1073
|
+
if (requestedPaths.length > ARCHIVE_MAX_PATHS) {
|
|
1074
|
+
return send(400, {
|
|
1075
|
+
ok: false,
|
|
1076
|
+
code: 'TOO_MANY_PATHS',
|
|
1077
|
+
message: `At most ${ARCHIVE_MAX_PATHS} paths can be archived at once.`,
|
|
1078
|
+
})
|
|
1079
|
+
}
|
|
1080
|
+
let command
|
|
1081
|
+
let cwd
|
|
1082
|
+
let name
|
|
1083
|
+
if (requestedPaths.length > 1) {
|
|
1084
|
+
// A multi-selection becomes one flat archive. Nothing is stat'ed
|
|
1085
|
+
// here: a path that disappeared since the listing is skipped by
|
|
1086
|
+
// `find` — one line on stderr, empty list — instead of failing the
|
|
1087
|
+
// whole download. Paths must still be plain absolute POSIX names,
|
|
1088
|
+
// and duplicates are collapsed so no member is stored twice.
|
|
1089
|
+
const targets = []
|
|
1090
|
+
const seen = new Set()
|
|
1091
|
+
for (const raw of requestedPaths) {
|
|
1092
|
+
const value = String(raw)
|
|
1093
|
+
if (!value.startsWith('/') || value.split('/').includes('..')) {
|
|
1094
|
+
return send(400, { ok: false, code: 'NOT_REMOTE_PATH', message: 'Not a remote POSIX path.' })
|
|
1095
|
+
}
|
|
1096
|
+
const target = normalizeRemotePath(value)
|
|
1097
|
+
if (safeRemoteName(posix.basename(target)) === '') {
|
|
1098
|
+
return send(400, { ok: false, code: 'NOT_REMOTE_PATH', message: 'Cannot archive that path.' })
|
|
1099
|
+
}
|
|
1100
|
+
const key = target.replace(/\/+$/, '') || '/'
|
|
1101
|
+
if (seen.has(key)) continue
|
|
1102
|
+
seen.add(key)
|
|
1103
|
+
targets.push(target)
|
|
1104
|
+
}
|
|
1105
|
+
command = archivePathsCommand(targets)
|
|
1106
|
+
cwd = null
|
|
1107
|
+
name = `${safeRemoteName(posix.basename(targets[0]))}.tar.gz`
|
|
1108
|
+
} else {
|
|
1109
|
+
const requested = String(url.searchParams.get('path') || '/')
|
|
1110
|
+
if (!requested.startsWith('/')) {
|
|
1111
|
+
return send(400, { ok: false, code: 'NOT_REMOTE_PATH', message: 'Not a remote POSIX path.' })
|
|
1112
|
+
}
|
|
1113
|
+
const target = normalizeRemotePath(requested)
|
|
1114
|
+
const base = safeRemoteName(posix.basename(target))
|
|
1115
|
+
if (base === '') return send(400, { ok: false, message: 'Cannot archive that folder.' })
|
|
1116
|
+
const attrs = await sftpCall(host.requireSftp(), 'stat', target)
|
|
1117
|
+
if (!(attrs.isDirectory && attrs.isDirectory())) {
|
|
1118
|
+
return send(400, { ok: false, message: 'Only a folder is archived; download a file directly.' })
|
|
1119
|
+
}
|
|
1120
|
+
command = archiveCommand(base)
|
|
1121
|
+
cwd = posix.dirname(target)
|
|
1122
|
+
name = `${base}.tar.gz`
|
|
1123
|
+
}
|
|
1124
|
+
const stream = await host.streamCommand(command, cwd)
|
|
1125
|
+
response.writeHead(200, {
|
|
1126
|
+
'content-type': 'application/gzip',
|
|
1127
|
+
'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
|
|
1128
|
+
'cache-control': 'no-store',
|
|
1129
|
+
'access-control-allow-origin': '*',
|
|
1130
|
+
})
|
|
1131
|
+
let sent = 0
|
|
1132
|
+
let cut = false
|
|
1133
|
+
stream.stderr.on('data', (chunk) => {
|
|
1134
|
+
// `find` reports a skipped path here and tar its diagnostics; the
|
|
1135
|
+
// exit code settles the request, so the line is only read while the
|
|
1136
|
+
// plugin is being debugged.
|
|
1137
|
+
if (process.env.DSH_REMOTE_DECK_DEBUG === '1') console.error('[remote-deck] archive:', String(chunk).trim())
|
|
1138
|
+
})
|
|
1139
|
+
stream.on('data', (chunk) => {
|
|
1140
|
+
sent += chunk.length
|
|
1141
|
+
if (sent > transferLimitNow()) {
|
|
1142
|
+
cut = true
|
|
1143
|
+
stream.destroy()
|
|
1144
|
+
response.destroy()
|
|
1145
|
+
}
|
|
1146
|
+
})
|
|
1147
|
+
stream.on('error', () => response.destroy())
|
|
1148
|
+
stream.on('close', () => {
|
|
1149
|
+
if (!cut) response.end()
|
|
1150
|
+
})
|
|
1151
|
+
stream.pipe(response, { end: false })
|
|
1152
|
+
request.on('close', () => stream.destroy())
|
|
1153
|
+
return
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
if (request.method === 'POST' && action === 'upload') {
|
|
1157
|
+
const host = hostFor(id)
|
|
1158
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
1159
|
+
await host.ensure(secrets)
|
|
1160
|
+
const requested = String(url.searchParams.get('path') || '/')
|
|
1161
|
+
if (!requested.startsWith('/')) {
|
|
1162
|
+
return send(400, { ok: false, code: 'NOT_REMOTE_PATH', message: 'Not a remote POSIX path.' })
|
|
1163
|
+
}
|
|
1164
|
+
const name = safeRemoteName(url.searchParams.get('name') || '')
|
|
1165
|
+
if (name === '') return send(400, { ok: false, message: 'A plain file name is required.' })
|
|
1166
|
+
const declared = Number(request.headers['content-length'])
|
|
1167
|
+
if (Number.isFinite(declared) && declared > transferLimitNow()) {
|
|
1168
|
+
return send(413, {
|
|
1169
|
+
ok: false,
|
|
1170
|
+
code: 'TRANSFER_TOO_LARGE',
|
|
1171
|
+
message: `That file is larger than the ${transferLimitText()} transfer limit.`,
|
|
1172
|
+
})
|
|
1173
|
+
}
|
|
1174
|
+
const target = posix.join(normalizeRemotePath(requested), name)
|
|
1175
|
+
const overwrite = url.searchParams.get('overwrite') === '1'
|
|
1176
|
+
if (!overwrite) {
|
|
1177
|
+
const existing = await sftpCall(host.requireSftp(), 'lstat', target).catch(() => null)
|
|
1178
|
+
if (existing !== null) {
|
|
1179
|
+
// The client asks the reader and re-sends with `overwrite=1`;
|
|
1180
|
+
// silently replacing a file is never acceptable.
|
|
1181
|
+
return send(409, {
|
|
1182
|
+
ok: false,
|
|
1183
|
+
code: 'EXISTS',
|
|
1184
|
+
message: `An entry named "${name}" is already there.`,
|
|
1185
|
+
})
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
const writeStream = host.requireSftp().createWriteStream(target)
|
|
1189
|
+
let received = 0
|
|
1190
|
+
let failed = false
|
|
1191
|
+
const abort = (message) => {
|
|
1192
|
+
if (failed) return
|
|
1193
|
+
failed = true
|
|
1194
|
+
try {
|
|
1195
|
+
writeStream.destroy()
|
|
1196
|
+
} catch {
|
|
1197
|
+
/* ignore */
|
|
1198
|
+
}
|
|
1199
|
+
try {
|
|
1200
|
+
request.destroy()
|
|
1201
|
+
} catch {
|
|
1202
|
+
/* ignore */
|
|
1203
|
+
}
|
|
1204
|
+
if (!response.headersSent) {
|
|
1205
|
+
send(400, { ok: false, code: 'TRANSFER_FAILED', message })
|
|
1206
|
+
} else {
|
|
1207
|
+
response.destroy()
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
request.on('data', (chunk) => {
|
|
1211
|
+
received += chunk.length
|
|
1212
|
+
if (received > transferLimitNow()) abort(`That file is larger than the ${transferLimitText()} transfer limit.`)
|
|
1213
|
+
})
|
|
1214
|
+
request.on('error', () => abort('The upload was interrupted.'))
|
|
1215
|
+
// Once the request body ends, its IncomingMessage closes even though
|
|
1216
|
+
// the SFTP write is still running, so `request` cannot report a client
|
|
1217
|
+
// that walked away. The response can: it only closes unfinished when
|
|
1218
|
+
// the connection went away.
|
|
1219
|
+
response.on('close', () => {
|
|
1220
|
+
if (response.writableEnded !== true) abort('The upload was interrupted.')
|
|
1221
|
+
})
|
|
1222
|
+
writeStream.on('error', (error) => abort(errorText(error)))
|
|
1223
|
+
writeStream.on('close', () => {
|
|
1224
|
+
if (!failed) send(200, { ok: true, path: target, bytes: received })
|
|
1225
|
+
})
|
|
1226
|
+
request.pipe(writeStream)
|
|
1227
|
+
return
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
if (request.method === 'POST' && action === 'save-local') {
|
|
1231
|
+
const host = hostFor(id)
|
|
1232
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
1233
|
+
await host.ensure(secrets)
|
|
1234
|
+
const sftp = host.requireSftp()
|
|
1235
|
+
const target = normalizeRemotePath(String(body.path || ''))
|
|
1236
|
+
const attrs = await sftpCall(sftp, 'stat', target)
|
|
1237
|
+
if (attrs.isDirectory && attrs.isDirectory()) return send(400, { ok: false, message: 'Cannot save a folder.' })
|
|
1238
|
+
const localPath = localTarget(DOWNLOAD_ROOT, record.name, target)
|
|
1239
|
+
await new Promise((resolve, reject) => {
|
|
1240
|
+
const writeStream = createWriteStream(localPath)
|
|
1241
|
+
const readStream = sftp.createReadStream(target)
|
|
1242
|
+
writeStream.on('close', resolve)
|
|
1243
|
+
writeStream.on('error', reject)
|
|
1244
|
+
readStream.on('error', reject)
|
|
1245
|
+
readStream.pipe(writeStream)
|
|
1246
|
+
})
|
|
1247
|
+
return send(200, { ok: true, localPath, root: DOWNLOAD_ROOT })
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
if (request.method === 'POST' && action === 'reveal') {
|
|
1251
|
+
const target = String(body.localPath || '')
|
|
1252
|
+
if (!insideDownloadRoot(target)) return send(400, { ok: false, message: 'Path is outside the download folder.' })
|
|
1253
|
+
spawn('explorer.exe', [`/select,${target}`], { detached: true, stdio: 'ignore' }).unref()
|
|
1254
|
+
return send(200, { ok: true })
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
// The path bar's "create this directory chain" button predates the
|
|
1258
|
+
// single-name contract below: it posts a whole path and asks for the
|
|
1259
|
+
// missing parents, and stays here so an older browser half keeps working.
|
|
1260
|
+
if (request.method === 'POST' && action === 'mkdir' && body.recursive === true) {
|
|
1261
|
+
const host = hostFor(id)
|
|
1262
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
1263
|
+
await host.ensure(secrets)
|
|
1264
|
+
const target = normalizeRemotePath(String(body.path || '/'))
|
|
1265
|
+
await ensureRemoteDir(host.requireSftp(), target)
|
|
1266
|
+
return send(200, { ok: true, path: target })
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
// ------------------------------------- rename / new folder / new file
|
|
1270
|
+
// The file page's three single-name actions. `lib/fs-actions.js` owns
|
|
1271
|
+
// validation and the SFTP calls; this route owns their HTTP meaning.
|
|
1272
|
+
if (request.method === 'POST' && (action === 'rename' || action === 'mkdir' || action === 'touch')) {
|
|
1273
|
+
const host = hostFor(id)
|
|
1274
|
+
if (host === undefined) return send(404, { ok: false, message: 'Connection not found.' })
|
|
1275
|
+
await host.ensure(secrets)
|
|
1276
|
+
const parsed = parseNameRequest(body)
|
|
1277
|
+
if (parsed.ok !== true) return send(400, { ok: false, code: parsed.code, message: parsed.message })
|
|
1278
|
+
// A POST body is complete — and its IncomingMessage already destroyed —
|
|
1279
|
+
// before this handler runs, so only the response and the socket say
|
|
1280
|
+
// whether the client is still there. Same liveness check as delete/write.
|
|
1281
|
+
const controller = new AbortController()
|
|
1282
|
+
response.on('close', () => {
|
|
1283
|
+
if (response.writableEnded !== true) controller.abort()
|
|
1284
|
+
})
|
|
1285
|
+
const isCancelled = clientGone(request, response, controller)
|
|
1286
|
+
const perform = action === 'rename' ? renameRemotePath : action === 'mkdir' ? mkdirRemotePath : touchRemotePath
|
|
1287
|
+
const outcome = await perform({ sftp: host.requireSftp(), path: parsed.path, name: parsed.name })
|
|
1288
|
+
// The client is gone; never write into a dead socket.
|
|
1289
|
+
if (isCancelled()) return
|
|
1290
|
+
if (outcome.ok !== true) {
|
|
1291
|
+
return send(FS_ACTION_STATUS[outcome.code] ?? 400, { ok: false, code: outcome.code, message: outcome.message })
|
|
1292
|
+
}
|
|
1293
|
+
return send(200, action === 'rename'
|
|
1294
|
+
? { ok: true, path: outcome.path, name: parsed.name }
|
|
1295
|
+
: { ok: true, path: outcome.path })
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
if (request.method === 'POST' && action === 'workspaces') {
|
|
1299
|
+
const created = await routing.createWorkspace(id, String(body.path || ''), record, {
|
|
1300
|
+
title: typeof body.title === 'string' ? body.title : undefined,
|
|
1301
|
+
})
|
|
1302
|
+
return send(200, { ok: true, ...created })
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
if (request.method === 'DELETE' && pathname === '/workspaces') {
|
|
1307
|
+
const stub = url.searchParams.get('stub') || ''
|
|
1308
|
+
if (stub === '') return send(400, { ok: false, message: 'Missing stub parameter.' })
|
|
1309
|
+
if (getRegistry() === undefined) return send(500, { ok: false, message: 'Workspace registry is unavailable.' })
|
|
1310
|
+
await routing.removeWorkspace(stub)
|
|
1311
|
+
return send(200, { ok: true })
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
if (request.method === 'GET' && pathname === '/map') {
|
|
1315
|
+
return send(200, {
|
|
1316
|
+
ok: true,
|
|
1317
|
+
workspaces: routing.listWorkspaces().map((row) => ({
|
|
1318
|
+
stub: row.stub,
|
|
1319
|
+
connectionId: row.connectionId,
|
|
1320
|
+
path: row.path,
|
|
1321
|
+
host: row.host,
|
|
1322
|
+
color: row.color,
|
|
1323
|
+
})),
|
|
1324
|
+
})
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
return send(404, { ok: false, message: 'not found' })
|
|
1328
|
+
} catch (error) {
|
|
1329
|
+
if (response.headersSent) {
|
|
1330
|
+
try {
|
|
1331
|
+
response.destroy()
|
|
1332
|
+
} catch {
|
|
1333
|
+
/* ignore */
|
|
1334
|
+
}
|
|
1335
|
+
return
|
|
1336
|
+
}
|
|
1337
|
+
return send(500, {
|
|
1338
|
+
ok: false,
|
|
1339
|
+
code: error && error.code,
|
|
1340
|
+
message: errorText(error),
|
|
1341
|
+
})
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
const server = http.createServer((request, response) => {
|
|
1346
|
+
handle(request, response).catch((error) => {
|
|
1347
|
+
try {
|
|
1348
|
+
if (response.headersSent) {
|
|
1349
|
+
response.destroy()
|
|
1350
|
+
return
|
|
1351
|
+
}
|
|
1352
|
+
response.writeHead(500, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
1353
|
+
response.end(JSON.stringify({ ok: false, message: errorText(error) }))
|
|
1354
|
+
} catch {
|
|
1355
|
+
try {
|
|
1356
|
+
response.destroy()
|
|
1357
|
+
} catch {
|
|
1358
|
+
/* ignore */
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
})
|
|
1362
|
+
})
|
|
1363
|
+
|
|
1364
|
+
async function connectionView(record) {
|
|
1365
|
+
const host = hostFor(record.id)
|
|
1366
|
+
const status = host === undefined ? { state: 'disconnected' } : host.status()
|
|
1367
|
+
const described = await secrets.describe(record.id)
|
|
1368
|
+
return {
|
|
1369
|
+
id: record.id,
|
|
1370
|
+
name: record.name,
|
|
1371
|
+
host: record.host,
|
|
1372
|
+
port: record.port,
|
|
1373
|
+
username: record.username,
|
|
1374
|
+
authType: record.authType,
|
|
1375
|
+
privateKeyPath: record.privateKeyPath,
|
|
1376
|
+
jump: typeof record.jump === 'string' ? record.jump : '',
|
|
1377
|
+
color: record.color,
|
|
1378
|
+
autoConnect: record.autoConnect,
|
|
1379
|
+
notes: record.notes,
|
|
1380
|
+
status: status.state,
|
|
1381
|
+
error: status.error,
|
|
1382
|
+
since: status.since,
|
|
1383
|
+
latencyMs: status.latencyMs ?? null,
|
|
1384
|
+
sys: status.sys ?? null,
|
|
1385
|
+
hasPassword: described.password,
|
|
1386
|
+
hasPassphrase: described.passphrase,
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
return server
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
/**
|
|
1394
|
+
* Read one raw (application/octet-stream) upload part.
|
|
1395
|
+
*
|
|
1396
|
+
* The limit is enforced while the body streams in, so an oversized part is cut
|
|
1397
|
+
* off without buffering it all; a client that leaves mid-body resolves
|
|
1398
|
+
* `aborted` and the caller answers nothing.
|
|
1399
|
+
*
|
|
1400
|
+
* @param {import('node:http').IncomingMessage} request
|
|
1401
|
+
* @param {number} limit bytes
|
|
1402
|
+
* @returns {Promise<{ ok: boolean, tooLarge: boolean, aborted: boolean, data?: Buffer }>}
|
|
1403
|
+
*/
|
|
1404
|
+
function readRawUploadBody(request, limit) {
|
|
1405
|
+
return new Promise((resolve) => {
|
|
1406
|
+
let chunks = []
|
|
1407
|
+
let received = 0
|
|
1408
|
+
let settled = false
|
|
1409
|
+
const settle = (value) => {
|
|
1410
|
+
if (settled) return
|
|
1411
|
+
settled = true
|
|
1412
|
+
const data = chunks
|
|
1413
|
+
chunks = []
|
|
1414
|
+
resolve({ data, ...value })
|
|
1415
|
+
}
|
|
1416
|
+
request.on('data', (chunk) => {
|
|
1417
|
+
if (settled) return
|
|
1418
|
+
received += chunk.length
|
|
1419
|
+
if (received > limit) {
|
|
1420
|
+
settle({ ok: false, tooLarge: true, aborted: false })
|
|
1421
|
+
return
|
|
1422
|
+
}
|
|
1423
|
+
chunks.push(Buffer.from(chunk))
|
|
1424
|
+
})
|
|
1425
|
+
request.on('end', () => {
|
|
1426
|
+
if (settled) return
|
|
1427
|
+
const data = Buffer.concat(chunks)
|
|
1428
|
+
chunks = []
|
|
1429
|
+
settled = true
|
|
1430
|
+
resolve({ ok: true, tooLarge: false, aborted: false, data })
|
|
1431
|
+
})
|
|
1432
|
+
request.on('error', () => settle({ ok: false, tooLarge: false, aborted: true }))
|
|
1433
|
+
request.on('aborted', () => settle({ ok: false, tooLarge: false, aborted: true }))
|
|
1434
|
+
})
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
function readJsonBody(request, limit = JSON_BODY_LIMIT) {
|
|
1438
|
+
return new Promise((resolve) => {
|
|
1439
|
+
let body = ''
|
|
1440
|
+
request.on('data', (chunk) => {
|
|
1441
|
+
if (body.length < limit) body += String(chunk)
|
|
1442
|
+
})
|
|
1443
|
+
request.on('end', () => {
|
|
1444
|
+
try {
|
|
1445
|
+
resolve(JSON.parse(body || '{}'))
|
|
1446
|
+
} catch {
|
|
1447
|
+
resolve({})
|
|
1448
|
+
}
|
|
1449
|
+
})
|
|
1450
|
+
request.on('error', () => resolve({}))
|
|
1451
|
+
})
|
|
1452
|
+
}
|