dsh-wsl-workspace 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/src/index.ts ADDED
@@ -0,0 +1,410 @@
1
+ /**
2
+ * Host half of dsh-wsl-workspace. Three responsibilities:
3
+ *
4
+ * 1. Materialize a `wsl-<mode>` variant for every healthy roster preset
5
+ * under `<dshHome>/.agent-presets/` (the roster's auto-scanned user
6
+ * root), so the WSL execution world — `shell-wsl` + `fs-wsl` behind one
7
+ * entry-local realm, with `tool-bash`/`tool-fs` consumers — composes with
8
+ * ANY mode instead of being a mode itself; the legacy standalone `wsl`
9
+ * preset directory and stale variants are removed on boot. The preset
10
+ * rows name THIS package's built lib files by absolute path, which the
11
+ * preset mount resolves to `file:` URLs without relying on bare specifier
12
+ * resolution from the preset's home directory.
13
+ *
14
+ * 2. Serve the browser dialog's data route (`/wsl-workspace/api`):
15
+ * distribution discovery, one-level directory listing, path checks, and
16
+ * the per-workspace username store — all over the 9P UNC share.
17
+ * Loopback-only, matching the sensitivity of the privileged configuration
18
+ * surface.
19
+ *
20
+ * 3. Contribute the per-session `DSH_WSL_DISTRO` managed-env fact so the WSL
21
+ * shell executor can resolve a plain Linux `workdir` to the calling
22
+ * session's distribution.
23
+ * @module dsh-wsl-workspace
24
+ */
25
+
26
+ import { Context } from '@deepseek-ai/cordis'
27
+ import z from '@deepseek-ai/schemastery'
28
+ import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
29
+ import { fileURLToPath } from 'node:url'
30
+ import { dirname, join } from 'node:path'
31
+ import type { IncomingMessage, ServerResponse } from 'node:http'
32
+ import { homedir } from 'node:os'
33
+ import { joinUnc, normalizeLinuxPath, isAbsoluteLinuxPath, isValidWslUsername, parseWslUnc } from './shared/paths.ts'
34
+ import { canonicalWslUnc, getWorkspaceUsername, setWorkspaceUsername } from './shared/wsl-credentials.ts'
35
+ import { defaultDistro, listDistros } from './shared/wsl.ts'
36
+ import { isWslVariantId, transformPresetForWsl, variantIdFor } from './host/variants.ts'
37
+
38
+ /** The HTTP route this plugin serves (a relative, same-origin path). */
39
+ export const DEFAULT_ROUTE = '/wsl-workspace/api'
40
+
41
+ /** Plugin config. */
42
+ export interface Config {
43
+ /** The route under which the dialog data API is served. */
44
+ route?: string
45
+ }
46
+
47
+ /** The shape after schemastery applied the defaults. */
48
+ type ResolvedConfig = Required<Config>
49
+
50
+ /** The `webServer.register` route contract this plugin consumes. */
51
+ interface WebServerRoute {
52
+ kind: 'exact'
53
+ path: string
54
+ handler(req: IncomingMessage, res: ServerResponse): Promise<void>
55
+ }
56
+
57
+ interface WebServerService {
58
+ register(route: WebServerRoute): () => void
59
+ }
60
+
61
+ /** The `ctx.shellEnv` registry face this plugin consumes (optional service). */
62
+ interface ShellEnvService {
63
+ register(contributor: {
64
+ name: string
65
+ variables: Readonly<Record<string, { description: string }>>
66
+ resolve(execution: {
67
+ agent?: { session: { header: { cwd?: string } } }
68
+ }): Readonly<Partial<Record<string, string>>>
69
+ }): () => void
70
+ }
71
+
72
+ /** One directory entry the dialog lists. */
73
+ interface WslDirEntryWire {
74
+ name: string
75
+ kind: 'directory' | 'file' | 'other'
76
+ }
77
+
78
+ /** One directory level plus its breadcrumb ancestry. */
79
+ interface WslDirListingWire {
80
+ path: string
81
+ parent: string | null
82
+ entries: WslDirEntryWire[]
83
+ }
84
+
85
+ /** The wire envelope every method answers with. */
86
+ type Envelope<T> = { ok: true; value: T } | { ok: false; error: string }
87
+
88
+ const MAX_BODY_BYTES = 1024 * 1024
89
+
90
+ /** Valid WSL distribution names: one path-safe segment (no separators, no dot-dirs). */
91
+ const DISTRO_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/
92
+
93
+ /** The loopback hostnames the data route answers to (DNS-rebinding fence). */
94
+ const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1'])
95
+
96
+ /** True when a socket address is loopback (any IPv4/IPv6 spelling). */
97
+ function isLoopback(address: string | undefined): boolean {
98
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
99
+ }
100
+
101
+ /** The hostname part of a `Host` header value (port and IPv6 brackets stripped). */
102
+ function hostNameOf(host: string): string {
103
+ if (host.startsWith('[')) {
104
+ const end = host.indexOf(']')
105
+ return end >= 0 ? host.slice(1, end) : host
106
+ }
107
+ return host.split(':')[0] ?? ''
108
+ }
109
+
110
+ /** True when the request's `Host` header names a loopback host. */
111
+ function isLoopbackHost(host: string | undefined): boolean {
112
+ return host !== undefined && LOOPBACK_HOSTNAMES.has(hostNameOf(host).toLowerCase())
113
+ }
114
+
115
+ /**
116
+ * Validate a wire-supplied distribution name before it becomes a UNC segment:
117
+ * an attacker-controlled segment containing separators or `..` would escape
118
+ * the `\\wsl.localhost\` share structure into arbitrary UNC paths.
119
+ * @param value - the raw wire value.
120
+ * @returns the validated distro name.
121
+ */
122
+ function requireDistro(value: unknown): string {
123
+ if (typeof value !== 'string' || !DISTRO_PATTERN.test(value) || value === '.' || value === '..') {
124
+ throw new Error('distro must be a valid WSL distribution name')
125
+ }
126
+ return value
127
+ }
128
+
129
+ /** Human text for an unknown rejection. */
130
+ function messageOf(value: unknown): string {
131
+ return value instanceof Error ? value.message : String(value)
132
+ }
133
+
134
+ /** Write one JSON envelope. */
135
+ function json(res: ServerResponse, status: number, body: Envelope<unknown>): void {
136
+ res.writeHead(status, {
137
+ 'content-type': 'application/json; charset=utf-8',
138
+ 'cache-control': 'no-store',
139
+ 'x-content-type-options': 'nosniff',
140
+ })
141
+ res.end(JSON.stringify(body))
142
+ }
143
+
144
+ /** Collect and parse the request body, bounded. */
145
+ async function readBody(req: IncomingMessage): Promise<Record<string, unknown>> {
146
+ const chunks: Buffer[] = []
147
+ let size = 0
148
+ for await (const chunk of req) {
149
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
150
+ size += buffer.length
151
+ if (size > MAX_BODY_BYTES) throw new Error('request body is too large')
152
+ chunks.push(buffer)
153
+ }
154
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown
155
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
156
+ throw new Error('request body must be a JSON object')
157
+ }
158
+ return parsed as Record<string, unknown>
159
+ }
160
+
161
+ /** Normalize a Linux path for the wire (rejecting non-absolute input). */
162
+ function requireLinuxPath(value: unknown, label: string): string {
163
+ if (typeof value !== 'string' || !isAbsoluteLinuxPath(value)) {
164
+ throw new Error(`${label} must be an absolute Linux path`)
165
+ }
166
+ return normalizeLinuxPath(value)
167
+ }
168
+
169
+ /** Validate a wire-supplied workspace path and return its canonical UNC form. */
170
+ function requireWslUnc(value: unknown): string {
171
+ if (typeof value !== 'string') throw new Error('path must be a string')
172
+ const canonical = canonicalWslUnc(value)
173
+ if (canonical === null) throw new Error('path must be a WSL UNC workspace path')
174
+ return canonical
175
+ }
176
+
177
+ /** Resolve one directory listing over the 9P share. */
178
+ function listWslDir(distro: string, linuxPath: string): WslDirListingWire {
179
+ const unc = joinUnc(distro, linuxPath)
180
+ const dirents = readdirSync(unc, { withFileTypes: true })
181
+ const entries: WslDirEntryWire[] = dirents
182
+ .slice(0, 1000)
183
+ .map((dirent): WslDirEntryWire => {
184
+ const kind: WslDirEntryWire['kind'] = dirent.isDirectory()
185
+ ? 'directory'
186
+ : dirent.isFile() ? 'file' : 'other'
187
+ return { name: dirent.name, kind }
188
+ })
189
+ .sort((a, b) => {
190
+ if (a.kind === 'directory' && b.kind !== 'directory') return -1
191
+ if (a.kind !== 'directory' && b.kind === 'directory') return 1
192
+ return a.name.localeCompare(b.name)
193
+ })
194
+ const parent = linuxPath === '/' ? null : linuxPath.split('/').slice(0, -1).join('/') || '/'
195
+ return { path: linuxPath, parent, entries }
196
+ }
197
+
198
+ /** Route one method dispatch. */
199
+ async function dispatch(method: string, params: Record<string, unknown>): Promise<unknown> {
200
+ switch (method) {
201
+ case 'listDistros': {
202
+ const distros = await listDistros()
203
+ const fallback = await defaultDistro()
204
+ if (fallback !== undefined && distros.includes(fallback)) {
205
+ return [fallback, ...distros.filter(name => name !== fallback)]
206
+ }
207
+ return distros
208
+ }
209
+ case 'listDir': {
210
+ const distro = requireDistro(params.distro)
211
+ const path = requireLinuxPath(params.path, 'path')
212
+ return listWslDir(distro, path)
213
+ }
214
+ case 'check': {
215
+ const distro = requireDistro(params.distro)
216
+ const path = requireLinuxPath(params.path, 'path')
217
+ const unc = joinUnc(distro, path)
218
+ try {
219
+ const info = statSync(unc)
220
+ return { exists: true, isDirectory: info.isDirectory() }
221
+ } catch {
222
+ return { exists: false, isDirectory: false }
223
+ }
224
+ }
225
+ case 'setUser': {
226
+ const path = requireWslUnc(params.path)
227
+ const username = params.username
228
+ if (username === undefined || username === '') {
229
+ setWorkspaceUsername(path, undefined)
230
+ } else {
231
+ if (typeof username !== 'string' || !isValidWslUsername(username)) {
232
+ throw new Error('username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')
233
+ }
234
+ setWorkspaceUsername(path, username)
235
+ }
236
+ return null
237
+ }
238
+ default:
239
+ throw new Error(`unknown method "${method}"`)
240
+ }
241
+ }
242
+
243
+ /** The `ctx.agentPresets` roster face this plugin consumes (optional service). */
244
+ interface AgentPresetsService {
245
+ list(): Promise<{ id: string; broken?: string; path: string }[]>
246
+ read(id: string): Promise<string>
247
+ }
248
+
249
+ /**
250
+ * Materialize a `wsl-<mode>` variant for every healthy source preset, and
251
+ * remove this plugin's managed residue: stale variants whose source
252
+ * disappeared, plus the legacy standalone `wsl` preset directory (the
253
+ * execution world now composes with modes; a standalone WSL mode no longer
254
+ * exists). Managed files: rewritten on every boot.
255
+ * @param agentPresets - the roster service.
256
+ * @param dshHome - the harness home (user preset root parent).
257
+ * @param shellPath - absolute path of the plugin's built WSL shell provider.
258
+ * @param fsPath - absolute path of the plugin's built WSL fs provider.
259
+ */
260
+ async function materializeVariants(
261
+ agentPresets: AgentPresetsService,
262
+ dshHome: string,
263
+ shellPath: string,
264
+ fsPath: string,
265
+ ): Promise<void> {
266
+ const presets = await agentPresets.list()
267
+ const userRoot = join(dshHome, '.agent-presets')
268
+ const generated = new Set<string>()
269
+ for (const preset of presets) {
270
+ if (preset.broken !== undefined) continue
271
+ if (isWslVariantId(preset.id)) continue
272
+ const variantId = variantIdFor(preset.id)
273
+ const source = await agentPresets.read(preset.id)
274
+ const transformed = transformPresetForWsl(source, shellPath, fsPath)
275
+ const dir = join(userRoot, variantId)
276
+ mkdirSync(dir, { recursive: true })
277
+ writeFileSync(join(dir, 'agent.cordis.yml'), transformed, 'utf8')
278
+ let name = `WSL · ${preset.id}`
279
+ let orderLine = ''
280
+ try {
281
+ const meta = readFileSync(join(dirname(preset.path), 'preset.yml'), 'utf8')
282
+ const match = /^name:\s*(.+)$/m.exec(meta)
283
+ if (match?.[1] !== undefined && match[1].trim() !== '') name = `WSL · ${match[1].trim()}`
284
+ // Inherit the source's declared order so the WSL variants line up with
285
+ // the local modes in the roster (standard, PTC, minimal, cordis).
286
+ const orderMatch = /^order:\s*(\d+)\s*$/m.exec(meta)
287
+ if (orderMatch?.[1] !== undefined) orderLine = `order: ${orderMatch[1]}\n`
288
+ } catch {
289
+ // Absent or unreadable display metadata falls back to the id-based name.
290
+ }
291
+ writeFileSync(
292
+ join(dir, 'preset.yml'),
293
+ `name: ${name}\n`
294
+ + orderLine
295
+ + `description: ${preset.id} 模式叠加 WSL 执行世界:bash 与文件工具运行在 WSL 发行版内。\n`,
296
+ 'utf8',
297
+ )
298
+ generated.add(variantId)
299
+ }
300
+ for (const entry of readdirSync(userRoot, { withFileTypes: true })) {
301
+ if (!entry.isDirectory()) continue
302
+ if (entry.name === 'wsl') {
303
+ // The legacy standalone WSL mode: folded into the variants above.
304
+ rmSync(join(userRoot, entry.name), { recursive: true, force: true })
305
+ continue
306
+ }
307
+ if (!/^wsl-[a-z0-9-]+$/.test(entry.name)) continue
308
+ if (!generated.has(entry.name)) rmSync(join(userRoot, entry.name), { recursive: true, force: true })
309
+ }
310
+ }
311
+
312
+ /** Function-plugin plugin contract. */
313
+ export const name = 'dsh-wsl-workspace'
314
+
315
+ /** Required services. */
316
+ export const inject = ['webServer']
317
+
318
+ /** Validated plugin config (schemastery applied the defaults). */
319
+ export const Config: z<Config> = z.object({
320
+ route: z.string().default(DEFAULT_ROUTE),
321
+ })
322
+
323
+ /**
324
+ * Apply the host half: materialize the `wsl` preset plus a `wsl-<mode>`
325
+ * variant for every healthy roster preset, register the data route, and
326
+ * contribute the per-session `DSH_WSL_DISTRO` managed-env fact so the WSL
327
+ * shell executor can resolve a plain Linux `workdir` to the calling
328
+ * session's distribution.
329
+ * @param ctx - the host plugin context.
330
+ * @param config - the validated configuration.
331
+ */
332
+ export function apply(ctx: Context, config: Config): void {
333
+ const resolved = config as ResolvedConfig
334
+ const dshHome = process.env.DSH_HOME ?? join(homedir(), '.dsh')
335
+ const packageRoot = fileURLToPath(new URL('..', import.meta.url))
336
+ const shellPath = join(packageRoot, 'lib', 'shell.js').replace(/\\/g, '/')
337
+ const fsPath = join(packageRoot, 'lib', 'fs.js').replace(/\\/g, '/')
338
+
339
+ const agentPresets = ctx.get('agentPresets') as unknown as AgentPresetsService | undefined
340
+ if (agentPresets !== undefined) {
341
+ ctx.effect(() => {
342
+ void materializeVariants(agentPresets, dshHome, shellPath, fsPath).catch((error) => {
343
+ // Variant generation is best-effort over a live roster: a missing or
344
+ // unreadable source preset must not take the whole plugin down, but
345
+ // the failure is surfaced loudly rather than hidden.
346
+ console.error(`dsh-wsl-workspace: WSL preset-variant generation failed: ${messageOf(error)}`)
347
+ })
348
+ return () => {}
349
+ }, 'dsh-wsl-workspace: WSL preset variants')
350
+ }
351
+
352
+ const shellEnv = ctx.get('shellEnv') as unknown as ShellEnvService | undefined
353
+ if (shellEnv !== undefined) {
354
+ ctx.effect(() => shellEnv.register({
355
+ name: 'wsl-workspace-distro',
356
+ variables: {
357
+ DSH_WSL_DISTRO: {
358
+ description: 'The WSL distribution of the calling session workspace, when the session cwd is a WSL UNC path.',
359
+ },
360
+ DSH_WSL_USER: {
361
+ description: 'The Linux user of the calling session workspace, when the workspace has one configured.',
362
+ },
363
+ },
364
+ resolve(execution) {
365
+ const cwd = execution.agent?.session.header.cwd
366
+ const unc = cwd === undefined ? null : parseWslUnc(cwd)
367
+ if (unc === null) return {}
368
+ const username = getWorkspaceUsername(joinUnc(unc.distro, unc.linuxPath))
369
+ return username === undefined || username === ''
370
+ ? { DSH_WSL_DISTRO: unc.distro }
371
+ : { DSH_WSL_DISTRO: unc.distro, DSH_WSL_USER: username }
372
+ },
373
+ }), 'dsh-wsl-workspace: per-session distro env fact')
374
+ }
375
+
376
+ const webServer = ctx.get('webServer') as unknown as WebServerService
377
+ ctx.effect(() => webServer.register({
378
+ kind: 'exact',
379
+ path: resolved.route,
380
+ handler: async (req, res) => {
381
+ if (!isLoopback(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host)) {
382
+ json(res, 403, { ok: false, error: 'loopback-only' })
383
+ return
384
+ }
385
+ if (req.method !== 'POST') {
386
+ json(res, 405, { ok: false, error: 'method not allowed' })
387
+ return
388
+ }
389
+ let body: Record<string, unknown>
390
+ try {
391
+ body = await readBody(req)
392
+ } catch (error) {
393
+ json(res, 400, { ok: false, error: messageOf(error) })
394
+ return
395
+ }
396
+ const method = typeof body.method === 'string' ? body.method : ''
397
+ const params = body.params === undefined ? {} : body.params
398
+ if (params === null || typeof params !== 'object' || Array.isArray(params)) {
399
+ json(res, 400, { ok: false, error: 'params must be an object' })
400
+ return
401
+ }
402
+ try {
403
+ const value = await dispatch(method, params as Record<string, unknown>)
404
+ json(res, 200, { ok: true, value })
405
+ } catch (error) {
406
+ json(res, 200, { ok: false, error: messageOf(error) })
407
+ }
408
+ },
409
+ }), 'dsh-wsl-workspace: dialog data route')
410
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * WSL path helpers shared by the client and host halves. Pure and
3
+ * dependency-free so both planes can import them without a runtime edge.
4
+ */
5
+
6
+ /** WSL2 default loopback bridge host: `\\wsl.localhost\<distro>\...`. */
7
+ const WSL_LOCALHOST_HOST = 'wsl.localhost'
8
+ /** Legacy WSL interop host: `\\wsl$\<distro>\...`. */
9
+ const WSL_LEGACY_HOST = 'wsl$'
10
+
11
+ /** The two UNC hosts WSL exposes a distribution's filesystem under. */
12
+ const UNC_HOSTS = [WSL_LOCALHOST_HOST, WSL_LEGACY_HOST]
13
+
14
+ /** One WSL workspace coordinate parsed out of a UNC path. */
15
+ export interface WslUncTarget {
16
+ /** Distro name (e.g. `Ubuntu`) as `wsl -l -q` reports it. */
17
+ readonly distro: string
18
+ /** Normalized absolute Linux path (leading `/`; no trailing slash except root). */
19
+ readonly linuxPath: string
20
+ }
21
+
22
+ /**
23
+ * Parse a WSL UNC path into its distro and Linux path. Accepts the WSL2
24
+ * `\\wsl.localhost\<distro>\<linux>` form, the legacy `\\wsl$\<distro>\<linux>`
25
+ * interop form, and forward-slash spellings of either.
26
+ * @param raw - candidate absolute path.
27
+ * @returns the parsed target, or null when the path is not a WSL UNC.
28
+ */
29
+ export function parseWslUnc(raw: string): WslUncTarget | null {
30
+ const normalized = raw.replace(/\\/g, '/').replace(/\/\/+/g, '//')
31
+ if (!normalized.startsWith('//')) return null
32
+ const segments = normalized.slice(2).split('/')
33
+ const host = (segments[0] ?? '').toLowerCase()
34
+ if (!UNC_HOSTS.includes(host)) return null
35
+ const distro = segments[1] ?? ''
36
+ if (distro === '') return null
37
+ const rest = segments.slice(2).filter(segment => segment.length > 0)
38
+ return { distro, linuxPath: `/${rest.join('/')}` }
39
+ }
40
+
41
+ /**
42
+ * Whether a path resolves into a WSL distro through either UNC form.
43
+ * @param raw - candidate absolute path.
44
+ * @returns whether the path parses as a WSL UNC.
45
+ */
46
+ export function isWslUnc(raw: string): boolean {
47
+ return parseWslUnc(raw) !== null
48
+ }
49
+
50
+ /**
51
+ * Translate a WSL UNC path to the absolute Linux path a process inside the
52
+ * distribution can open. Throws on non-WSL input: callers rely on this
53
+ * conversion to hand paths to the Linux world, so a silent pass-through
54
+ * would hand a Windows path to bash.
55
+ * @param uncPath - a path {@link parseWslUnc} accepts.
56
+ * @returns the absolute Linux path.
57
+ */
58
+ export function uncToLinux(uncPath: string): string {
59
+ const parts = parseWslUnc(uncPath)
60
+ if (parts === null) {
61
+ throw new Error(`wsl-workspace: "${uncPath}" is not a WSL UNC path`)
62
+ }
63
+ return parts.linuxPath
64
+ }
65
+
66
+ /**
67
+ * Normalize a Linux absolute path for the Host: collapse repeated slashes and
68
+ * strip a trailing slash (root becomes `/`).
69
+ * @param path - absolute Linux path.
70
+ * @returns the normalized path.
71
+ */
72
+ export function normalizeLinuxPath(path: string): string {
73
+ const collapsed = path.replace(/\/+/g, '/')
74
+ return collapsed === '/' ? '/' : collapsed.replace(/\/$/, '')
75
+ }
76
+
77
+ /**
78
+ * Whether a path is an absolute, non-empty Linux path.
79
+ * @param path - candidate.
80
+ * @returns whether it starts with `/` and contains no NUL.
81
+ */
82
+ export function isAbsoluteLinuxPath(path: string): boolean {
83
+ return path.startsWith('/') && !path.includes('\0')
84
+ }
85
+
86
+ /**
87
+ * Join a distro and a Linux absolute path into the WSL2 UNC form used as the
88
+ * workspace identity (`\\wsl.localhost\<distro>\<linux>`, backslash segments).
89
+ * @param distro - distro name.
90
+ * @param linuxPath - absolute Linux path (leading `/`).
91
+ * @returns the UNC path.
92
+ */
93
+ export function joinUnc(distro: string, linuxPath: string): string {
94
+ if (!isAbsoluteLinuxPath(linuxPath)) {
95
+ throw new Error(`wsl-workspace: cannot map a non-absolute Linux path "${linuxPath}" to UNC`)
96
+ }
97
+ // Defense in depth: a distribution name with separators or dot-dirs would
98
+ // escape the `\\wsl.localhost\` share structure (the host route validates
99
+ // wire-supplied names too; every other caller passes through here).
100
+ if (distro === '' || distro === '.' || distro === '..' || /[\\/]/.test(distro)) {
101
+ throw new Error(`wsl-workspace: invalid distribution name "${distro}"`)
102
+ }
103
+ const normalized = linuxPath.replace(/\/+/g, '/').replace(/\/$/, '')
104
+ const withoutLeading = normalized.startsWith('/') ? normalized.slice(1) : normalized
105
+ const windowsSegments = withoutLeading.replace(/\//g, '\\')
106
+ const suffix = windowsSegments === '' ? '' : `\\${windowsSegments}`
107
+ return `\\\\wsl.localhost\\${distro}${suffix}`
108
+ }
109
+
110
+ /**
111
+ * Translate a Windows drive path to the drvfs mount path WSL distributions
112
+ * conventionally expose it at (`C:\foo` → `/mnt/c/foo`). Only single-letter
113
+ * drives under `/mnt` are mapped; custom mount points are out of scope.
114
+ * @param path - the candidate Windows path.
115
+ * @returns the `/mnt/<drive>/…` path, or `null` for non-drive paths.
116
+ */
117
+ export function windowsToMntPath(path: string): string | null {
118
+ const match = /^([A-Za-z]):[\\/](.*)$/.exec(path)
119
+ if (match === null) return null
120
+ const rest = (match[2] ?? '').replace(/\\/g, '/').replace(/\/+/g, '/').replace(/\/$/, '')
121
+ return `/mnt/${(match[1] ?? '').toLowerCase()}${rest === '' ? '' : `/${rest}`}`
122
+ }
123
+
124
+ /**
125
+ * Translate a `/mnt/<drive>/…` path back to its Windows drive path.
126
+ * @param linuxPath - the candidate Linux path.
127
+ * @returns the `X:\…` drive path, or `null` when the path is not a drvfs mount.
128
+ */
129
+ export function mntToWindowsPath(linuxPath: string): string | null {
130
+ const match = /^\/mnt\/([a-zA-Z])(?:\/(.*))?$/.exec(linuxPath)
131
+ if (match === null) return null
132
+ const rest = (match[2] ?? '').replace(/\//g, '\\')
133
+ return `${(match[1] ?? '').toUpperCase()}:\\${rest}`
134
+ }
135
+
136
+ /**
137
+ * True when a value is a Windows-shaped path (drive or UNC), which is how
138
+ * the shell executor decides the WSLENV `/p` translation flag: only Windows
139
+ * path values need translation when they cross into the Linux process.
140
+ * @param value - the environment value to classify.
141
+ * @returns whether the value looks like a Windows path.
142
+ */
143
+ export function isWindowsPathShaped(value: string): boolean {
144
+ return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith('\\\\')
145
+ }
146
+
147
+ /** Linux username shape for `wsl.exe -u`: starts with a letter or underscore, then letters/digits/`_`/`.`/`-` (max 64). */
148
+ const WSL_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/
149
+
150
+ /**
151
+ * Whether a value is a safe Linux username for `wsl.exe -u`. The check is
152
+ * strict on purpose: a value starting with `-` could be parsed as a wsl.exe
153
+ * option instead of a username.
154
+ * @param value - candidate username.
155
+ * @returns whether it matches the Linux username shape.
156
+ */
157
+ export function isValidWslUsername(value: string): boolean {
158
+ return WSL_USERNAME_PATTERN.test(value)
159
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Per-workspace WSL credentials (host side only). The dialog stores the
3
+ * optional Linux username of a WSL workspace under the harness home; the
4
+ * per-session env contributor and the WSL shell executor read it back so
5
+ * `wsl.exe -u <username>` can run commands as that user. Keys are canonical
6
+ * UNC workspace paths. This module touches node builtins, so the browser
7
+ * half never imports it.
8
+ * @module dsh-wsl-workspace/shared/wsl-credentials
9
+ */
10
+
11
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
12
+ import { homedir } from 'node:os'
13
+ import { dirname, join } from 'node:path'
14
+ import { isValidWslUsername, joinUnc, parseWslUnc } from './paths.ts'
15
+
16
+ /** One workspace's stored credentials. */
17
+ interface WorkspaceEntry {
18
+ /** The Linux user bash runs as inside the distribution (absent = distro default). */
19
+ username?: string
20
+ }
21
+
22
+ /** The stored form: canonical UNC workspace path → credentials. */
23
+ type WorkspaceStore = Record<string, WorkspaceEntry>
24
+
25
+ /** The store file lives under the harness home so both host halves share it. */
26
+ function storePath(): string {
27
+ const dshHome = process.env.DSH_HOME ?? join(homedir(), '.dsh')
28
+ return join(dshHome, 'wsl-workspaces.json')
29
+ }
30
+
31
+ /** Read the store; a missing or corrupt file reads as empty (never throws). */
32
+ function readStore(): WorkspaceStore {
33
+ try {
34
+ const parsed: unknown = JSON.parse(readFileSync(storePath(), 'utf8'))
35
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
36
+ return parsed as WorkspaceStore
37
+ } catch {
38
+ return {}
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Canonicalize any accepted WSL UNC spelling into the store's key form.
44
+ * @param path - candidate workspace path (either UNC host form).
45
+ * @returns the canonical UNC path, or null when the path is not a WSL UNC.
46
+ */
47
+ export function canonicalWslUnc(path: string): string | null {
48
+ const parsed = parseWslUnc(path)
49
+ return parsed === null ? null : joinUnc(parsed.distro, parsed.linuxPath)
50
+ }
51
+
52
+ /**
53
+ * Read the stored username for a WSL workspace.
54
+ * @param uncPath - the workspace path (any accepted WSL UNC spelling).
55
+ * @returns the username, or undefined when none is stored.
56
+ */
57
+ export function getWorkspaceUsername(uncPath: string): string | undefined {
58
+ const key = canonicalWslUnc(uncPath)
59
+ if (key === null) return undefined
60
+ const username = readStore()[key]?.username
61
+ return username === undefined || username === '' ? undefined : username
62
+ }
63
+
64
+ /**
65
+ * Store (or clear) the username of a WSL workspace.
66
+ * @param uncPath - the workspace path (any accepted WSL UNC spelling).
67
+ * @param username - the username; empty or undefined clears the stored value.
68
+ */
69
+ export function setWorkspaceUsername(uncPath: string, username: string | undefined): void {
70
+ const key = canonicalWslUnc(uncPath)
71
+ if (key === null) throw new Error('wsl-workspace: workspace path is not a WSL UNC path')
72
+ const store = readStore()
73
+ if (username === undefined || username.trim() === '') {
74
+ delete store[key]
75
+ } else {
76
+ const trimmed = username.trim()
77
+ if (!isValidWslUsername(trimmed)) {
78
+ throw new Error('wsl-workspace: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')
79
+ }
80
+ store[key] = { username: trimmed }
81
+ }
82
+ const path = storePath()
83
+ mkdirSync(dirname(path), { recursive: true })
84
+ writeFileSync(path, JSON.stringify(store, null, 2) + '\n', 'utf8')
85
+ }