@muou000/dsh-wsl 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/publish.yml +26 -0
- package/LICENSE +21 -0
- package/README.md +15 -2
- package/client/wsl.js +691 -0
- package/client.js +692 -0
- package/cordis.patch.yml +8 -0
- package/icon.svg +7 -0
- package/index.mjs +2 -0
- package/lib/binding.js +8 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +13 -4
- package/vendor/wsl/LICENSE +21 -0
- package/vendor/wsl/UPSTREAM.md +16 -0
- package/vendor/wsl/icon.svg +7 -0
- package/vendor/wsl/index.mjs +691 -0
- package/vendor/wsl/locale +6 -0
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
// Adapted from dsh-wsl-folder v1.1.1 (MIT, copyright 2026 lvyuxin).
|
|
2
|
+
// See UPSTREAM.md for the pinned revision and DSH 0.2.2-rc.5 integration notes.
|
|
3
|
+
import { execFile } from 'node:child_process'
|
|
4
|
+
import { randomUUID } from 'node:crypto'
|
|
5
|
+
import { constants as fsConstants } from 'node:fs'
|
|
6
|
+
import { copyFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
7
|
+
import { isIPv4 } from 'node:net'
|
|
8
|
+
import { dataDirectory } from '../../lib/binding.js'
|
|
9
|
+
import { dirname, join, posix, win32 } from 'node:path'
|
|
10
|
+
|
|
11
|
+
export const name = 'dsh-ssh-wsl'
|
|
12
|
+
|
|
13
|
+
export const ROUTE = '/api/dsh-ssh/wsl'
|
|
14
|
+
const UNC_HOST = 'wsl.localhost'
|
|
15
|
+
const MAX_ENTRIES = 2000
|
|
16
|
+
// A distribution name is one path segment of a UNC share and one argv of `wsl.exe`; `.`/`..` are
|
|
17
|
+
// legal characters but can never name a distribution, and would turn the path into traversal.
|
|
18
|
+
const DISTRO_NAME = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,128}$/
|
|
19
|
+
const DISTRO_TTL_MS = 30_000
|
|
20
|
+
const LXSS_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss'
|
|
21
|
+
|
|
22
|
+
export class RouteError extends Error {
|
|
23
|
+
constructor(code, message, status = 200) {
|
|
24
|
+
super(message)
|
|
25
|
+
this.code = code
|
|
26
|
+
this.status = status
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// ── WSL path helpers ───────────────────────────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
/** `\\wsl.localhost\D\a\b` or `\\wsl$\D\a\b` (either slash) -> { distro, path: '/a/b' }. */
|
|
33
|
+
export function parseWslUnc(value) {
|
|
34
|
+
if (typeof value !== 'string') return undefined
|
|
35
|
+
// Namespaced spellings (`\\?\UNC\wsl.localhost\...`) name the same share.
|
|
36
|
+
const plain = value.replace(/^[\\/]{2}[?.][\\/]UNC[\\/]/i, '\\\\')
|
|
37
|
+
const match = /^[\\/]{2}(?:wsl\.localhost|wsl\$)[\\/]([^\\/]+)(?:[\\/](.*))?$/i.exec(plain)
|
|
38
|
+
if (match === null || !DISTRO_NAME.test(match[1])) return undefined
|
|
39
|
+
const rest = (match[2] ?? '').split(/[\\/]+/).filter(Boolean)
|
|
40
|
+
// Collapse `.`/`..`/duplicate separators: a UNC cwd and a Linux path must agree segment for segment.
|
|
41
|
+
return { distro: match[1], path: rest.length === 0 ? '/' : posix.normalize(`/${rest.join('/')}`) }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function toUnc(distro, linuxPath) {
|
|
45
|
+
const rest = linuxPath === '/' ? '' : linuxPath.slice(1).split('/').join('\\')
|
|
46
|
+
return `\\\\${UNC_HOST}\\${distro}\\${rest}`
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function requireDistro(value) {
|
|
50
|
+
if (typeof value !== 'string' || !DISTRO_NAME.test(value)) {
|
|
51
|
+
throw new RouteError('bad-distro', `invalid distribution name: ${String(value)}`, 400)
|
|
52
|
+
}
|
|
53
|
+
return value
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function requireLinuxPath(value) {
|
|
57
|
+
if (typeof value !== 'string' || !value.startsWith('/') || value.includes('\0') || value.includes('\\')) {
|
|
58
|
+
throw new RouteError('bad-path', `invalid Linux path: ${String(value)}`, 400)
|
|
59
|
+
}
|
|
60
|
+
const normalized = posix.normalize(value)
|
|
61
|
+
return normalized.length > 1 ? normalized.replace(/\/+$/, '') : '/'
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function wslExe() {
|
|
65
|
+
return join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'wsl.exe')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ── process helpers ────────────────────────────────────────────────────────────
|
|
69
|
+
|
|
70
|
+
/** wsl.exe prints UTF-16LE unless WSL_UTF8 is honoured; accept both. */
|
|
71
|
+
export function decode(buffer) {
|
|
72
|
+
if (!buffer || buffer.length === 0) return ''
|
|
73
|
+
// A UTF-16LE BOM is decisive; text without ASCII (a Chinese-only message, say) has no NUL byte
|
|
74
|
+
// to detect, so the BOM check has to come before the zero-byte heuristic.
|
|
75
|
+
const text = buffer.length >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE
|
|
76
|
+
? buffer.toString('utf16le')
|
|
77
|
+
: buffer.includes(0) ? buffer.toString('utf16le') : buffer.toString('utf8')
|
|
78
|
+
return text.replace(/^\uFEFF/, '')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function run(file, args, timeout, { raw = false } = {}) {
|
|
82
|
+
return new Promise((resolve, reject) => {
|
|
83
|
+
execFile(file, args, {
|
|
84
|
+
encoding: 'buffer',
|
|
85
|
+
timeout,
|
|
86
|
+
windowsHide: true,
|
|
87
|
+
env: { ...process.env, WSL_UTF8: '1' },
|
|
88
|
+
}, (error, stdout, stderr) => {
|
|
89
|
+
if (error) {
|
|
90
|
+
const failure = new RouteError('wsl-failed', (decode(stderr) || decode(stdout) || error.message).trim())
|
|
91
|
+
failure.exitCode = typeof error.code === 'number' ? error.code : undefined
|
|
92
|
+
reject(failure)
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
resolve(raw ? stdout : decode(stdout))
|
|
96
|
+
})
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ── distributions ──────────────────────────────────────────────────────────────
|
|
101
|
+
|
|
102
|
+
/** Parse `reg query <Lxss> /s`: one subkey per distribution, plus the default's GUID. */
|
|
103
|
+
export function parseLxss(text) {
|
|
104
|
+
const defaultGuid = /DefaultDistribution\s+REG_SZ\s+(\{[^}]+\})/i.exec(text)?.[1]?.toLowerCase()
|
|
105
|
+
const distros = []
|
|
106
|
+
for (const block of text.split(/\r?\n(?=HKEY_)/)) {
|
|
107
|
+
const guid = /\\Lxss\\(\{[^}]+\})/i.exec(block)?.[1]?.toLowerCase()
|
|
108
|
+
const distroName = /DistributionName\s+REG_SZ\s+([^\r\n]+)/i.exec(block)?.[1]?.trim()
|
|
109
|
+
if (guid === undefined || distroName === undefined || !DISTRO_NAME.test(distroName)) continue
|
|
110
|
+
const version = Number.parseInt(/\bVersion\s+REG_DWORD\s+(0x[0-9a-f]+)/i.exec(block)?.[1] ?? '0x2', 16)
|
|
111
|
+
const uid = Number.parseInt(/DefaultUid\s+REG_DWORD\s+(0x[0-9a-f]+)/i.exec(block)?.[1] ?? '0x0', 16)
|
|
112
|
+
distros.push({ name: distroName, default: guid === defaultGuid, version, uid })
|
|
113
|
+
}
|
|
114
|
+
return distros
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function distrosFromWslExe() {
|
|
118
|
+
const text = await run(wslExe(), ['-l', '-v'], 20_000)
|
|
119
|
+
const distros = []
|
|
120
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
121
|
+
const match = /^\s*(\*)?\s*(\S+)\s+(\S+)\s+(\d+)\s*$/.exec(raw)
|
|
122
|
+
if (match === null || !DISTRO_NAME.test(match[2])) continue
|
|
123
|
+
distros.push({ name: match[2], default: match[1] === '*', version: Number(match[4]), uid: undefined })
|
|
124
|
+
}
|
|
125
|
+
return distros
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
let distroCache // { at, value: Promise<distro[]> }
|
|
129
|
+
|
|
130
|
+
function listDistros() {
|
|
131
|
+
if (distroCache !== undefined && Date.now() - distroCache.at < DISTRO_TTL_MS) return distroCache.value
|
|
132
|
+
const value = run(join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'reg.exe'), ['query', LXSS_KEY, '/s'], 10_000)
|
|
133
|
+
.then(parseLxss)
|
|
134
|
+
.catch(() => [])
|
|
135
|
+
.then((found) => (found.length > 0 ? found : distrosFromWslExe()))
|
|
136
|
+
distroCache = { at: Date.now(), value }
|
|
137
|
+
value.catch(() => { distroCache = undefined })
|
|
138
|
+
return value
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ── home directory ─────────────────────────────────────────────────────────────
|
|
142
|
+
|
|
143
|
+
const homeCache = new Map()
|
|
144
|
+
|
|
145
|
+
/** INI comment stripping that respects quoted values (`command = "a; b"` keeps the semicolon). */
|
|
146
|
+
function stripIniComment(line) {
|
|
147
|
+
let quoted = false
|
|
148
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
149
|
+
const char = line[index]
|
|
150
|
+
if (char === '"') quoted = !quoted
|
|
151
|
+
else if (!quoted && (char === '#' || char === ';')) return line.slice(0, index)
|
|
152
|
+
}
|
|
153
|
+
return line
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** One `key = value` from an INI-style /etc/wsl.conf section, when present. */
|
|
157
|
+
export function wslConfValue(text, wantedSection, wantedKey) {
|
|
158
|
+
const sectionWanted = String(wantedSection ?? '').trim().toLowerCase()
|
|
159
|
+
const keyWanted = String(wantedKey ?? '').trim().toLowerCase()
|
|
160
|
+
let section = ''
|
|
161
|
+
for (const raw of String(text ?? '').split(/\r?\n/)) {
|
|
162
|
+
const line = stripIniComment(raw).trim()
|
|
163
|
+
const header = /^\[(.+)\]$/.exec(line)
|
|
164
|
+
if (header !== null) { section = header[1].trim().toLowerCase(); continue }
|
|
165
|
+
const pair = /^([\w.-]+)\s*=\s*"?([^"]*?)"?\s*$/.exec(line)
|
|
166
|
+
if (section === sectionWanted && pair !== null && pair[1].toLowerCase() === keyWanted) return pair[2]
|
|
167
|
+
}
|
|
168
|
+
return undefined
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** `[user] default=<name>` from /etc/wsl.conf, when present. */
|
|
172
|
+
export function wslConfDefaultUser(text) {
|
|
173
|
+
const user = wslConfValue(text, 'user', 'default')
|
|
174
|
+
return user === undefined || user === '' ? undefined : user
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Normalize an automount root to `/x/`; WSL's default (an empty setting) is `/mnt/`. */
|
|
178
|
+
function normalizeAutomountRoot(value) {
|
|
179
|
+
const raw = String(value ?? '').trim()
|
|
180
|
+
if (raw === '') return '/mnt/'
|
|
181
|
+
const trimmed = raw.replace(/\/+$/, '')
|
|
182
|
+
return `${trimmed.startsWith('/') ? '' : '/'}${trimmed}/`.replace(/\/+/g, '/')
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** `[automount] root=` from /etc/wsl.conf, normalized to `/x/`; WSL's default is `/mnt/`. */
|
|
186
|
+
export function wslConfAutomountRoot(text) {
|
|
187
|
+
const root = wslConfValue(text, 'automount', 'root')
|
|
188
|
+
return normalizeAutomountRoot(root)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* The Windows path behind a drvfs mount: `/mnt/d/a/b` -> `D:\a\b` (with the distribution's
|
|
193
|
+
* automount root). Returns undefined for any other Linux path.
|
|
194
|
+
*/
|
|
195
|
+
export function drvfsWindowsPath(linuxPath, root = '/mnt/') {
|
|
196
|
+
if (root === null) return undefined
|
|
197
|
+
const escaped = normalizeAutomountRoot(root).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
198
|
+
const match = new RegExp(`^${escaped}([a-zA-Z])(?:/(.*))?$`).exec(linuxPath)
|
|
199
|
+
if (match === null) return undefined
|
|
200
|
+
const rest = (match[2] ?? '').split('/').filter(Boolean).join('\\')
|
|
201
|
+
return `${match[1].toUpperCase()}:\\${rest}`
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const confCache = new Map() // distro -> { at, value: Promise<string> }
|
|
205
|
+
|
|
206
|
+
function wslConf(distro) {
|
|
207
|
+
const cached = confCache.get(distro)
|
|
208
|
+
if (cached !== undefined && Date.now() - cached.at < DISTRO_TTL_MS) return cached.value
|
|
209
|
+
const value = readFile(`${toUnc(distro, '/')}etc\\wsl.conf`, 'utf8').catch(() => '')
|
|
210
|
+
confCache.set(distro, { at: Date.now(), value })
|
|
211
|
+
return value
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function automountRoot(distro) {
|
|
215
|
+
const conf = await wslConf(distro)
|
|
216
|
+
if (wslConfValue(conf, 'automount', 'enabled')?.toLowerCase() === 'false') return null
|
|
217
|
+
return wslConfAutomountRoot(conf)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function passwdHome(text, user) {
|
|
221
|
+
for (const line of text.split(/\r?\n/)) {
|
|
222
|
+
const fields = line.split(':')
|
|
223
|
+
if (fields.length < 7) continue
|
|
224
|
+
if (typeof user === 'string' ? fields[0] === user : Number(fields[2]) === user) return fields[5]
|
|
225
|
+
}
|
|
226
|
+
return undefined
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function homeFromFiles(distro) {
|
|
230
|
+
const root = toUnc(distro, '/')
|
|
231
|
+
const passwd = await readFile(`${root}etc\\passwd`, 'utf8')
|
|
232
|
+
const conf = await wslConf(distro)
|
|
233
|
+
const user = wslConfDefaultUser(conf)
|
|
234
|
+
if (user !== undefined) return passwdHome(passwd, user)
|
|
235
|
+
const uid = (await listDistros()).find((d) => d.name === distro)?.uid
|
|
236
|
+
return uid === undefined ? undefined : passwdHome(passwd, uid)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function resolveHome(distro) {
|
|
240
|
+
let home
|
|
241
|
+
try {
|
|
242
|
+
home = await homeFromFiles(distro)
|
|
243
|
+
} catch {
|
|
244
|
+
home = undefined
|
|
245
|
+
}
|
|
246
|
+
if (typeof home !== 'string' || !home.startsWith('/')) {
|
|
247
|
+
home = (await run(wslExe(), ['-d', distro, '-e', 'sh', '-c', 'printf %s "$HOME"'], 30_000)).trim()
|
|
248
|
+
}
|
|
249
|
+
return home.startsWith('/') ? requireLinuxPath(home) : '/'
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function homeOf(distro) {
|
|
253
|
+
let pending = homeCache.get(distro)
|
|
254
|
+
if (pending === undefined) {
|
|
255
|
+
pending = resolveHome(distro)
|
|
256
|
+
homeCache.set(distro, pending)
|
|
257
|
+
pending.catch(() => homeCache.delete(distro))
|
|
258
|
+
}
|
|
259
|
+
return pending
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ── listing ────────────────────────────────────────────────────────────────────
|
|
263
|
+
|
|
264
|
+
function errorCode(error) {
|
|
265
|
+
return error?.code === 'ENOENT' || error?.code === 'ENOTDIR' ? 'not-found'
|
|
266
|
+
: error?.code === 'EACCES' || error?.code === 'EPERM' ? 'denied'
|
|
267
|
+
: 'unreadable'
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Subdirectory names read through a Windows-visible path (UNC share or drive letter). */
|
|
271
|
+
async function namesFromWindows(source) {
|
|
272
|
+
const dirents = await readdir(source, { withFileTypes: true })
|
|
273
|
+
const names = []
|
|
274
|
+
const links = []
|
|
275
|
+
for (const dirent of dirents) {
|
|
276
|
+
if (dirent.isDirectory()) names.push(dirent.name)
|
|
277
|
+
else if (dirent.isSymbolicLink()) links.push(dirent.name)
|
|
278
|
+
}
|
|
279
|
+
// A symlinked directory (or a junction on a Windows drive) counts when it resolves.
|
|
280
|
+
const base = source.endsWith('\\') ? source : `${source}\\`
|
|
281
|
+
const resolved = await Promise.all(links.slice(0, 200).map(async (entry) => {
|
|
282
|
+
try {
|
|
283
|
+
return (await stat(`${base}${entry}`)).isDirectory() ? entry : null
|
|
284
|
+
} catch {
|
|
285
|
+
return null
|
|
286
|
+
}
|
|
287
|
+
}))
|
|
288
|
+
for (const entry of resolved) if (entry !== null) names.push(entry)
|
|
289
|
+
return names
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Subdirectory names read by `find` inside the distribution: slow, but it sees every mount. */
|
|
293
|
+
async function namesFromDistribution(distro, linuxPath) {
|
|
294
|
+
const script = '[ -d "$1" ] || exit 3; [ -r "$1" ] && [ -x "$1" ] || exit 4; '
|
|
295
|
+
+ 'find -L "$1" -mindepth 1 -maxdepth 1 -type d -printf "%f\\0" 2>/dev/null; exit 0'
|
|
296
|
+
let output
|
|
297
|
+
try {
|
|
298
|
+
output = await run(wslExe(), ['-d', distro, '-e', 'sh', '-c', script, 'sh', linuxPath], 30_000, { raw: true })
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (error?.exitCode === 3) throw new RouteError('not-found', `${linuxPath}: no such directory`)
|
|
301
|
+
if (error?.exitCode === 4) throw new RouteError('denied', `${linuxPath}: permission denied for the distribution's default user`)
|
|
302
|
+
throw error
|
|
303
|
+
}
|
|
304
|
+
return output.toString('utf8').split('\0').filter((entry) => entry !== '')
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function listDirectory(distro, linuxPath) {
|
|
308
|
+
const windowsDrive = drvfsWindowsPath(linuxPath, await automountRoot(distro))
|
|
309
|
+
const target = windowsDrive ?? toUnc(distro, linuxPath)
|
|
310
|
+
let names
|
|
311
|
+
try {
|
|
312
|
+
names = await namesFromWindows(target)
|
|
313
|
+
} catch (error) {
|
|
314
|
+
// The UNC share refuses some mounts (EPERM); the distribution itself can still list them.
|
|
315
|
+
if (windowsDrive !== undefined || errorCode(error) !== 'denied') throw new RouteError(errorCode(error), String(error?.message ?? error))
|
|
316
|
+
names = await namesFromDistribution(distro, linuxPath)
|
|
317
|
+
}
|
|
318
|
+
names.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base', numeric: true }))
|
|
319
|
+
const entries = names.slice(0, MAX_ENTRIES).map((entry) => ({
|
|
320
|
+
name: entry,
|
|
321
|
+
path: linuxPath === '/' ? `/${entry}` : `${linuxPath}/${entry}`,
|
|
322
|
+
hidden: entry.startsWith('.'),
|
|
323
|
+
}))
|
|
324
|
+
return {
|
|
325
|
+
distro,
|
|
326
|
+
path: linuxPath,
|
|
327
|
+
parent: linuxPath === '/' ? null : posix.dirname(linuxPath),
|
|
328
|
+
target,
|
|
329
|
+
entries,
|
|
330
|
+
truncated: names.length > MAX_ENTRIES,
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ── folders picked from WSL that live on a Windows drive ───────────────────────
|
|
335
|
+
|
|
336
|
+
/** Where the WSL origin of Windows-drive workspaces is remembered (survives restarts). */
|
|
337
|
+
function memoryFile() {
|
|
338
|
+
return join(dataDirectory(), 'wsl-folders.json')
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const folderKey = (windowsPath) => win32.normalize(windowsPath).replace(/\\+$/, '').toLowerCase()
|
|
342
|
+
|
|
343
|
+
let folders // Map<folderKey, { distro, path, target }>, loaded once
|
|
344
|
+
let foldersLoading
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* A remembered Linux path, normalized; undefined when it cannot be trusted. The file lives in
|
|
348
|
+
* <DSH home>, so a hand-edited or stale entry must not smuggle `..`/NUL/backslashes into a
|
|
349
|
+
* terminal's `--cd` argument.
|
|
350
|
+
*/
|
|
351
|
+
function rememberedLinuxPath(value) {
|
|
352
|
+
if (typeof value !== 'string' || !value.startsWith('/') || value.includes('\0') || value.includes('\\')) return undefined
|
|
353
|
+
const segments = value.split('/').filter(Boolean)
|
|
354
|
+
if (segments.includes('..')) return undefined
|
|
355
|
+
const normalized = posix.normalize(`/${segments.join('/')}`)
|
|
356
|
+
return normalized.length > 1 ? normalized.replace(/\/+$/, '') : '/'
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** A remembered entry is trusted only when every field has the shape the terminal redirect uses. */
|
|
360
|
+
function rememberedEntry(entry) {
|
|
361
|
+
if (typeof entry?.target !== 'string' || !/^[a-zA-Z]:[\\/]/.test(entry.target) || entry.target === '') return undefined
|
|
362
|
+
if (!DISTRO_NAME.test(entry?.distro ?? '')) return undefined
|
|
363
|
+
const path = rememberedLinuxPath(entry?.path)
|
|
364
|
+
return path === undefined ? undefined : { distro: entry.distro, path, target: entry.target }
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
async function loadFolders() {
|
|
368
|
+
if (folders !== undefined) return folders
|
|
369
|
+
// Keep one shared load: assigning the empty map before the read let a second caller see an
|
|
370
|
+
// empty map and overwrite the file with it before the first read finished.
|
|
371
|
+
if (foldersLoading !== undefined) return foldersLoading
|
|
372
|
+
foldersLoading = (async () => {
|
|
373
|
+
const map = new Map()
|
|
374
|
+
try {
|
|
375
|
+
const saved = JSON.parse(await readFile(memoryFile(), 'utf8'))
|
|
376
|
+
for (const raw of Array.isArray(saved?.folders) ? saved.folders : []) {
|
|
377
|
+
const entry = rememberedEntry(raw)
|
|
378
|
+
if (entry !== undefined) map.set(folderKey(entry.target), entry)
|
|
379
|
+
}
|
|
380
|
+
} catch (error) {
|
|
381
|
+
if (error.code !== 'ENOENT') throw error
|
|
382
|
+
}
|
|
383
|
+
folders = map
|
|
384
|
+
return map
|
|
385
|
+
})()
|
|
386
|
+
try {
|
|
387
|
+
return await foldersLoading
|
|
388
|
+
} finally {
|
|
389
|
+
foldersLoading = undefined
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** One serialized writer: concurrent picks would otherwise race on the temp name and the rename. */
|
|
394
|
+
let folderWrite = Promise.resolve()
|
|
395
|
+
|
|
396
|
+
/** Test seam: remember one Windows-drive folder (production callers reach it through `pick`). */
|
|
397
|
+
export async function rememberFolder(entry) {
|
|
398
|
+
const remembered = rememberedEntry(entry)
|
|
399
|
+
if (remembered === undefined) throw new RouteError('bad-path', 'invalid remembered folder', 400)
|
|
400
|
+
const map = await loadFolders()
|
|
401
|
+
const write = folderWrite.catch(() => {}).then(async () => {
|
|
402
|
+
const next = new Map(map).set(folderKey(remembered.target), remembered)
|
|
403
|
+
const file = memoryFile()
|
|
404
|
+
await mkdir(dirname(file), { recursive: true, mode: 0o700 })
|
|
405
|
+
const temp = `${file}.${process.pid}.${randomUUID()}.tmp`
|
|
406
|
+
try {
|
|
407
|
+
await writeFile(temp, `${JSON.stringify({ version: 1, folders: [...next.values()] }, null, 2)}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 })
|
|
408
|
+
await rename(temp, file)
|
|
409
|
+
map.set(folderKey(remembered.target), remembered)
|
|
410
|
+
} finally {
|
|
411
|
+
await rm(temp, { force: true }).catch(() => {})
|
|
412
|
+
}
|
|
413
|
+
})
|
|
414
|
+
folderWrite = write
|
|
415
|
+
return write
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** The remembered WSL folder containing `cwd` (the workspace itself or a directory below it). */
|
|
419
|
+
export function findFolder(map, cwd) {
|
|
420
|
+
if (typeof cwd !== 'string' || !/^[a-zA-Z]:[\\/]/.test(cwd)) return undefined
|
|
421
|
+
let key = folderKey(cwd)
|
|
422
|
+
for (;;) {
|
|
423
|
+
const hit = map.get(key)
|
|
424
|
+
if (hit !== undefined) return hit
|
|
425
|
+
const parent = win32.dirname(key)
|
|
426
|
+
if (parent === key || parent.length < 3) return map.get(parent.replace(/\\+$/, ''))
|
|
427
|
+
key = parent.replace(/\\+$/, '')
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async function pick(distro, linuxPath) {
|
|
432
|
+
const windowsDrive = drvfsWindowsPath(linuxPath, await automountRoot(distro))
|
|
433
|
+
const target = windowsDrive ?? toUnc(distro, linuxPath)
|
|
434
|
+
try {
|
|
435
|
+
if (!(await stat(target)).isDirectory()) throw new RouteError('not-found', `${target} is not a directory`)
|
|
436
|
+
} catch (error) {
|
|
437
|
+
if (error instanceof RouteError) throw error
|
|
438
|
+
throw new RouteError(errorCode(error), String(error?.message ?? error))
|
|
439
|
+
}
|
|
440
|
+
if (windowsDrive !== undefined) await rememberFolder({ distro, path: linuxPath, target })
|
|
441
|
+
return { target }
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Exact Connection Fetch routes inherit DSH's browser trust, authentication and owner-only
|
|
445
|
+
// admission on every carrier. The HTTP waterfall additionally enforces this plugin's local default.
|
|
446
|
+
export function isLoopbackAddress(address) {
|
|
447
|
+
if (typeof address !== 'string') return false
|
|
448
|
+
const ip = address.toLowerCase().replace(/^::ffff:/, '')
|
|
449
|
+
return ip === '::1' || (isIPv4(ip) && ip.startsWith('127.'))
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
export function localRequestGuard(request, response, next) {
|
|
453
|
+
const pathname = new URL(request.url ?? '/', 'http://localhost').pathname
|
|
454
|
+
if (!pathname.startsWith(`${ROUTE}/`) || isLoopbackAddress(request.socket?.remoteAddress)) return next()
|
|
455
|
+
response.writeHead(403, { 'content-type': 'application/json', 'cache-control': 'no-store' })
|
|
456
|
+
response.end(JSON.stringify({ error: 'forbidden', message: 'WSL browsing is limited to loopback clients' }))
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const MAX_BODY_BYTES = 4096
|
|
460
|
+
async function jsonBody(request) {
|
|
461
|
+
const reader = request.body?.getReader()
|
|
462
|
+
if (!reader) throw new RouteError('bad-request', 'expected a JSON object', 400)
|
|
463
|
+
const chunks = []
|
|
464
|
+
let size = 0
|
|
465
|
+
try {
|
|
466
|
+
for (;;) {
|
|
467
|
+
const { value, done } = await reader.read()
|
|
468
|
+
if (done) break
|
|
469
|
+
size += value.byteLength
|
|
470
|
+
if (size > MAX_BODY_BYTES) {
|
|
471
|
+
await reader.cancel().catch(() => {})
|
|
472
|
+
throw new RouteError('bad-request', 'the JSON request exceeds 4096 bytes', 413)
|
|
473
|
+
}
|
|
474
|
+
chunks.push(value)
|
|
475
|
+
}
|
|
476
|
+
const value = JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
477
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('expected an object')
|
|
478
|
+
return value
|
|
479
|
+
} catch (error) {
|
|
480
|
+
if (error instanceof RouteError) throw error
|
|
481
|
+
throw new RouteError('bad-request', 'expected a JSON object', 400)
|
|
482
|
+
} finally {
|
|
483
|
+
reader.releaseLock()
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// Inputs such as /mnt/c must not fall through to the Windows drive if the named distro is absent.
|
|
488
|
+
export function createRoutes({ distributions = listDistros, listing = listDirectory, home = homeOf, select = pick, pickerKind = () => 'native' } = {}) {
|
|
489
|
+
async function installed(value) {
|
|
490
|
+
const name = requireDistro(value)
|
|
491
|
+
const match = (await distributions()).find(d => d.name.toLowerCase() === name.toLowerCase())
|
|
492
|
+
if (match === undefined) throw new RouteError('bad-distro', 'distribution is not installed', 404)
|
|
493
|
+
return match.name
|
|
494
|
+
}
|
|
495
|
+
return {
|
|
496
|
+
capabilities: { method: 'GET', handle: () => ({ wsl: true, picker: pickerKind() }) },
|
|
497
|
+
distros: { method: 'GET', handle: async () => ({ distros: (await distributions()).map(({ name, default: preferred, version }) => ({ name, default: preferred, version })) }) },
|
|
498
|
+
home: { method: 'GET', handle: async q => ({ home: await home(await installed(q.get('distro'))) }) },
|
|
499
|
+
list: { method: 'GET', handle: async q => {
|
|
500
|
+
const path = requireLinuxPath(q.get('path') ?? '/')
|
|
501
|
+
return listing(await installed(q.get('distro')), path)
|
|
502
|
+
} },
|
|
503
|
+
pick: { method: 'POST', handle: async (_q, body) => {
|
|
504
|
+
const path = requireLinuxPath(body.path)
|
|
505
|
+
return select(await installed(body.distro), path)
|
|
506
|
+
} },
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
export async function serve(request, route) {
|
|
511
|
+
const headers = { 'cache-control': 'no-store' }
|
|
512
|
+
const json = (value, status = 200) => Response.json(value, { status, headers })
|
|
513
|
+
if (request.method !== route.method) return new Response(null, { status: 405, headers: { ...headers, allow: route.method } })
|
|
514
|
+
const site = request.headers.get('sec-fetch-site')
|
|
515
|
+
if (site && site !== 'same-origin' && site !== 'none') return json({ error: 'forbidden', message: 'cross-site request refused' }, 403)
|
|
516
|
+
if (route.method === 'POST' && !/^application\/json\s*(?:;|$)/i.test(request.headers.get('content-type') ?? '')) {
|
|
517
|
+
return json({ error: 'bad-request', message: 'expected application/json' }, 415)
|
|
518
|
+
}
|
|
519
|
+
try {
|
|
520
|
+
const body = route.method === 'POST' ? await jsonBody(request) : undefined
|
|
521
|
+
request.signal.throwIfAborted()
|
|
522
|
+
return json(await route.handle(new URL(request.url).searchParams, body))
|
|
523
|
+
} catch (error) {
|
|
524
|
+
if (error instanceof RouteError) return json({ error: error.code, message: error.message }, error.status)
|
|
525
|
+
return json({ error: 'internal', message: String(error?.message ?? error) }, 500)
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
const WRAPPED = Symbol.for('dsh-ssh.wsl.wrapped')
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* Replace `owner[key]` with `wrap(original)` and return the restoring disposer. The disposer
|
|
533
|
+
* leaves a later replacement by someone else in place.
|
|
534
|
+
*/
|
|
535
|
+
export function patchMethod(owner, key, wrap) {
|
|
536
|
+
const original = owner[key]
|
|
537
|
+
if (typeof original !== 'function' || original[WRAPPED] === true) return () => {}
|
|
538
|
+
const own = Object.getOwnPropertyDescriptor(owner, key)
|
|
539
|
+
const replacement = wrap(original)
|
|
540
|
+
replacement[WRAPPED] = true
|
|
541
|
+
owner[key] = replacement
|
|
542
|
+
return () => {
|
|
543
|
+
if (owner[key] !== replacement) return
|
|
544
|
+
if (own) Object.defineProperty(owner, key, own)
|
|
545
|
+
else delete owner[key]
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Where a sidebar terminal for `cwd` should start inside WSL, if anywhere: a `\\wsl.localhost`
|
|
551
|
+
* workspace, or a Windows folder (or a directory below one) that was picked from WSL.
|
|
552
|
+
* `path` is the Linux path passed to wsl.exe --cd, including for custom automount roots.
|
|
553
|
+
*/
|
|
554
|
+
export function wslTargetOf(cwd, remembered = folders) {
|
|
555
|
+
const unc = parseWslUnc(cwd)
|
|
556
|
+
if (unc !== undefined) return { distro: unc.distro, cd: unc.path, path: unc.path }
|
|
557
|
+
const folder = remembered === undefined ? undefined : findFolder(remembered, cwd)
|
|
558
|
+
if (folder === undefined) return undefined
|
|
559
|
+
const below = win32.normalize(cwd).slice(win32.normalize(folder.target).replace(/\\+$/, '').length)
|
|
560
|
+
const tail = below.split(/[\\/]+/).filter(Boolean).join('/')
|
|
561
|
+
return { distro: folder.distro, cd: win32.normalize(cwd), path: tail ? `${folder.path.replace(/\/+$/, '')}/${tail}` : folder.path }
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// rc.5 passes both user and sandboxed Agent terminals through spawn(). Only userLaunch()
|
|
565
|
+
// prepares a human terminal. Leave its Windows cwd in place: spawnTerminal uses it as process cwd.
|
|
566
|
+
export function installTerminalRedirect(ctx, controller) {
|
|
567
|
+
if (process.platform !== 'win32') return () => {}
|
|
568
|
+
if (typeof controller?.userLaunch !== 'function') {
|
|
569
|
+
ctx.logger?.warn?.('dsh-ssh: WSL terminal integration requires TerminalController.userLaunch')
|
|
570
|
+
return () => {}
|
|
571
|
+
}
|
|
572
|
+
return patchMethod(controller, 'userLaunch', original => async function (...args) {
|
|
573
|
+
const launch = await original.apply(this, args)
|
|
574
|
+
if (launch?.info?.origin !== 'user' || launch.info.control !== 'user') return launch
|
|
575
|
+
const cwd = launch.info.cwd
|
|
576
|
+
let target = wslTargetOf(cwd)
|
|
577
|
+
if (!target && typeof cwd === 'string' && /^[a-z]:[\\/]/i.test(cwd)) {
|
|
578
|
+
// Wait for a cold map only when resolving a Windows-drive workspace.
|
|
579
|
+
try { target = wslTargetOf(cwd, await loadFolders()) }
|
|
580
|
+
catch (error) { ctx.logger?.warn?.(`dsh-ssh: cannot read WSL folder origins: ${error.message}`) }
|
|
581
|
+
}
|
|
582
|
+
if (!target) return launch
|
|
583
|
+
const path = wslExe()
|
|
584
|
+
const argv = [path, '-d', target.distro, '--cd', target.path]
|
|
585
|
+
const title = `WSL · ${target.distro}`
|
|
586
|
+
return { ...launch, argv, info: { ...launch.info, title, shell: { name: title, path, args: argv.slice(1) } } }
|
|
587
|
+
})
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// ── agent writes on the WSL share ──────────────────────────────────────────────
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Publication primitives for one write whose target is on WSL's 9P share. `platform: 'linux'`
|
|
594
|
+
* selects DSH's POSIX publication (rename over the file) instead of the Windows DACL copy and
|
|
595
|
+
* ReplaceFileW, which the share rejects; an exclusive copy stands in for the hard link that
|
|
596
|
+
* publishes a new file, keeping its no-clobber result (EEXIST when someone created the file first).
|
|
597
|
+
*/
|
|
598
|
+
export function wslWriteInternals(base = {}) {
|
|
599
|
+
return {
|
|
600
|
+
...base,
|
|
601
|
+
platform: 'linux',
|
|
602
|
+
linkFile: (source, destination) => copyFile(source, destination, fsConstants.COPYFILE_EXCL),
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* The prototype that implements DSH's local filesystem writes: the nearest one on the chain that
|
|
608
|
+
* owns `writeText`, `editText` and the per-target `withLock`. Subclasses (the sandboxed filesystem)
|
|
609
|
+
* reach it through `super`, so one patch serves every instance in the process.
|
|
610
|
+
*/
|
|
611
|
+
export function findLocalFileSystemProto(fs) {
|
|
612
|
+
for (let proto = Object.getPrototypeOf(fs ?? {}); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
613
|
+
const own = (key) => typeof Object.getOwnPropertyDescriptor(proto, key)?.value === 'function'
|
|
614
|
+
if (own('writeText') && own('editText') && own('withLock')) return proto
|
|
615
|
+
}
|
|
616
|
+
return undefined
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** Only repair an address under the same WSL share as the operation's working directory.
|
|
620
|
+
* A real Windows directory named C:\wsl.localhost on a native workspace remains a native path. */
|
|
621
|
+
export function repairWslSpelling(value, cwd) {
|
|
622
|
+
const workspace = parseWslUnc(cwd)
|
|
623
|
+
if (!workspace || typeof value !== 'string') return value
|
|
624
|
+
const match = /^(?:[a-z]:)?[\\/](wsl\.localhost|wsl\$)[\\/]([^\\/]+)([\\/].*)?$/i.exec(value)
|
|
625
|
+
if (!match || match[2].toLowerCase() !== workspace.distro.toLowerCase()) return value
|
|
626
|
+
return `\\\\${match[1]}\\${match[2]}${match[3] ?? ''}`
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
export function installWslPathRepair(ctx, fs) {
|
|
630
|
+
if (process.platform !== 'win32') return () => {}
|
|
631
|
+
const proto = findLocalFileSystemProto(fs)
|
|
632
|
+
if (!proto) return () => {}
|
|
633
|
+
const restores = ['resolve', 'lstat'].map(key => patchMethod(proto, key, original => function (path, opts, ...rest) {
|
|
634
|
+
return original.call(this, repairWslSpelling(path, opts?.cwd ?? this.config?.cwd), opts, ...rest)
|
|
635
|
+
}))
|
|
636
|
+
return () => { for (const restore of restores.reverse()) restore() }
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
export function installWslWriteSupport(ctx, fs) {
|
|
640
|
+
if (process.platform !== 'win32') return () => {}
|
|
641
|
+
const proto = findLocalFileSystemProto(fs)
|
|
642
|
+
if (proto === undefined) {
|
|
643
|
+
ctx.logger?.warn?.('dsh-ssh: the filesystem provider is not DSH\'s local filesystem; WSL write support is off')
|
|
644
|
+
return () => {}
|
|
645
|
+
}
|
|
646
|
+
// A per-call view of the instance: only `internals` differs, and every other member (locks,
|
|
647
|
+
// config) still resolves to the real instance through the prototype.
|
|
648
|
+
const onShare = (self, target) => (parseWslUnc(target?.targetKey) === undefined
|
|
649
|
+
? self
|
|
650
|
+
: Object.create(self, { internals: { value: wslWriteInternals(self.internals), configurable: true, writable: true } }))
|
|
651
|
+
// moveFile publishes its destination. The sandbox subclass checks both paths before super.
|
|
652
|
+
const restores = ['writeText', 'editText', 'patchText', 'moveFile'].map(key =>
|
|
653
|
+
patchMethod(proto, key, original => function (...args) {
|
|
654
|
+
return original.apply(onShare(this, args[key === 'moveFile' ? 1 : 0]), args)
|
|
655
|
+
}))
|
|
656
|
+
return () => { for (const restore of restores.reverse()) restore() }
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// ── plugin ─────────────────────────────────────────────────────────────────────
|
|
660
|
+
|
|
661
|
+
export const inject = ['connection']
|
|
662
|
+
|
|
663
|
+
export function apply(ctx, config = {}) {
|
|
664
|
+
if (process.platform !== 'win32') return
|
|
665
|
+
if (config.remote !== true) ctx.on('connection/request', localRequestGuard)
|
|
666
|
+
let picker = null
|
|
667
|
+
ctx.inject(['directoryPicker'], inner => {
|
|
668
|
+
inner.effect(() => {
|
|
669
|
+
picker = inner.directoryPicker.capability().kind
|
|
670
|
+
return () => { picker = null }
|
|
671
|
+
}, 'dsh-ssh: picker capability')
|
|
672
|
+
})
|
|
673
|
+
const routes = createRoutes({ pickerKind: () => picker })
|
|
674
|
+
for (const [key, route] of Object.entries(routes)) {
|
|
675
|
+
ctx.connection.fetch.register({
|
|
676
|
+
path: `${ROUTE}/${key}`, methods: [route.method], requestBody: route.method === 'GET' ? 'buffered' : 'streaming',
|
|
677
|
+
fetch: request => serve(request, route),
|
|
678
|
+
})
|
|
679
|
+
}
|
|
680
|
+
if (config.terminal !== false) {
|
|
681
|
+
ctx.inject(['terminalController'], inner => {
|
|
682
|
+
inner.effect(() => installTerminalRedirect(inner, inner.terminalController), 'dsh-ssh: WSL user terminals')
|
|
683
|
+
})
|
|
684
|
+
}
|
|
685
|
+
if (config.write !== false || config.paths !== false) {
|
|
686
|
+
ctx.inject(['fs'], inner => {
|
|
687
|
+
if (config.write !== false) inner.effect(() => installWslWriteSupport(inner, inner.fs), 'dsh-ssh: WSL file publication')
|
|
688
|
+
if (config.paths !== false) inner.effect(() => installWslPathRepair(inner, inner.fs), 'dsh-ssh: WSL workspace path resolution')
|
|
689
|
+
})
|
|
690
|
+
}
|
|
691
|
+
}
|