@dreb/dashboard 2.66.1 → 2.66.2

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/README.md CHANGED
@@ -35,7 +35,9 @@ Open `http://127.0.0.1:5343`.
35
35
  project path, status chip, current activity, live subagents, task progress,
36
36
  ctx%, model, cost, last-assistant preview, and terminal provider-error reason). Below, past sessions grouped by project — three
37
37
  compact rows each with an "all N on disk" expander — with resume/delete.
38
- At <=700px, cards stack; long session names, status chips, project paths,
38
+ Sessions remain listed when their historical project path is missing; resume
39
+ then asks for an existing runtime directory and shows both paths without
40
+ changing the persisted session header. At <=700px, cards stack; long session names, status chips, project paths,
39
41
  activity/subagent text, and past-session labels wrap within cards or rows
40
42
  rather than spilling off-screen. `+ new session` anywhere.
41
43
  - **Session view** — full chat parity: markdown streaming transcript, tool
@@ -139,8 +141,9 @@ a separate fixed top-center stack; neither surface expires automatically.
139
141
  Creating a runtime from Fleet or Files leaves the current screen in place.
140
142
  Closing the runtime currently being viewed likewise keeps the main-session or
141
143
  subagent route and its rendered history as a read-only browser snapshot, with
142
- explicit **Resume session** and **Return to fleet** actions. Closing another
143
- runtime produces no redundant toast.
144
+ explicit **Resume session**, **Choose directory…**, and **Return to fleet**
145
+ actions. The directory chooser recovers a closed session if its captured runtime
146
+ path has since disappeared. Closing another runtime produces no redundant toast.
144
147
 
145
148
  ### Scoped models
146
149
 
@@ -213,9 +216,11 @@ runtime state, so they do not trigger child RPC calls or a disk inventory scan.
213
216
 
214
217
  Disk inventory is separate from live-runtime state. Before fleet, inventory, or
215
218
  resync serialization, the server projects each on-disk session to the declared
216
- browser DTO and bounds its first-message preview to 256 Unicode characters;
217
- internal parent paths and complete searchable transcript text never cross this
218
- boundary. The client narrowly refreshes inventory with `GET /api/sessions` after
219
+ browser DTO, reports whether its historical CWD resolves to a directory (plus
220
+ the canonical candidate when it does), and bounds its first-message preview to
221
+ 256 Unicode characters. Missing historical paths remain display metadata but are
222
+ not used as memory/project roots or recent runtime choices. Internal parent paths
223
+ and complete searchable transcript text never cross this boundary. The client narrowly refreshes inventory with `GET /api/sessions` after
219
224
  create, resume, stop, or delete, rather than reloading the whole fleet. While the
220
225
  Fleet screen or a session/subagent fleet sidebar is visible, it refreshes
221
226
  per-runtime stats on a shared 30-second cadence; the refresh is
package/dist/index.d.ts CHANGED
@@ -14,7 +14,7 @@ import { watch } from "node:fs";
14
14
  export { DashboardAuth, TailscaleStatusResolver, TailscaleWhoisResolver } from "./server/auth.js";
15
15
  export { DashboardImageService } from "./server/dashboard-images.js";
16
16
  export { EventHub } from "./server/event-hub.js";
17
- export { canonicalizePath, FileApi } from "./server/files.js";
17
+ export { canonicalizePath, FileApi, resolveExistingDirectory } from "./server/files.js";
18
18
  export { ImagePreviewWorker } from "./server/image-preview.js";
19
19
  export { FilePairingStorage, loadOrCreateDashboardSecret } from "./server/pairing-storage.js";
20
20
  export { RuntimePool, resolveDrebCliPath } from "./server/runtime-pool.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA;;;;;;;;;;GAUG;AAEH,OAAO,EAA4B,KAAK,EAAE,MAAM,SAAS,CAAC;AAa1D,OAAO,EAAE,aAAa,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAClG,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC9F,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAE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LAN mode):\n * default loopback bind (127.0.0.1), no auth, no Tailscale needed\n * --remote requires Tailscale; binds all interfaces but every request\n * passes identity allowlist + pairing code + device cookies\n *\n * Usage:\n * dreb-dashboard [--port 5343] [--remote --allow me@example.com [--allow ...]]\n */\n\nimport { existsSync, readFileSync, watch } from \"node:fs\";\nimport { createServer as createHttpServer, type Server as HttpServer } from \"node:http\";\nimport { createServer as createHttpsServer, type Server as HttpsServer } from \"node:https\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { DashboardAuth } from \"./server/auth.js\";\nimport { DashboardImageService } from \"./server/dashboard-images.js\";\nimport { ImagePreviewWorker } from \"./server/image-preview.js\";\nimport { FilePairingStorage, loadOrCreateDashboardSecret } from \"./server/pairing-storage.js\";\nimport { RuntimePool } from \"./server/runtime-pool.js\";\nimport { createDashboardServer } from \"./server/server.js\";\n\nexport { DashboardAuth, TailscaleStatusResolver, TailscaleWhoisResolver } from \"./server/auth.js\";\nexport { DashboardImageService } from \"./server/dashboard-images.js\";\nexport { EventHub } from \"./server/event-hub.js\";\nexport { canonicalizePath, FileApi } from \"./server/files.js\";\nexport { ImagePreviewWorker } from \"./server/image-preview.js\";\nexport { FilePairingStorage, loadOrCreateDashboardSecret } from \"./server/pairing-storage.js\";\nexport { RuntimePool, resolveDrebCliPath } from \"./server/runtime-pool.js\";\nexport { createDashboardServer, parseDeviceCookie } from \"./server/server.js\";\nexport type * from \"./shared/protocol.js\";\n\nconst DEFAULT_PORT = 5343;\n\ninterface CliArgs {\n\tport: number;\n\tremote: boolean;\n\tallow: string[];\n\thelp: boolean;\n\thttps: boolean;\n\tcert?: string;\n\tkey?: string;\n}\n\nexport function parseArgs(argv: string[]): CliArgs {\n\tconst args: CliArgs = { port: DEFAULT_PORT, remote: false, allow: [], help: false, https: false };\n\tfor (let i = 0; i < argv.length; i++) {\n\t\tconst arg = argv[i];\n\t\tif (arg === \"--port\") {\n\t\t\tconst value = argv[++i];\n\t\t\tconst port = Number.parseInt(value ?? \"\", 10);\n\t\t\tif (!Number.isInteger(port) || port < 1 || port > 65535) {\n\t\t\t\tthrow new Error(`Invalid --port value: ${value}`);\n\t\t\t}\n\t\t\targs.port = port;\n\t\t} else if (arg === \"--remote\") {\n\t\t\targs.remote = true;\n\t\t} else if (arg === \"--allow\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--allow requires an identity (Tailscale login name)\");\n\t\t\targs.allow.push(value);\n\t\t} else if (arg === \"--https\") {\n\t\t\targs.https = true;\n\t\t} else if (arg === \"--cert\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--cert requires a path to a PEM certificate file\");\n\t\t\targs.cert = value;\n\t\t} else if (arg === \"--key\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--key requires a path to a PEM private key file\");\n\t\t\targs.key = value;\n\t\t} else if (arg === \"--help\" || arg === \"-h\") {\n\t\t\targs.help = true;\n\t\t} else {\n\t\t\tthrow new Error(`Unknown argument: ${arg}`);\n\t\t}\n\t}\n\tif (args.remote && args.allow.length === 0) {\n\t\tthrow new Error(\"--remote requires at least one --allow <tailscale-login> (empty allowlist denies everyone)\");\n\t}\n\t// Native TLS. `https` is opt-in; it requires cert AND key (no silent\n\t// fallback to plain HTTP). The dashboard terminates TLS itself — no reverse\n\t// proxy, no auth-model change. `req.socket.remoteAddress` stays the real\n\t// tailnet IP, so identity resolution + allowlist + pairing keep working.\n\tif (args.https) {\n\t\tif (!args.cert) throw new Error(\"--https requires --cert <path>\");\n\t\tif (!args.key) throw new Error(\"--https requires --key <path>\");\n\t}\n\treturn args;\n}\n\n/**\n * Warning shown at startup when `--remote` binds the tailnet over plain HTTP\n * (no `--https`). Browsers treat plain HTTP over a non-loopback host as an\n * INSECURE context, so service workers and the Notification API are\n * unavailable — PWA install and mobile notifications (iOS exposes no\n * Notification API at all there) silently never work. Loopback (127.0.0.1) is\n * exempt (it counts as secure), so pure-local mode returns no warning.\n *\n * Returns the multi-line warning string, or `undefined` when TLS is enabled or\n * the server is loopback-only. Kept pure (no console) so it is unit-testable.\n */\nexport function insecureRemoteWarning(args: Pick<CliArgs, \"remote\" | \"https\">): string | undefined {\n\tif (!args.remote || args.https) return undefined;\n\treturn (\n\t\t\"⚠ warning: --remote without --https serves plain HTTP over the tailnet, which browsers treat as an\\n\" +\n\t\t\" INSECURE context — service workers, PWA install, and mobile notifications (especially iOS) will NOT work.\\n\" +\n\t\t\" Enable TLS for the tailnet hostname:\\n\" +\n\t\t\" tailscale cert <host>.<tailnet>.ts.net\\n\" +\n\t\t\" …then relaunch with --https --cert <host>.<tailnet>.ts.net.crt --key <host>.<tailnet>.ts.net.key\\n\" +\n\t\t\" and open the dashboard via https://<host>.<tailnet>.ts.net (the hostname, not the tailnet IP).\"\n\t);\n}\n\ntype ShutdownWatcher = Pick<ReturnType<typeof watch>, \"close\">;\n\ninterface ShutdownDeps {\n\tlog: (message: string) => void;\n\tclearReloadTimer: () => void;\n\twatchers: Iterable<ShutdownWatcher>;\n\tcloseServer: () => void;\n\tstopAll: () => Promise<unknown>;\n\texit: (code: number) => void;\n}\n\nexport function createShutdown(deps: ShutdownDeps): (message: string, exitCode: number) => void {\n\tlet shuttingDown = false;\n\treturn (message: string, exitCode: number) => {\n\t\tif (shuttingDown) return;\n\t\tshuttingDown = true;\n\t\tdeps.log(message);\n\t\tdeps.clearReloadTimer();\n\t\tfor (const watcher of deps.watchers) watcher.close();\n\t\tdeps.closeServer();\n\t\tvoid deps\n\t\t\t.stopAll()\n\t\t\t.catch((err) => {\n\t\t\t\tdeps.log(`shutdown teardown failed: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t})\n\t\t\t.finally(() => deps.exit(exitCode));\n\t};\n}\n\ntype TlsOptions = { cert: string; key: string };\ntype TlsWatchFilename = string | Buffer | null;\ntype TlsWatchListener = (event: string, filename: TlsWatchFilename) => void;\ntype TlsFileWatcher = ShutdownWatcher & {\n\ton(event: \"error\", listener: (err: unknown) => void): unknown;\n};\n\ninterface TlsReloaderDeps {\n\treadTlsOptions: () => TlsOptions;\n\tsetSecureContext: (options: TlsOptions) => void;\n\tlog: (message: string) => void;\n\twarn: (message: string) => void;\n}\n\nexport function createTlsReloader(deps: TlsReloaderDeps): () => void {\n\treturn () => {\n\t\ttry {\n\t\t\tdeps.setSecureContext(deps.readTlsOptions());\n\t\t\tdeps.log(\"tls certificate reloaded\");\n\t\t} catch (err) {\n\t\t\tdeps.warn(`tls reload failed (keeping old cert): ${err instanceof Error ? err.message : String(err)}`);\n\t\t}\n\t};\n}\n\nexport function shouldReloadForFile(filename: TlsWatchFilename, certBase: string, keyBase: string): boolean {\n\tif (filename == null) return true;\n\tif (typeof filename !== \"string\") return false;\n\treturn filename === certBase || filename === keyBase;\n}\n\ninterface TlsWatchDeps {\n\tcertPath: string;\n\tkeyPath: string;\n\twatchDirectory: (directory: string, listener: TlsWatchListener) => TlsFileWatcher;\n\treloadTls: () => void;\n\twarn: (message: string) => void;\n\tdebounceMs?: number;\n}\n\ninterface TlsWatchController {\n\twatchers: TlsFileWatcher[];\n\tclearReloadTimer: () => void;\n}\n\nexport function createTlsWatchers(deps: TlsWatchDeps): TlsWatchController {\n\tlet reloadTimer: ReturnType<typeof setTimeout> | undefined;\n\tconst watchers: TlsFileWatcher[] = [];\n\tconst debounceMs = deps.debounceMs ?? 500;\n\tconst certBase = basename(deps.certPath);\n\tconst keyBase = basename(deps.keyPath);\n\tconst clearReloadTimer = () => {\n\t\tif (!reloadTimer) return;\n\t\tclearTimeout(reloadTimer);\n\t\treloadTimer = undefined;\n\t};\n\tconst scheduleReload = () => {\n\t\tclearReloadTimer();\n\t\treloadTimer = setTimeout(deps.reloadTls, debounceMs);\n\t};\n\n\tfor (const dir of new Set([dirname(deps.certPath), dirname(deps.keyPath)])) {\n\t\ttry {\n\t\t\tconst watcher = deps.watchDirectory(dir, (_event, filename) => {\n\t\t\t\t// `fs.watch` directory events on macOS (FSEvents) frequently fire\n\t\t\t\t// with `filename === null`; fall through and reload anyway.\n\t\t\t\t// On Linux (inotify) the basename is carried reliably and filters\n\t\t\t\t// out unrelated files in the parent directory.\n\t\t\t\tif (!shouldReloadForFile(filename, certBase, keyBase)) return;\n\t\t\t\tscheduleReload();\n\t\t\t});\n\t\t\twatcher.on(\"error\", (err) => {\n\t\t\t\tdeps.warn(`tls cert watch error: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t});\n\t\t\twatchers.push(watcher);\n\t\t} catch (err) {\n\t\t\tdeps.warn(`tls cert watch setup failed for ${dir}: ${err instanceof Error ? err.message : String(err)}`);\n\t\t}\n\t}\n\n\treturn { watchers, clearReloadTimer };\n}\n\nconst HELP = `dreb-dashboard — dreb web dashboard server\n\nUsage: dreb-dashboard [options]\n\nOptions:\n --port <n> Port to listen on (default ${DEFAULT_PORT})\n --remote Enable remote mode (requires Tailscale). Without this\n flag the server binds 127.0.0.1 only — no LAN access.\n Plain HTTP over the tailnet is an INSECURE context: add\n --https (below) or mobile PWA install + notifications\n (especially iOS) will not work.\n --allow <identity> Tailscale login name allowed to pair (repeatable;\n required with --remote)\n --https Terminate TLS on the dashboard itself (native TLS). No\n reverse proxy, no auth-model change. Requires --cert\n and --key. Mainly for --remote (loopback is already a\n secure context): use 'tailscale cert' files for a\n tailnet hostname so mobile PWAs + notifications work.\n NOTE: with --https the server speaks TLS only, so the\n host's plain-http local tab (http://127.0.0.1) stops\n working — use the tailnet hostname (https://...) there.\n --cert <path> PEM certificate file (required with --https)\n --key <path> PEM private key file (required with --https)\n --help Show this help\n`;\n\nasync function main(): Promise<void> {\n\tlet args: CliArgs;\n\ttry {\n\t\targs = parseArgs(process.argv.slice(2));\n\t} catch (err) {\n\t\tconsole.error(`error: ${err instanceof Error ? err.message : String(err)}`);\n\t\tconsole.error(HELP);\n\t\tprocess.exit(1);\n\t}\n\tif (args.help) {\n\t\tconsole.log(HELP);\n\t\treturn;\n\t}\n\n\tconst agentDir = join(homedir(), \".dreb\", \"agent\");\n\tconst auth = new DashboardAuth({\n\t\tremoteEnabled: args.remote,\n\t\tallowedIdentities: args.allow,\n\t\tstorage: new FilePairingStorage(join(agentDir, \"dashboard-pairings.json\")),\n\t\tsecret: loadOrCreateDashboardSecret(join(agentDir, \"dashboard-auth-secret\")),\n\t\tlogger: (line) => console.warn(`[dashboard-auth] ${line}`),\n\t});\n\tconst pool = new RuntimePool();\n\tconst imageService = new DashboardImageService(new ImagePreviewWorker());\n\n\t// Static client assets live next to the compiled server (dist/static).\n\tconst staticDir = join(dirname(fileURLToPath(import.meta.url)), \"static\");\n\n\t// The server's own build version (dist/index.js → ../package.json) — surfaced\n\t// in the settings footer so a stale long-running service is spottable.\n\tlet serverVersion: string | undefined;\n\ttry {\n\t\tconst pkgPath = join(dirname(fileURLToPath(import.meta.url)), \"..\", \"package.json\");\n\t\tserverVersion = JSON.parse(readFileSync(pkgPath, \"utf8\")).version;\n\t} catch {\n\t\tserverVersion = undefined;\n\t}\n\n\t// Restart hook: exit non-zero so a supervisor (systemd Restart=on-failure,\n\t// etc.) respawns the process with the freshly-built dist. Assigned the http\n\t// server below via a mutable holder so the closure can close it first.\n\t// The TLS hot-reload debounce timer and directory watchers are lifted here\n\t// too, so restart and signal shutdown can release them (otherwise they leak\n\t// across restart/exit).\n\tlet httpServer: HttpServer | HttpsServer | undefined;\n\tlet clearTlsReloadTimer = () => {};\n\tlet closeDashboard = () => imageService.close();\n\tconst tlsWatchers: TlsFileWatcher[] = [];\n\tconst beginShutdown = createShutdown({\n\t\tlog: (message) => console.log(message),\n\t\tclearReloadTimer: () => clearTlsReloadTimer(),\n\t\twatchers: tlsWatchers,\n\t\tcloseServer: () => httpServer?.close(),\n\t\tstopAll: () => Promise.all([pool.stopAll(), closeDashboard()]),\n\t\texit: (code) => process.exit(code),\n\t});\n\tconst onRestart = () => beginShutdown(\"restart requested — exiting for supervisor to respawn\", 1);\n\n\tconst { SessionManager } = await import(\"@dreb/coding-agent\");\n\tconst app = createDashboardServer({\n\t\tauth,\n\t\tpool,\n\t\timageService,\n\t\tstaticDir: existsSync(staticDir) ? staticDir : undefined,\n\t\tserverVersion,\n\t\tonRestart,\n\t\tlistAllSessions: () => SessionManager.listAll(),\n\t\tdeleteSession: async (path: string) => {\n\t\t\tconst result = await SessionManager.deleteSession(path, {});\n\t\t\tif (!result.ok) throw new Error(result.error ?? \"Unknown deletion error\");\n\t\t\treturn { method: result.method };\n\t\t},\n\t});\n\tcloseDashboard = () => app.closeDashboard();\n\n\tconst host = args.remote ? \"0.0.0.0\" : \"127.0.0.1\";\n\tconst scheme = args.https ? \"https\" : \"http\";\n\n\t// Native TLS: the dashboard terminates TLS itself (no reverse proxy). The\n\t// auth model is unchanged — `req.socket.remoteAddress` is still the real\n\t// tailnet IP, so Tailscale identity resolution + allowlist + pairing keep\n\t// working. Local mode never sets --https (loopback is already a secure\n\t// context), but it's allowed if the operator wants it.\n\tlet server: HttpServer | HttpsServer;\n\tif (args.https && args.cert && args.key) {\n\t\tconst readTlsOptions = () => ({\n\t\t\tcert: readFileSync(args.cert!, \"utf-8\"),\n\t\t\tkey: readFileSync(args.key!, \"utf-8\"),\n\t\t});\n\t\tlet tlsOptions: TlsOptions;\n\t\ttry {\n\t\t\ttlsOptions = readTlsOptions();\n\t\t} catch (err) {\n\t\t\tconsole.error(`error: failed to read TLS cert/key: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tconst httpsServer = createHttpsServer(tlsOptions, app);\n\t\t// Hot-reload the cert on file change (zero-downtime renewal — e.g. a\n\t\t// systemd timer rewrites the `tailscale cert` files daily). New\n\t\t// connections pick up the new cert; existing ones finish on the old.\n\t\tconst reloadTls = createTlsReloader({\n\t\t\treadTlsOptions,\n\t\t\tsetSecureContext: (options) => httpsServer.setSecureContext(options),\n\t\t\tlog: (message) => console.log(message),\n\t\t\twarn: (message) => console.warn(message),\n\t\t});\n\t\t// Debounce: cert + key are often rewritten in quick succession. Watch\n\t\t// the PARENT DIRECTORY (not each file) and filter by filename: `fs.watch`\n\t\t// follows the inode, so an atomic renewal (write temp + rename(2))\n\t\t// replaces the inode and a file-level watcher goes silent on the new\n\t\t// file after the first reload. A directory watcher survives renames and\n\t\t// reports the changed basename via the `filename` callback argument.\n\t\tconst tlsWatchController = createTlsWatchers({\n\t\t\tcertPath: args.cert,\n\t\t\tkeyPath: args.key,\n\t\t\twatchDirectory: (dir, listener) => watch(dir, listener),\n\t\t\treloadTls,\n\t\t\twarn: (message) => console.warn(message),\n\t\t});\n\t\tclearTlsReloadTimer = tlsWatchController.clearReloadTimer;\n\t\ttlsWatchers.push(...tlsWatchController.watchers);\n\t\tserver = httpsServer;\n\t} else {\n\t\tserver = createHttpServer(app);\n\t}\n\tserver.listen(args.port, host, () => {\n\t\tconsole.log(\n\t\t\t`dreb dashboard listening on ${scheme}://${host === \"0.0.0.0\" ? \"<tailscale-ip>\" : host}:${args.port}`,\n\t\t);\n\t\tif (args.remote) {\n\t\t\tconsole.log(`remote mode: allowed identities = ${args.allow.join(\", \")}`);\n\t\t\tconst { code, expiresInMs } = auth.currentPairingCode();\n\t\t\tconsole.log(\n\t\t\t\t`pairing code: ${code} (rotates every 30s; current code rolls in ${Math.ceil(expiresInMs / 1000)}s)`,\n\t\t\t);\n\t\t\tconsole.log(\"new devices enter this code; see it live in dashboard Settings on the host machine\");\n\t\t} else {\n\t\t\tconsole.log(\"local mode: loopback only — use --remote for Tailscale access\");\n\t\t}\n\t\tif (args.https) {\n\t\t\tconsole.log(\"tls: native HTTPS enabled (cert + key hot-reload on file change)\");\n\t\t} else {\n\t\t\tconst insecureWarning = insecureRemoteWarning(args);\n\t\t\tif (insecureWarning) console.warn(insecureWarning);\n\t\t}\n\t});\n\thttpServer = server;\n\n\tconst shutdown = () => beginShutdown(\"shutting down…\", 0);\n\tprocess.on(\"SIGINT\", shutdown);\n\tprocess.on(\"SIGTERM\", shutdown);\n}\n\n// Only run when executed directly (not when imported for the library exports).\nconst entryPath = process.argv[1];\nif (entryPath && import.meta.url === new URL(`file://${entryPath}`).href) {\n\tmain().catch((err) => {\n\t\tconsole.error(`fatal: ${err instanceof Error ? err.message : String(err)}`);\n\t\tprocess.exit(1);\n\t});\n}\n"]}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA;;;;;;;;;;GAUG;AAEH,OAAO,EAA4B,KAAK,EAAE,MAAM,SAAS,CAAC;AAa1D,OAAO,EAAE,aAAa,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAClG,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AACxF,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC9F,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC9E,mBAAmB,sBAAsB,CAAC;AAI1C,UAAU,OAAO;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,OAAO,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CA6CjD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,IAAI,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O,EAAE,MAAM,KAAK,IAAI,CAAC;CAChC;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,eAAe,GAAG,MAAM,IAAI,CASnE;AAED,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAI1G;AAED,UAAU,YAAY;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,gBAAgB,KAAK,cAAc,CAAC;IAClF,SAAS,EAAE,MAAM,IAAI,CAAC;IACtB,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,UAAU,kBAAkB;IAC3B,QAAQ,EAAE,cAAc,EAAE,CAAC;IAC3B,gBAAgB,EAAE,MAAM,IAAI,CAAC;CAC7B;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,YAAY,GAAG,kBAAkB,CAoCxE","sourcesContent":["#!/usr/bin/env node\n/**\n * dreb-dashboard — launch the dreb web dashboard server.\n *\n * Modes (exactly two, no LAN mode):\n * default loopback bind (127.0.0.1), no auth, no Tailscale needed\n * --remote requires Tailscale; binds all interfaces but every request\n * passes identity allowlist + pairing code + device cookies\n *\n * Usage:\n * dreb-dashboard [--port 5343] [--remote --allow me@example.com [--allow ...]]\n */\n\nimport { existsSync, readFileSync, watch } from \"node:fs\";\nimport { createServer as createHttpServer, type Server as HttpServer } from \"node:http\";\nimport { createServer as createHttpsServer, type Server as HttpsServer } from \"node:https\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { DashboardAuth } from \"./server/auth.js\";\nimport { DashboardImageService } from \"./server/dashboard-images.js\";\nimport { ImagePreviewWorker } from \"./server/image-preview.js\";\nimport { FilePairingStorage, loadOrCreateDashboardSecret } from \"./server/pairing-storage.js\";\nimport { RuntimePool } from \"./server/runtime-pool.js\";\nimport { createDashboardServer } from \"./server/server.js\";\n\nexport { DashboardAuth, TailscaleStatusResolver, TailscaleWhoisResolver } from \"./server/auth.js\";\nexport { DashboardImageService } from \"./server/dashboard-images.js\";\nexport { EventHub } from \"./server/event-hub.js\";\nexport { canonicalizePath, FileApi, resolveExistingDirectory } from \"./server/files.js\";\nexport { ImagePreviewWorker } from \"./server/image-preview.js\";\nexport { FilePairingStorage, loadOrCreateDashboardSecret } from \"./server/pairing-storage.js\";\nexport { RuntimePool, resolveDrebCliPath } from \"./server/runtime-pool.js\";\nexport { createDashboardServer, parseDeviceCookie } from \"./server/server.js\";\nexport type * from \"./shared/protocol.js\";\n\nconst DEFAULT_PORT = 5343;\n\ninterface CliArgs {\n\tport: number;\n\tremote: boolean;\n\tallow: string[];\n\thelp: boolean;\n\thttps: boolean;\n\tcert?: string;\n\tkey?: string;\n}\n\nexport function parseArgs(argv: string[]): CliArgs {\n\tconst args: CliArgs = { port: DEFAULT_PORT, remote: false, allow: [], help: false, https: false };\n\tfor (let i = 0; i < argv.length; i++) {\n\t\tconst arg = argv[i];\n\t\tif (arg === \"--port\") {\n\t\t\tconst value = argv[++i];\n\t\t\tconst port = Number.parseInt(value ?? \"\", 10);\n\t\t\tif (!Number.isInteger(port) || port < 1 || port > 65535) {\n\t\t\t\tthrow new Error(`Invalid --port value: ${value}`);\n\t\t\t}\n\t\t\targs.port = port;\n\t\t} else if (arg === \"--remote\") {\n\t\t\targs.remote = true;\n\t\t} else if (arg === \"--allow\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--allow requires an identity (Tailscale login name)\");\n\t\t\targs.allow.push(value);\n\t\t} else if (arg === \"--https\") {\n\t\t\targs.https = true;\n\t\t} else if (arg === \"--cert\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--cert requires a path to a PEM certificate file\");\n\t\t\targs.cert = value;\n\t\t} else if (arg === \"--key\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--key requires a path to a PEM private key file\");\n\t\t\targs.key = value;\n\t\t} else if (arg === \"--help\" || arg === \"-h\") {\n\t\t\targs.help = true;\n\t\t} else {\n\t\t\tthrow new Error(`Unknown argument: ${arg}`);\n\t\t}\n\t}\n\tif (args.remote && args.allow.length === 0) {\n\t\tthrow new Error(\"--remote requires at least one --allow <tailscale-login> (empty allowlist denies everyone)\");\n\t}\n\t// Native TLS. `https` is opt-in; it requires cert AND key (no silent\n\t// fallback to plain HTTP). The dashboard terminates TLS itself — no reverse\n\t// proxy, no auth-model change. `req.socket.remoteAddress` stays the real\n\t// tailnet IP, so identity resolution + allowlist + pairing keep working.\n\tif (args.https) {\n\t\tif (!args.cert) throw new Error(\"--https requires --cert <path>\");\n\t\tif (!args.key) throw new Error(\"--https requires --key <path>\");\n\t}\n\treturn args;\n}\n\n/**\n * Warning shown at startup when `--remote` binds the tailnet over plain HTTP\n * (no `--https`). Browsers treat plain HTTP over a non-loopback host as an\n * INSECURE context, so service workers and the Notification API are\n * unavailable — PWA install and mobile notifications (iOS exposes no\n * Notification API at all there) silently never work. Loopback (127.0.0.1) is\n * exempt (it counts as secure), so pure-local mode returns no warning.\n *\n * Returns the multi-line warning string, or `undefined` when TLS is enabled or\n * the server is loopback-only. Kept pure (no console) so it is unit-testable.\n */\nexport function insecureRemoteWarning(args: Pick<CliArgs, \"remote\" | \"https\">): string | undefined {\n\tif (!args.remote || args.https) return undefined;\n\treturn (\n\t\t\"⚠ warning: --remote without --https serves plain HTTP over the tailnet, which browsers treat as an\\n\" +\n\t\t\" INSECURE context — service workers, PWA install, and mobile notifications (especially iOS) will NOT work.\\n\" +\n\t\t\" Enable TLS for the tailnet hostname:\\n\" +\n\t\t\" tailscale cert <host>.<tailnet>.ts.net\\n\" +\n\t\t\" …then relaunch with --https --cert <host>.<tailnet>.ts.net.crt --key <host>.<tailnet>.ts.net.key\\n\" +\n\t\t\" and open the dashboard via https://<host>.<tailnet>.ts.net (the hostname, not the tailnet IP).\"\n\t);\n}\n\ntype ShutdownWatcher = Pick<ReturnType<typeof watch>, \"close\">;\n\ninterface ShutdownDeps {\n\tlog: (message: string) => void;\n\tclearReloadTimer: () => void;\n\twatchers: Iterable<ShutdownWatcher>;\n\tcloseServer: () => void;\n\tstopAll: () => Promise<unknown>;\n\texit: (code: number) => void;\n}\n\nexport function createShutdown(deps: ShutdownDeps): (message: string, exitCode: number) => void {\n\tlet shuttingDown = false;\n\treturn (message: string, exitCode: number) => {\n\t\tif (shuttingDown) return;\n\t\tshuttingDown = true;\n\t\tdeps.log(message);\n\t\tdeps.clearReloadTimer();\n\t\tfor (const watcher of deps.watchers) watcher.close();\n\t\tdeps.closeServer();\n\t\tvoid deps\n\t\t\t.stopAll()\n\t\t\t.catch((err) => {\n\t\t\t\tdeps.log(`shutdown teardown failed: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t})\n\t\t\t.finally(() => deps.exit(exitCode));\n\t};\n}\n\ntype TlsOptions = { cert: string; key: string };\ntype TlsWatchFilename = string | Buffer | null;\ntype TlsWatchListener = (event: string, filename: TlsWatchFilename) => void;\ntype TlsFileWatcher = ShutdownWatcher & {\n\ton(event: \"error\", listener: (err: unknown) => void): unknown;\n};\n\ninterface TlsReloaderDeps {\n\treadTlsOptions: () => TlsOptions;\n\tsetSecureContext: (options: TlsOptions) => void;\n\tlog: (message: string) => void;\n\twarn: (message: string) => void;\n}\n\nexport function createTlsReloader(deps: TlsReloaderDeps): () => void {\n\treturn () => {\n\t\ttry {\n\t\t\tdeps.setSecureContext(deps.readTlsOptions());\n\t\t\tdeps.log(\"tls certificate reloaded\");\n\t\t} catch (err) {\n\t\t\tdeps.warn(`tls reload failed (keeping old cert): ${err instanceof Error ? err.message : String(err)}`);\n\t\t}\n\t};\n}\n\nexport function shouldReloadForFile(filename: TlsWatchFilename, certBase: string, keyBase: string): boolean {\n\tif (filename == null) return true;\n\tif (typeof filename !== \"string\") return false;\n\treturn filename === certBase || filename === keyBase;\n}\n\ninterface TlsWatchDeps {\n\tcertPath: string;\n\tkeyPath: string;\n\twatchDirectory: (directory: string, listener: TlsWatchListener) => TlsFileWatcher;\n\treloadTls: () => void;\n\twarn: (message: string) => void;\n\tdebounceMs?: number;\n}\n\ninterface TlsWatchController {\n\twatchers: TlsFileWatcher[];\n\tclearReloadTimer: () => void;\n}\n\nexport function createTlsWatchers(deps: TlsWatchDeps): TlsWatchController {\n\tlet reloadTimer: ReturnType<typeof setTimeout> | undefined;\n\tconst watchers: TlsFileWatcher[] = [];\n\tconst debounceMs = deps.debounceMs ?? 500;\n\tconst certBase = basename(deps.certPath);\n\tconst keyBase = basename(deps.keyPath);\n\tconst clearReloadTimer = () => {\n\t\tif (!reloadTimer) return;\n\t\tclearTimeout(reloadTimer);\n\t\treloadTimer = undefined;\n\t};\n\tconst scheduleReload = () => {\n\t\tclearReloadTimer();\n\t\treloadTimer = setTimeout(deps.reloadTls, debounceMs);\n\t};\n\n\tfor (const dir of new Set([dirname(deps.certPath), dirname(deps.keyPath)])) {\n\t\ttry {\n\t\t\tconst watcher = deps.watchDirectory(dir, (_event, filename) => {\n\t\t\t\t// `fs.watch` directory events on macOS (FSEvents) frequently fire\n\t\t\t\t// with `filename === null`; fall through and reload anyway.\n\t\t\t\t// On Linux (inotify) the basename is carried reliably and filters\n\t\t\t\t// out unrelated files in the parent directory.\n\t\t\t\tif (!shouldReloadForFile(filename, certBase, keyBase)) return;\n\t\t\t\tscheduleReload();\n\t\t\t});\n\t\t\twatcher.on(\"error\", (err) => {\n\t\t\t\tdeps.warn(`tls cert watch error: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t});\n\t\t\twatchers.push(watcher);\n\t\t} catch (err) {\n\t\t\tdeps.warn(`tls cert watch setup failed for ${dir}: ${err instanceof Error ? err.message : String(err)}`);\n\t\t}\n\t}\n\n\treturn { watchers, clearReloadTimer };\n}\n\nconst HELP = `dreb-dashboard — dreb web dashboard server\n\nUsage: dreb-dashboard [options]\n\nOptions:\n --port <n> Port to listen on (default ${DEFAULT_PORT})\n --remote Enable remote mode (requires Tailscale). Without this\n flag the server binds 127.0.0.1 only — no LAN access.\n Plain HTTP over the tailnet is an INSECURE context: add\n --https (below) or mobile PWA install + notifications\n (especially iOS) will not work.\n --allow <identity> Tailscale login name allowed to pair (repeatable;\n required with --remote)\n --https Terminate TLS on the dashboard itself (native TLS). No\n reverse proxy, no auth-model change. Requires --cert\n and --key. Mainly for --remote (loopback is already a\n secure context): use 'tailscale cert' files for a\n tailnet hostname so mobile PWAs + notifications work.\n NOTE: with --https the server speaks TLS only, so the\n host's plain-http local tab (http://127.0.0.1) stops\n working — use the tailnet hostname (https://...) there.\n --cert <path> PEM certificate file (required with --https)\n --key <path> PEM private key file (required with --https)\n --help Show this help\n`;\n\nasync function main(): Promise<void> {\n\tlet args: CliArgs;\n\ttry {\n\t\targs = parseArgs(process.argv.slice(2));\n\t} catch (err) {\n\t\tconsole.error(`error: ${err instanceof Error ? err.message : String(err)}`);\n\t\tconsole.error(HELP);\n\t\tprocess.exit(1);\n\t}\n\tif (args.help) {\n\t\tconsole.log(HELP);\n\t\treturn;\n\t}\n\n\tconst agentDir = join(homedir(), \".dreb\", \"agent\");\n\tconst auth = new DashboardAuth({\n\t\tremoteEnabled: args.remote,\n\t\tallowedIdentities: args.allow,\n\t\tstorage: new FilePairingStorage(join(agentDir, \"dashboard-pairings.json\")),\n\t\tsecret: loadOrCreateDashboardSecret(join(agentDir, \"dashboard-auth-secret\")),\n\t\tlogger: (line) => console.warn(`[dashboard-auth] ${line}`),\n\t});\n\tconst pool = new RuntimePool();\n\tconst imageService = new DashboardImageService(new ImagePreviewWorker());\n\n\t// Static client assets live next to the compiled server (dist/static).\n\tconst staticDir = join(dirname(fileURLToPath(import.meta.url)), \"static\");\n\n\t// The server's own build version (dist/index.js → ../package.json) — surfaced\n\t// in the settings footer so a stale long-running service is spottable.\n\tlet serverVersion: string | undefined;\n\ttry {\n\t\tconst pkgPath = join(dirname(fileURLToPath(import.meta.url)), \"..\", \"package.json\");\n\t\tserverVersion = JSON.parse(readFileSync(pkgPath, \"utf8\")).version;\n\t} catch {\n\t\tserverVersion = undefined;\n\t}\n\n\t// Restart hook: exit non-zero so a supervisor (systemd Restart=on-failure,\n\t// etc.) respawns the process with the freshly-built dist. Assigned the http\n\t// server below via a mutable holder so the closure can close it first.\n\t// The TLS hot-reload debounce timer and directory watchers are lifted here\n\t// too, so restart and signal shutdown can release them (otherwise they leak\n\t// across restart/exit).\n\tlet httpServer: HttpServer | HttpsServer | undefined;\n\tlet clearTlsReloadTimer = () => {};\n\tlet closeDashboard = () => imageService.close();\n\tconst tlsWatchers: TlsFileWatcher[] = [];\n\tconst beginShutdown = createShutdown({\n\t\tlog: (message) => console.log(message),\n\t\tclearReloadTimer: () => clearTlsReloadTimer(),\n\t\twatchers: tlsWatchers,\n\t\tcloseServer: () => httpServer?.close(),\n\t\tstopAll: () => Promise.all([pool.stopAll(), closeDashboard()]),\n\t\texit: (code) => process.exit(code),\n\t});\n\tconst onRestart = () => beginShutdown(\"restart requested — exiting for supervisor to respawn\", 1);\n\n\tconst { SessionManager } = await import(\"@dreb/coding-agent\");\n\tconst app = createDashboardServer({\n\t\tauth,\n\t\tpool,\n\t\timageService,\n\t\tstaticDir: existsSync(staticDir) ? staticDir : undefined,\n\t\tserverVersion,\n\t\tonRestart,\n\t\tlistAllSessions: () => SessionManager.listAll(),\n\t\tdeleteSession: async (path: string) => {\n\t\t\tconst result = await SessionManager.deleteSession(path, {});\n\t\t\tif (!result.ok) throw new Error(result.error ?? \"Unknown deletion error\");\n\t\t\treturn { method: result.method };\n\t\t},\n\t});\n\tcloseDashboard = () => app.closeDashboard();\n\n\tconst host = args.remote ? \"0.0.0.0\" : \"127.0.0.1\";\n\tconst scheme = args.https ? \"https\" : \"http\";\n\n\t// Native TLS: the dashboard terminates TLS itself (no reverse proxy). The\n\t// auth model is unchanged — `req.socket.remoteAddress` is still the real\n\t// tailnet IP, so Tailscale identity resolution + allowlist + pairing keep\n\t// working. Local mode never sets --https (loopback is already a secure\n\t// context), but it's allowed if the operator wants it.\n\tlet server: HttpServer | HttpsServer;\n\tif (args.https && args.cert && args.key) {\n\t\tconst readTlsOptions = () => ({\n\t\t\tcert: readFileSync(args.cert!, \"utf-8\"),\n\t\t\tkey: readFileSync(args.key!, \"utf-8\"),\n\t\t});\n\t\tlet tlsOptions: TlsOptions;\n\t\ttry {\n\t\t\ttlsOptions = readTlsOptions();\n\t\t} catch (err) {\n\t\t\tconsole.error(`error: failed to read TLS cert/key: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tconst httpsServer = createHttpsServer(tlsOptions, app);\n\t\t// Hot-reload the cert on file change (zero-downtime renewal — e.g. a\n\t\t// systemd timer rewrites the `tailscale cert` files daily). New\n\t\t// connections pick up the new cert; existing ones finish on the old.\n\t\tconst reloadTls = createTlsReloader({\n\t\t\treadTlsOptions,\n\t\t\tsetSecureContext: (options) => httpsServer.setSecureContext(options),\n\t\t\tlog: (message) => console.log(message),\n\t\t\twarn: (message) => console.warn(message),\n\t\t});\n\t\t// Debounce: cert + key are often rewritten in quick succession. Watch\n\t\t// the PARENT DIRECTORY (not each file) and filter by filename: `fs.watch`\n\t\t// follows the inode, so an atomic renewal (write temp + rename(2))\n\t\t// replaces the inode and a file-level watcher goes silent on the new\n\t\t// file after the first reload. A directory watcher survives renames and\n\t\t// reports the changed basename via the `filename` callback argument.\n\t\tconst tlsWatchController = createTlsWatchers({\n\t\t\tcertPath: args.cert,\n\t\t\tkeyPath: args.key,\n\t\t\twatchDirectory: (dir, listener) => watch(dir, listener),\n\t\t\treloadTls,\n\t\t\twarn: (message) => console.warn(message),\n\t\t});\n\t\tclearTlsReloadTimer = tlsWatchController.clearReloadTimer;\n\t\ttlsWatchers.push(...tlsWatchController.watchers);\n\t\tserver = httpsServer;\n\t} else {\n\t\tserver = createHttpServer(app);\n\t}\n\tserver.listen(args.port, host, () => {\n\t\tconsole.log(\n\t\t\t`dreb dashboard listening on ${scheme}://${host === \"0.0.0.0\" ? \"<tailscale-ip>\" : host}:${args.port}`,\n\t\t);\n\t\tif (args.remote) {\n\t\t\tconsole.log(`remote mode: allowed identities = ${args.allow.join(\", \")}`);\n\t\t\tconst { code, expiresInMs } = auth.currentPairingCode();\n\t\t\tconsole.log(\n\t\t\t\t`pairing code: ${code} (rotates every 30s; current code rolls in ${Math.ceil(expiresInMs / 1000)}s)`,\n\t\t\t);\n\t\t\tconsole.log(\"new devices enter this code; see it live in dashboard Settings on the host machine\");\n\t\t} else {\n\t\t\tconsole.log(\"local mode: loopback only — use --remote for Tailscale access\");\n\t\t}\n\t\tif (args.https) {\n\t\t\tconsole.log(\"tls: native HTTPS enabled (cert + key hot-reload on file change)\");\n\t\t} else {\n\t\t\tconst insecureWarning = insecureRemoteWarning(args);\n\t\t\tif (insecureWarning) console.warn(insecureWarning);\n\t\t}\n\t});\n\thttpServer = server;\n\n\tconst shutdown = () => beginShutdown(\"shutting down…\", 0);\n\tprocess.on(\"SIGINT\", shutdown);\n\tprocess.on(\"SIGTERM\", shutdown);\n}\n\n// Only run when executed directly (not when imported for the library exports).\nconst entryPath = process.argv[1];\nif (entryPath && import.meta.url === new URL(`file://${entryPath}`).href) {\n\tmain().catch((err) => {\n\t\tconsole.error(`fatal: ${err instanceof Error ? err.message : String(err)}`);\n\t\tprocess.exit(1);\n\t});\n}\n"]}
package/dist/index.js CHANGED
@@ -25,7 +25,7 @@ import { createDashboardServer } from "./server/server.js";
25
25
  export { DashboardAuth, TailscaleStatusResolver, TailscaleWhoisResolver } from "./server/auth.js";
26
26
  export { DashboardImageService } from "./server/dashboard-images.js";
27
27
  export { EventHub } from "./server/event-hub.js";
28
- export { canonicalizePath, FileApi } from "./server/files.js";
28
+ export { canonicalizePath, FileApi, resolveExistingDirectory } from "./server/files.js";
29
29
  export { ImagePreviewWorker } from "./server/image-preview.js";
30
30
  export { FilePairingStorage, loadOrCreateDashboardSecret } from "./server/pairing-storage.js";
31
31
  export { RuntimePool, resolveDrebCliPath } from "./server/runtime-pool.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EAAE,YAAY,IAAI,gBAAgB,EAA6B,MAAM,WAAW,CAAC;AACxF,OAAO,EAAE,YAAY,IAAI,iBAAiB,EAA8B,MAAM,YAAY,CAAC;AAC3F,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC9F,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,OAAO,EAAE,aAAa,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAClG,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE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AAC,CAAC;QACjF,CAAC;aAAM,CAAC;YACP,MAAM,eAAe,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;YACpD,IAAI,eAAe;gBAAE,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;QACpD,CAAC;IAAA,CACD,CAAC,CAAC;IACH,UAAU,GAAG,MAAM,CAAC;IAEpB,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,aAAa,CAAC,kBAAgB,EAAE,CAAC,CAAC,CAAC;IAC1D,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC/B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AAAA,CAChC;AAED,+EAA+E;AAC/E,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClC,IAAI,SAAS,IAAI,OAAO,IAAI,CAAC,GAAG,KAAK,IAAI,GAAG,CAAC,UAAU,SAAS,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAC1E,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;QACrB,OAAO,CAAC,KAAK,CAAC,UAAU,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAC5E,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAAA,CAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * dreb-dashboard — launch the dreb web dashboard server.\n *\n * Modes (exactly two, no LAN mode):\n * default loopback bind (127.0.0.1), no auth, no Tailscale needed\n * --remote requires Tailscale; binds all interfaces but every request\n * passes identity allowlist + pairing code + device cookies\n *\n * Usage:\n * dreb-dashboard [--port 5343] [--remote --allow me@example.com [--allow ...]]\n */\n\nimport { existsSync, readFileSync, watch } from \"node:fs\";\nimport { createServer as createHttpServer, type Server as HttpServer } from \"node:http\";\nimport { createServer as createHttpsServer, type Server as HttpsServer } from \"node:https\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { DashboardAuth } from \"./server/auth.js\";\nimport { DashboardImageService } from \"./server/dashboard-images.js\";\nimport { ImagePreviewWorker } from \"./server/image-preview.js\";\nimport { FilePairingStorage, loadOrCreateDashboardSecret } from \"./server/pairing-storage.js\";\nimport { RuntimePool } from \"./server/runtime-pool.js\";\nimport { createDashboardServer } from \"./server/server.js\";\n\nexport { DashboardAuth, TailscaleStatusResolver, TailscaleWhoisResolver } from \"./server/auth.js\";\nexport { DashboardImageService } from \"./server/dashboard-images.js\";\nexport { EventHub } from \"./server/event-hub.js\";\nexport { canonicalizePath, FileApi } from \"./server/files.js\";\nexport { ImagePreviewWorker } from \"./server/image-preview.js\";\nexport { FilePairingStorage, loadOrCreateDashboardSecret } from \"./server/pairing-storage.js\";\nexport { RuntimePool, resolveDrebCliPath } from \"./server/runtime-pool.js\";\nexport { createDashboardServer, parseDeviceCookie } from \"./server/server.js\";\nexport type * from \"./shared/protocol.js\";\n\nconst DEFAULT_PORT = 5343;\n\ninterface CliArgs {\n\tport: number;\n\tremote: boolean;\n\tallow: string[];\n\thelp: boolean;\n\thttps: boolean;\n\tcert?: string;\n\tkey?: string;\n}\n\nexport function parseArgs(argv: string[]): CliArgs {\n\tconst args: CliArgs = { port: DEFAULT_PORT, remote: false, allow: [], help: false, https: false };\n\tfor (let i = 0; i < argv.length; i++) {\n\t\tconst arg = argv[i];\n\t\tif (arg === \"--port\") {\n\t\t\tconst value = argv[++i];\n\t\t\tconst port = Number.parseInt(value ?? \"\", 10);\n\t\t\tif (!Number.isInteger(port) || port < 1 || port > 65535) {\n\t\t\t\tthrow new Error(`Invalid --port value: ${value}`);\n\t\t\t}\n\t\t\targs.port = port;\n\t\t} else if (arg === \"--remote\") {\n\t\t\targs.remote = true;\n\t\t} else if (arg === \"--allow\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--allow requires an identity (Tailscale login name)\");\n\t\t\targs.allow.push(value);\n\t\t} else if (arg === \"--https\") {\n\t\t\targs.https = true;\n\t\t} else if (arg === \"--cert\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--cert requires a path to a PEM certificate file\");\n\t\t\targs.cert = value;\n\t\t} else if (arg === \"--key\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--key requires a path to a PEM private key file\");\n\t\t\targs.key = value;\n\t\t} else if (arg === \"--help\" || arg === \"-h\") {\n\t\t\targs.help = true;\n\t\t} else {\n\t\t\tthrow new Error(`Unknown argument: ${arg}`);\n\t\t}\n\t}\n\tif (args.remote && args.allow.length === 0) {\n\t\tthrow new Error(\"--remote requires at least one --allow <tailscale-login> (empty allowlist denies everyone)\");\n\t}\n\t// Native TLS. `https` is opt-in; it requires cert AND key (no silent\n\t// fallback to plain HTTP). The dashboard terminates TLS itself — no reverse\n\t// proxy, no auth-model change. `req.socket.remoteAddress` stays the real\n\t// tailnet IP, so identity resolution + allowlist + pairing keep working.\n\tif (args.https) {\n\t\tif (!args.cert) throw new Error(\"--https requires --cert <path>\");\n\t\tif (!args.key) throw new Error(\"--https requires --key <path>\");\n\t}\n\treturn args;\n}\n\n/**\n * Warning shown at startup when `--remote` binds the tailnet over plain HTTP\n * (no `--https`). Browsers treat plain HTTP over a non-loopback host as an\n * INSECURE context, so service workers and the Notification API are\n * unavailable — PWA install and mobile notifications (iOS exposes no\n * Notification API at all there) silently never work. Loopback (127.0.0.1) is\n * exempt (it counts as secure), so pure-local mode returns no warning.\n *\n * Returns the multi-line warning string, or `undefined` when TLS is enabled or\n * the server is loopback-only. Kept pure (no console) so it is unit-testable.\n */\nexport function insecureRemoteWarning(args: Pick<CliArgs, \"remote\" | \"https\">): string | undefined {\n\tif (!args.remote || args.https) return undefined;\n\treturn (\n\t\t\"⚠ warning: --remote without --https serves plain HTTP over the tailnet, which browsers treat as an\\n\" +\n\t\t\" INSECURE context — service workers, PWA install, and mobile notifications (especially iOS) will NOT work.\\n\" +\n\t\t\" Enable TLS for the tailnet hostname:\\n\" +\n\t\t\" tailscale cert <host>.<tailnet>.ts.net\\n\" +\n\t\t\" …then relaunch with --https --cert <host>.<tailnet>.ts.net.crt --key <host>.<tailnet>.ts.net.key\\n\" +\n\t\t\" and open the dashboard via https://<host>.<tailnet>.ts.net (the hostname, not the tailnet IP).\"\n\t);\n}\n\ntype ShutdownWatcher = Pick<ReturnType<typeof watch>, \"close\">;\n\ninterface ShutdownDeps {\n\tlog: (message: string) => void;\n\tclearReloadTimer: () => void;\n\twatchers: Iterable<ShutdownWatcher>;\n\tcloseServer: () => void;\n\tstopAll: () => Promise<unknown>;\n\texit: (code: number) => void;\n}\n\nexport function createShutdown(deps: ShutdownDeps): (message: string, exitCode: number) => void {\n\tlet shuttingDown = false;\n\treturn (message: string, exitCode: number) => {\n\t\tif (shuttingDown) return;\n\t\tshuttingDown = true;\n\t\tdeps.log(message);\n\t\tdeps.clearReloadTimer();\n\t\tfor (const watcher of deps.watchers) watcher.close();\n\t\tdeps.closeServer();\n\t\tvoid deps\n\t\t\t.stopAll()\n\t\t\t.catch((err) => {\n\t\t\t\tdeps.log(`shutdown teardown failed: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t})\n\t\t\t.finally(() => deps.exit(exitCode));\n\t};\n}\n\ntype TlsOptions = { cert: string; key: string };\ntype TlsWatchFilename = string | Buffer | null;\ntype TlsWatchListener = (event: string, filename: TlsWatchFilename) => void;\ntype TlsFileWatcher = ShutdownWatcher & {\n\ton(event: \"error\", listener: (err: unknown) => void): unknown;\n};\n\ninterface TlsReloaderDeps {\n\treadTlsOptions: () => TlsOptions;\n\tsetSecureContext: (options: TlsOptions) => void;\n\tlog: (message: string) => void;\n\twarn: (message: string) => void;\n}\n\nexport function createTlsReloader(deps: TlsReloaderDeps): () => void {\n\treturn () => {\n\t\ttry {\n\t\t\tdeps.setSecureContext(deps.readTlsOptions());\n\t\t\tdeps.log(\"tls certificate reloaded\");\n\t\t} catch (err) {\n\t\t\tdeps.warn(`tls reload failed (keeping old cert): ${err instanceof Error ? err.message : String(err)}`);\n\t\t}\n\t};\n}\n\nexport function shouldReloadForFile(filename: TlsWatchFilename, certBase: string, keyBase: string): boolean {\n\tif (filename == null) return true;\n\tif (typeof filename !== \"string\") return false;\n\treturn filename === certBase || filename === keyBase;\n}\n\ninterface TlsWatchDeps {\n\tcertPath: string;\n\tkeyPath: string;\n\twatchDirectory: (directory: string, listener: TlsWatchListener) => TlsFileWatcher;\n\treloadTls: () => void;\n\twarn: (message: string) => void;\n\tdebounceMs?: number;\n}\n\ninterface TlsWatchController {\n\twatchers: TlsFileWatcher[];\n\tclearReloadTimer: () => void;\n}\n\nexport function createTlsWatchers(deps: TlsWatchDeps): TlsWatchController {\n\tlet reloadTimer: ReturnType<typeof setTimeout> | undefined;\n\tconst watchers: TlsFileWatcher[] = [];\n\tconst debounceMs = deps.debounceMs ?? 500;\n\tconst certBase = basename(deps.certPath);\n\tconst keyBase = basename(deps.keyPath);\n\tconst clearReloadTimer = () => {\n\t\tif (!reloadTimer) return;\n\t\tclearTimeout(reloadTimer);\n\t\treloadTimer = undefined;\n\t};\n\tconst scheduleReload = () => {\n\t\tclearReloadTimer();\n\t\treloadTimer = setTimeout(deps.reloadTls, debounceMs);\n\t};\n\n\tfor (const dir of new Set([dirname(deps.certPath), dirname(deps.keyPath)])) {\n\t\ttry {\n\t\t\tconst watcher = deps.watchDirectory(dir, (_event, filename) => {\n\t\t\t\t// `fs.watch` directory events on macOS (FSEvents) frequently fire\n\t\t\t\t// with `filename === null`; fall through and reload anyway.\n\t\t\t\t// On Linux (inotify) the basename is carried reliably and filters\n\t\t\t\t// out unrelated files in the parent directory.\n\t\t\t\tif (!shouldReloadForFile(filename, certBase, keyBase)) return;\n\t\t\t\tscheduleReload();\n\t\t\t});\n\t\t\twatcher.on(\"error\", (err) => {\n\t\t\t\tdeps.warn(`tls cert watch error: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t});\n\t\t\twatchers.push(watcher);\n\t\t} catch (err) {\n\t\t\tdeps.warn(`tls cert watch setup failed for ${dir}: ${err instanceof Error ? err.message : String(err)}`);\n\t\t}\n\t}\n\n\treturn { watchers, clearReloadTimer };\n}\n\nconst HELP = `dreb-dashboard — dreb web dashboard server\n\nUsage: dreb-dashboard [options]\n\nOptions:\n --port <n> Port to listen on (default ${DEFAULT_PORT})\n --remote Enable remote mode (requires Tailscale). Without this\n flag the server binds 127.0.0.1 only — no LAN access.\n Plain HTTP over the tailnet is an INSECURE context: add\n --https (below) or mobile PWA install + notifications\n (especially iOS) will not work.\n --allow <identity> Tailscale login name allowed to pair (repeatable;\n required with --remote)\n --https Terminate TLS on the dashboard itself (native TLS). No\n reverse proxy, no auth-model change. Requires --cert\n and --key. Mainly for --remote (loopback is already a\n secure context): use 'tailscale cert' files for a\n tailnet hostname so mobile PWAs + notifications work.\n NOTE: with --https the server speaks TLS only, so the\n host's plain-http local tab (http://127.0.0.1) stops\n working — use the tailnet hostname (https://...) there.\n --cert <path> PEM certificate file (required with --https)\n --key <path> PEM private key file (required with --https)\n --help Show this help\n`;\n\nasync function main(): Promise<void> {\n\tlet args: CliArgs;\n\ttry {\n\t\targs = parseArgs(process.argv.slice(2));\n\t} catch (err) {\n\t\tconsole.error(`error: ${err instanceof Error ? err.message : String(err)}`);\n\t\tconsole.error(HELP);\n\t\tprocess.exit(1);\n\t}\n\tif (args.help) {\n\t\tconsole.log(HELP);\n\t\treturn;\n\t}\n\n\tconst agentDir = join(homedir(), \".dreb\", \"agent\");\n\tconst auth = new DashboardAuth({\n\t\tremoteEnabled: args.remote,\n\t\tallowedIdentities: args.allow,\n\t\tstorage: new FilePairingStorage(join(agentDir, \"dashboard-pairings.json\")),\n\t\tsecret: loadOrCreateDashboardSecret(join(agentDir, \"dashboard-auth-secret\")),\n\t\tlogger: (line) => console.warn(`[dashboard-auth] ${line}`),\n\t});\n\tconst pool = new RuntimePool();\n\tconst imageService = new DashboardImageService(new ImagePreviewWorker());\n\n\t// Static client assets live next to the compiled server (dist/static).\n\tconst staticDir = join(dirname(fileURLToPath(import.meta.url)), \"static\");\n\n\t// The server's own build version (dist/index.js → ../package.json) — surfaced\n\t// in the settings footer so a stale long-running service is spottable.\n\tlet serverVersion: string | undefined;\n\ttry {\n\t\tconst pkgPath = join(dirname(fileURLToPath(import.meta.url)), \"..\", \"package.json\");\n\t\tserverVersion = JSON.parse(readFileSync(pkgPath, \"utf8\")).version;\n\t} catch {\n\t\tserverVersion = undefined;\n\t}\n\n\t// Restart hook: exit non-zero so a supervisor (systemd Restart=on-failure,\n\t// etc.) respawns the process with the freshly-built dist. Assigned the http\n\t// server below via a mutable holder so the closure can close it first.\n\t// The TLS hot-reload debounce timer and directory watchers are lifted here\n\t// too, so restart and signal shutdown can release them (otherwise they leak\n\t// across restart/exit).\n\tlet httpServer: HttpServer | HttpsServer | undefined;\n\tlet clearTlsReloadTimer = () => {};\n\tlet closeDashboard = () => imageService.close();\n\tconst tlsWatchers: TlsFileWatcher[] = [];\n\tconst beginShutdown = createShutdown({\n\t\tlog: (message) => console.log(message),\n\t\tclearReloadTimer: () => clearTlsReloadTimer(),\n\t\twatchers: tlsWatchers,\n\t\tcloseServer: () => httpServer?.close(),\n\t\tstopAll: () => Promise.all([pool.stopAll(), closeDashboard()]),\n\t\texit: (code) => process.exit(code),\n\t});\n\tconst onRestart = () => beginShutdown(\"restart requested — exiting for supervisor to respawn\", 1);\n\n\tconst { SessionManager } = await import(\"@dreb/coding-agent\");\n\tconst app = createDashboardServer({\n\t\tauth,\n\t\tpool,\n\t\timageService,\n\t\tstaticDir: existsSync(staticDir) ? staticDir : undefined,\n\t\tserverVersion,\n\t\tonRestart,\n\t\tlistAllSessions: () => SessionManager.listAll(),\n\t\tdeleteSession: async (path: string) => {\n\t\t\tconst result = await SessionManager.deleteSession(path, {});\n\t\t\tif (!result.ok) throw new Error(result.error ?? \"Unknown deletion error\");\n\t\t\treturn { method: result.method };\n\t\t},\n\t});\n\tcloseDashboard = () => app.closeDashboard();\n\n\tconst host = args.remote ? \"0.0.0.0\" : \"127.0.0.1\";\n\tconst scheme = args.https ? \"https\" : \"http\";\n\n\t// Native TLS: the dashboard terminates TLS itself (no reverse proxy). The\n\t// auth model is unchanged — `req.socket.remoteAddress` is still the real\n\t// tailnet IP, so Tailscale identity resolution + allowlist + pairing keep\n\t// working. Local mode never sets --https (loopback is already a secure\n\t// context), but it's allowed if the operator wants it.\n\tlet server: HttpServer | HttpsServer;\n\tif (args.https && args.cert && args.key) {\n\t\tconst readTlsOptions = () => ({\n\t\t\tcert: readFileSync(args.cert!, \"utf-8\"),\n\t\t\tkey: readFileSync(args.key!, \"utf-8\"),\n\t\t});\n\t\tlet tlsOptions: TlsOptions;\n\t\ttry {\n\t\t\ttlsOptions = readTlsOptions();\n\t\t} catch (err) {\n\t\t\tconsole.error(`error: failed to read TLS cert/key: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tconst httpsServer = createHttpsServer(tlsOptions, app);\n\t\t// Hot-reload the cert on file change (zero-downtime renewal — e.g. a\n\t\t// systemd timer rewrites the `tailscale cert` files daily). New\n\t\t// connections pick up the new cert; existing ones finish on the old.\n\t\tconst reloadTls = createTlsReloader({\n\t\t\treadTlsOptions,\n\t\t\tsetSecureContext: (options) => httpsServer.setSecureContext(options),\n\t\t\tlog: (message) => console.log(message),\n\t\t\twarn: (message) => console.warn(message),\n\t\t});\n\t\t// Debounce: cert + key are often rewritten in quick succession. Watch\n\t\t// the PARENT DIRECTORY (not each file) and filter by filename: `fs.watch`\n\t\t// follows the inode, so an atomic renewal (write temp + rename(2))\n\t\t// replaces the inode and a file-level watcher goes silent on the new\n\t\t// file after the first reload. A directory watcher survives renames and\n\t\t// reports the changed basename via the `filename` callback argument.\n\t\tconst tlsWatchController = createTlsWatchers({\n\t\t\tcertPath: args.cert,\n\t\t\tkeyPath: args.key,\n\t\t\twatchDirectory: (dir, listener) => watch(dir, listener),\n\t\t\treloadTls,\n\t\t\twarn: (message) => console.warn(message),\n\t\t});\n\t\tclearTlsReloadTimer = tlsWatchController.clearReloadTimer;\n\t\ttlsWatchers.push(...tlsWatchController.watchers);\n\t\tserver = httpsServer;\n\t} else {\n\t\tserver = createHttpServer(app);\n\t}\n\tserver.listen(args.port, host, () => {\n\t\tconsole.log(\n\t\t\t`dreb dashboard listening on ${scheme}://${host === \"0.0.0.0\" ? \"<tailscale-ip>\" : host}:${args.port}`,\n\t\t);\n\t\tif (args.remote) {\n\t\t\tconsole.log(`remote mode: allowed identities = ${args.allow.join(\", \")}`);\n\t\t\tconst { code, expiresInMs } = auth.currentPairingCode();\n\t\t\tconsole.log(\n\t\t\t\t`pairing code: ${code} (rotates every 30s; current code rolls in ${Math.ceil(expiresInMs / 1000)}s)`,\n\t\t\t);\n\t\t\tconsole.log(\"new devices enter this code; see it live in dashboard Settings on the host machine\");\n\t\t} else {\n\t\t\tconsole.log(\"local mode: loopback only — use --remote for Tailscale access\");\n\t\t}\n\t\tif (args.https) {\n\t\t\tconsole.log(\"tls: native HTTPS enabled (cert + key hot-reload on file change)\");\n\t\t} else {\n\t\t\tconst insecureWarning = insecureRemoteWarning(args);\n\t\t\tif (insecureWarning) console.warn(insecureWarning);\n\t\t}\n\t});\n\thttpServer = server;\n\n\tconst shutdown = () => beginShutdown(\"shutting down…\", 0);\n\tprocess.on(\"SIGINT\", shutdown);\n\tprocess.on(\"SIGTERM\", shutdown);\n}\n\n// Only run when executed directly (not when imported for the library exports).\nconst entryPath = process.argv[1];\nif (entryPath && import.meta.url === new URL(`file://${entryPath}`).href) {\n\tmain().catch((err) => {\n\t\tconsole.error(`fatal: ${err instanceof Error ? err.message : String(err)}`);\n\t\tprocess.exit(1);\n\t});\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index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ACH,UAAU,GAAG,MAAM,CAAC;IAEpB,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,aAAa,CAAC,kBAAgB,EAAE,CAAC,CAAC,CAAC;IAC1D,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC/B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AAAA,CAChC;AAED,+EAA+E;AAC/E,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClC,IAAI,SAAS,IAAI,OAAO,IAAI,CAAC,GAAG,KAAK,IAAI,GAAG,CAAC,UAAU,SAAS,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAC1E,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;QACrB,OAAO,CAAC,KAAK,CAAC,UAAU,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAC5E,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAAA,CAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * dreb-dashboard — launch the dreb web dashboard server.\n *\n * Modes (exactly two, no LAN mode):\n * default loopback bind (127.0.0.1), no auth, no Tailscale needed\n * --remote requires Tailscale; binds all interfaces but every request\n * passes identity allowlist + pairing code + device cookies\n *\n * Usage:\n * dreb-dashboard [--port 5343] [--remote --allow me@example.com [--allow ...]]\n */\n\nimport { existsSync, readFileSync, watch } from \"node:fs\";\nimport { createServer as createHttpServer, type Server as HttpServer } from \"node:http\";\nimport { createServer as createHttpsServer, type Server as HttpsServer } from \"node:https\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { DashboardAuth } from \"./server/auth.js\";\nimport { DashboardImageService } from \"./server/dashboard-images.js\";\nimport { ImagePreviewWorker } from \"./server/image-preview.js\";\nimport { FilePairingStorage, loadOrCreateDashboardSecret } from \"./server/pairing-storage.js\";\nimport { RuntimePool } from \"./server/runtime-pool.js\";\nimport { createDashboardServer } from \"./server/server.js\";\n\nexport { DashboardAuth, TailscaleStatusResolver, TailscaleWhoisResolver } from \"./server/auth.js\";\nexport { DashboardImageService } from \"./server/dashboard-images.js\";\nexport { EventHub } from \"./server/event-hub.js\";\nexport { canonicalizePath, FileApi, resolveExistingDirectory } from \"./server/files.js\";\nexport { ImagePreviewWorker } from \"./server/image-preview.js\";\nexport { FilePairingStorage, loadOrCreateDashboardSecret } from \"./server/pairing-storage.js\";\nexport { RuntimePool, resolveDrebCliPath } from \"./server/runtime-pool.js\";\nexport { createDashboardServer, parseDeviceCookie } from \"./server/server.js\";\nexport type * from \"./shared/protocol.js\";\n\nconst DEFAULT_PORT = 5343;\n\ninterface CliArgs {\n\tport: number;\n\tremote: boolean;\n\tallow: string[];\n\thelp: boolean;\n\thttps: boolean;\n\tcert?: string;\n\tkey?: string;\n}\n\nexport function parseArgs(argv: string[]): CliArgs {\n\tconst args: CliArgs = { port: DEFAULT_PORT, remote: false, allow: [], help: false, https: false };\n\tfor (let i = 0; i < argv.length; i++) {\n\t\tconst arg = argv[i];\n\t\tif (arg === \"--port\") {\n\t\t\tconst value = argv[++i];\n\t\t\tconst port = Number.parseInt(value ?? \"\", 10);\n\t\t\tif (!Number.isInteger(port) || port < 1 || port > 65535) {\n\t\t\t\tthrow new Error(`Invalid --port value: ${value}`);\n\t\t\t}\n\t\t\targs.port = port;\n\t\t} else if (arg === \"--remote\") {\n\t\t\targs.remote = true;\n\t\t} else if (arg === \"--allow\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--allow requires an identity (Tailscale login name)\");\n\t\t\targs.allow.push(value);\n\t\t} else if (arg === \"--https\") {\n\t\t\targs.https = true;\n\t\t} else if (arg === \"--cert\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--cert requires a path to a PEM certificate file\");\n\t\t\targs.cert = value;\n\t\t} else if (arg === \"--key\") {\n\t\t\tconst value = argv[++i];\n\t\t\tif (!value) throw new Error(\"--key requires a path to a PEM private key file\");\n\t\t\targs.key = value;\n\t\t} else if (arg === \"--help\" || arg === \"-h\") {\n\t\t\targs.help = true;\n\t\t} else {\n\t\t\tthrow new Error(`Unknown argument: ${arg}`);\n\t\t}\n\t}\n\tif (args.remote && args.allow.length === 0) {\n\t\tthrow new Error(\"--remote requires at least one --allow <tailscale-login> (empty allowlist denies everyone)\");\n\t}\n\t// Native TLS. `https` is opt-in; it requires cert AND key (no silent\n\t// fallback to plain HTTP). The dashboard terminates TLS itself — no reverse\n\t// proxy, no auth-model change. `req.socket.remoteAddress` stays the real\n\t// tailnet IP, so identity resolution + allowlist + pairing keep working.\n\tif (args.https) {\n\t\tif (!args.cert) throw new Error(\"--https requires --cert <path>\");\n\t\tif (!args.key) throw new Error(\"--https requires --key <path>\");\n\t}\n\treturn args;\n}\n\n/**\n * Warning shown at startup when `--remote` binds the tailnet over plain HTTP\n * (no `--https`). Browsers treat plain HTTP over a non-loopback host as an\n * INSECURE context, so service workers and the Notification API are\n * unavailable — PWA install and mobile notifications (iOS exposes no\n * Notification API at all there) silently never work. Loopback (127.0.0.1) is\n * exempt (it counts as secure), so pure-local mode returns no warning.\n *\n * Returns the multi-line warning string, or `undefined` when TLS is enabled or\n * the server is loopback-only. Kept pure (no console) so it is unit-testable.\n */\nexport function insecureRemoteWarning(args: Pick<CliArgs, \"remote\" | \"https\">): string | undefined {\n\tif (!args.remote || args.https) return undefined;\n\treturn (\n\t\t\"⚠ warning: --remote without --https serves plain HTTP over the tailnet, which browsers treat as an\\n\" +\n\t\t\" INSECURE context — service workers, PWA install, and mobile notifications (especially iOS) will NOT work.\\n\" +\n\t\t\" Enable TLS for the tailnet hostname:\\n\" +\n\t\t\" tailscale cert <host>.<tailnet>.ts.net\\n\" +\n\t\t\" …then relaunch with --https --cert <host>.<tailnet>.ts.net.crt --key <host>.<tailnet>.ts.net.key\\n\" +\n\t\t\" and open the dashboard via https://<host>.<tailnet>.ts.net (the hostname, not the tailnet IP).\"\n\t);\n}\n\ntype ShutdownWatcher = Pick<ReturnType<typeof watch>, \"close\">;\n\ninterface ShutdownDeps {\n\tlog: (message: string) => void;\n\tclearReloadTimer: () => void;\n\twatchers: Iterable<ShutdownWatcher>;\n\tcloseServer: () => void;\n\tstopAll: () => Promise<unknown>;\n\texit: (code: number) => void;\n}\n\nexport function createShutdown(deps: ShutdownDeps): (message: string, exitCode: number) => void {\n\tlet shuttingDown = false;\n\treturn (message: string, exitCode: number) => {\n\t\tif (shuttingDown) return;\n\t\tshuttingDown = true;\n\t\tdeps.log(message);\n\t\tdeps.clearReloadTimer();\n\t\tfor (const watcher of deps.watchers) watcher.close();\n\t\tdeps.closeServer();\n\t\tvoid deps\n\t\t\t.stopAll()\n\t\t\t.catch((err) => {\n\t\t\t\tdeps.log(`shutdown teardown failed: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t})\n\t\t\t.finally(() => deps.exit(exitCode));\n\t};\n}\n\ntype TlsOptions = { cert: string; key: string };\ntype TlsWatchFilename = string | Buffer | null;\ntype TlsWatchListener = (event: string, filename: TlsWatchFilename) => void;\ntype TlsFileWatcher = ShutdownWatcher & {\n\ton(event: \"error\", listener: (err: unknown) => void): unknown;\n};\n\ninterface TlsReloaderDeps {\n\treadTlsOptions: () => TlsOptions;\n\tsetSecureContext: (options: TlsOptions) => void;\n\tlog: (message: string) => void;\n\twarn: (message: string) => void;\n}\n\nexport function createTlsReloader(deps: TlsReloaderDeps): () => void {\n\treturn () => {\n\t\ttry {\n\t\t\tdeps.setSecureContext(deps.readTlsOptions());\n\t\t\tdeps.log(\"tls certificate reloaded\");\n\t\t} catch (err) {\n\t\t\tdeps.warn(`tls reload failed (keeping old cert): ${err instanceof Error ? err.message : String(err)}`);\n\t\t}\n\t};\n}\n\nexport function shouldReloadForFile(filename: TlsWatchFilename, certBase: string, keyBase: string): boolean {\n\tif (filename == null) return true;\n\tif (typeof filename !== \"string\") return false;\n\treturn filename === certBase || filename === keyBase;\n}\n\ninterface TlsWatchDeps {\n\tcertPath: string;\n\tkeyPath: string;\n\twatchDirectory: (directory: string, listener: TlsWatchListener) => TlsFileWatcher;\n\treloadTls: () => void;\n\twarn: (message: string) => void;\n\tdebounceMs?: number;\n}\n\ninterface TlsWatchController {\n\twatchers: TlsFileWatcher[];\n\tclearReloadTimer: () => void;\n}\n\nexport function createTlsWatchers(deps: TlsWatchDeps): TlsWatchController {\n\tlet reloadTimer: ReturnType<typeof setTimeout> | undefined;\n\tconst watchers: TlsFileWatcher[] = [];\n\tconst debounceMs = deps.debounceMs ?? 500;\n\tconst certBase = basename(deps.certPath);\n\tconst keyBase = basename(deps.keyPath);\n\tconst clearReloadTimer = () => {\n\t\tif (!reloadTimer) return;\n\t\tclearTimeout(reloadTimer);\n\t\treloadTimer = undefined;\n\t};\n\tconst scheduleReload = () => {\n\t\tclearReloadTimer();\n\t\treloadTimer = setTimeout(deps.reloadTls, debounceMs);\n\t};\n\n\tfor (const dir of new Set([dirname(deps.certPath), dirname(deps.keyPath)])) {\n\t\ttry {\n\t\t\tconst watcher = deps.watchDirectory(dir, (_event, filename) => {\n\t\t\t\t// `fs.watch` directory events on macOS (FSEvents) frequently fire\n\t\t\t\t// with `filename === null`; fall through and reload anyway.\n\t\t\t\t// On Linux (inotify) the basename is carried reliably and filters\n\t\t\t\t// out unrelated files in the parent directory.\n\t\t\t\tif (!shouldReloadForFile(filename, certBase, keyBase)) return;\n\t\t\t\tscheduleReload();\n\t\t\t});\n\t\t\twatcher.on(\"error\", (err) => {\n\t\t\t\tdeps.warn(`tls cert watch error: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t});\n\t\t\twatchers.push(watcher);\n\t\t} catch (err) {\n\t\t\tdeps.warn(`tls cert watch setup failed for ${dir}: ${err instanceof Error ? err.message : String(err)}`);\n\t\t}\n\t}\n\n\treturn { watchers, clearReloadTimer };\n}\n\nconst HELP = `dreb-dashboard — dreb web dashboard server\n\nUsage: dreb-dashboard [options]\n\nOptions:\n --port <n> Port to listen on (default ${DEFAULT_PORT})\n --remote Enable remote mode (requires Tailscale). Without this\n flag the server binds 127.0.0.1 only — no LAN access.\n Plain HTTP over the tailnet is an INSECURE context: add\n --https (below) or mobile PWA install + notifications\n (especially iOS) will not work.\n --allow <identity> Tailscale login name allowed to pair (repeatable;\n required with --remote)\n --https Terminate TLS on the dashboard itself (native TLS). No\n reverse proxy, no auth-model change. Requires --cert\n and --key. Mainly for --remote (loopback is already a\n secure context): use 'tailscale cert' files for a\n tailnet hostname so mobile PWAs + notifications work.\n NOTE: with --https the server speaks TLS only, so the\n host's plain-http local tab (http://127.0.0.1) stops\n working — use the tailnet hostname (https://...) there.\n --cert <path> PEM certificate file (required with --https)\n --key <path> PEM private key file (required with --https)\n --help Show this help\n`;\n\nasync function main(): Promise<void> {\n\tlet args: CliArgs;\n\ttry {\n\t\targs = parseArgs(process.argv.slice(2));\n\t} catch (err) {\n\t\tconsole.error(`error: ${err instanceof Error ? err.message : String(err)}`);\n\t\tconsole.error(HELP);\n\t\tprocess.exit(1);\n\t}\n\tif (args.help) {\n\t\tconsole.log(HELP);\n\t\treturn;\n\t}\n\n\tconst agentDir = join(homedir(), \".dreb\", \"agent\");\n\tconst auth = new DashboardAuth({\n\t\tremoteEnabled: args.remote,\n\t\tallowedIdentities: args.allow,\n\t\tstorage: new FilePairingStorage(join(agentDir, \"dashboard-pairings.json\")),\n\t\tsecret: loadOrCreateDashboardSecret(join(agentDir, \"dashboard-auth-secret\")),\n\t\tlogger: (line) => console.warn(`[dashboard-auth] ${line}`),\n\t});\n\tconst pool = new RuntimePool();\n\tconst imageService = new DashboardImageService(new ImagePreviewWorker());\n\n\t// Static client assets live next to the compiled server (dist/static).\n\tconst staticDir = join(dirname(fileURLToPath(import.meta.url)), \"static\");\n\n\t// The server's own build version (dist/index.js → ../package.json) — surfaced\n\t// in the settings footer so a stale long-running service is spottable.\n\tlet serverVersion: string | undefined;\n\ttry {\n\t\tconst pkgPath = join(dirname(fileURLToPath(import.meta.url)), \"..\", \"package.json\");\n\t\tserverVersion = JSON.parse(readFileSync(pkgPath, \"utf8\")).version;\n\t} catch {\n\t\tserverVersion = undefined;\n\t}\n\n\t// Restart hook: exit non-zero so a supervisor (systemd Restart=on-failure,\n\t// etc.) respawns the process with the freshly-built dist. Assigned the http\n\t// server below via a mutable holder so the closure can close it first.\n\t// The TLS hot-reload debounce timer and directory watchers are lifted here\n\t// too, so restart and signal shutdown can release them (otherwise they leak\n\t// across restart/exit).\n\tlet httpServer: HttpServer | HttpsServer | undefined;\n\tlet clearTlsReloadTimer = () => {};\n\tlet closeDashboard = () => imageService.close();\n\tconst tlsWatchers: TlsFileWatcher[] = [];\n\tconst beginShutdown = createShutdown({\n\t\tlog: (message) => console.log(message),\n\t\tclearReloadTimer: () => clearTlsReloadTimer(),\n\t\twatchers: tlsWatchers,\n\t\tcloseServer: () => httpServer?.close(),\n\t\tstopAll: () => Promise.all([pool.stopAll(), closeDashboard()]),\n\t\texit: (code) => process.exit(code),\n\t});\n\tconst onRestart = () => beginShutdown(\"restart requested — exiting for supervisor to respawn\", 1);\n\n\tconst { SessionManager } = await import(\"@dreb/coding-agent\");\n\tconst app = createDashboardServer({\n\t\tauth,\n\t\tpool,\n\t\timageService,\n\t\tstaticDir: existsSync(staticDir) ? staticDir : undefined,\n\t\tserverVersion,\n\t\tonRestart,\n\t\tlistAllSessions: () => SessionManager.listAll(),\n\t\tdeleteSession: async (path: string) => {\n\t\t\tconst result = await SessionManager.deleteSession(path, {});\n\t\t\tif (!result.ok) throw new Error(result.error ?? \"Unknown deletion error\");\n\t\t\treturn { method: result.method };\n\t\t},\n\t});\n\tcloseDashboard = () => app.closeDashboard();\n\n\tconst host = args.remote ? \"0.0.0.0\" : \"127.0.0.1\";\n\tconst scheme = args.https ? \"https\" : \"http\";\n\n\t// Native TLS: the dashboard terminates TLS itself (no reverse proxy). The\n\t// auth model is unchanged — `req.socket.remoteAddress` is still the real\n\t// tailnet IP, so Tailscale identity resolution + allowlist + pairing keep\n\t// working. Local mode never sets --https (loopback is already a secure\n\t// context), but it's allowed if the operator wants it.\n\tlet server: HttpServer | HttpsServer;\n\tif (args.https && args.cert && args.key) {\n\t\tconst readTlsOptions = () => ({\n\t\t\tcert: readFileSync(args.cert!, \"utf-8\"),\n\t\t\tkey: readFileSync(args.key!, \"utf-8\"),\n\t\t});\n\t\tlet tlsOptions: TlsOptions;\n\t\ttry {\n\t\t\ttlsOptions = readTlsOptions();\n\t\t} catch (err) {\n\t\t\tconsole.error(`error: failed to read TLS cert/key: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tconst httpsServer = createHttpsServer(tlsOptions, app);\n\t\t// Hot-reload the cert on file change (zero-downtime renewal — e.g. a\n\t\t// systemd timer rewrites the `tailscale cert` files daily). New\n\t\t// connections pick up the new cert; existing ones finish on the old.\n\t\tconst reloadTls = createTlsReloader({\n\t\t\treadTlsOptions,\n\t\t\tsetSecureContext: (options) => httpsServer.setSecureContext(options),\n\t\t\tlog: (message) => console.log(message),\n\t\t\twarn: (message) => console.warn(message),\n\t\t});\n\t\t// Debounce: cert + key are often rewritten in quick succession. Watch\n\t\t// the PARENT DIRECTORY (not each file) and filter by filename: `fs.watch`\n\t\t// follows the inode, so an atomic renewal (write temp + rename(2))\n\t\t// replaces the inode and a file-level watcher goes silent on the new\n\t\t// file after the first reload. A directory watcher survives renames and\n\t\t// reports the changed basename via the `filename` callback argument.\n\t\tconst tlsWatchController = createTlsWatchers({\n\t\t\tcertPath: args.cert,\n\t\t\tkeyPath: args.key,\n\t\t\twatchDirectory: (dir, listener) => watch(dir, listener),\n\t\t\treloadTls,\n\t\t\twarn: (message) => console.warn(message),\n\t\t});\n\t\tclearTlsReloadTimer = tlsWatchController.clearReloadTimer;\n\t\ttlsWatchers.push(...tlsWatchController.watchers);\n\t\tserver = httpsServer;\n\t} else {\n\t\tserver = createHttpServer(app);\n\t}\n\tserver.listen(args.port, host, () => {\n\t\tconsole.log(\n\t\t\t`dreb dashboard listening on ${scheme}://${host === \"0.0.0.0\" ? \"<tailscale-ip>\" : host}:${args.port}`,\n\t\t);\n\t\tif (args.remote) {\n\t\t\tconsole.log(`remote mode: allowed identities = ${args.allow.join(\", \")}`);\n\t\t\tconst { code, expiresInMs } = auth.currentPairingCode();\n\t\t\tconsole.log(\n\t\t\t\t`pairing code: ${code} (rotates every 30s; current code rolls in ${Math.ceil(expiresInMs / 1000)}s)`,\n\t\t\t);\n\t\t\tconsole.log(\"new devices enter this code; see it live in dashboard Settings on the host machine\");\n\t\t} else {\n\t\t\tconsole.log(\"local mode: loopback only — use --remote for Tailscale access\");\n\t\t}\n\t\tif (args.https) {\n\t\t\tconsole.log(\"tls: native HTTPS enabled (cert + key hot-reload on file change)\");\n\t\t} else {\n\t\t\tconst insecureWarning = insecureRemoteWarning(args);\n\t\t\tif (insecureWarning) console.warn(insecureWarning);\n\t\t}\n\t});\n\thttpServer = server;\n\n\tconst shutdown = () => beginShutdown(\"shutting down…\", 0);\n\tprocess.on(\"SIGINT\", shutdown);\n\tprocess.on(\"SIGTERM\", shutdown);\n}\n\n// Only run when executed directly (not when imported for the library exports).\nconst entryPath = process.argv[1];\nif (entryPath && import.meta.url === new URL(`file://${entryPath}`).href) {\n\tmain().catch((err) => {\n\t\tconsole.error(`fatal: ${err instanceof Error ? err.message : String(err)}`);\n\t\tprocess.exit(1);\n\t});\n}\n"]}
@@ -19,6 +19,8 @@ export type FileOpLogger = (operation: string, path: string, detail?: string) =>
19
19
  export declare function canonicalizePath(raw: string, opts: {
20
20
  mustExist: boolean;
21
21
  }): Promise<string>;
22
+ /** Resolve and canonicalize an existing directory supplied by a Dashboard client. */
23
+ export declare function resolveExistingDirectory(rawPath: string): Promise<string>;
22
24
  export declare class FileApi {
23
25
  private readonly log;
24
26
  constructor(log: FileOpLogger);
@@ -1 +1 @@
1
- {"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../../src/server/files.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,aAAa,EAAgB,MAAM,uBAAuB,CAAC;AAEzE,MAAM,MAAM,YAAY,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;AAQtF;;;;;GAKG;AACH,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE;IAAE,SAAS,EAAE,OAAO,CAAA;CAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAwCjG;AAED,qBAAa,OAAO;IACP,OAAO,CAAC,QAAQ,CAAC,GAAG;IAAhC,YAA6B,GAAG,EAAE,YAAY,EAAI;IAElD,kFAAkF;IAC5E,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAOvD;IAEK,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC,CA2BxE;IAED,8EAA8E;IACxE,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAQ9E;IAED;;;OAGG;IACG,aAAa,CAClB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,OAAO,GAChB,OAAO,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,QAAQ,CAAC;QAAC,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;QAAC,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;KAAE,CAAC,CAkDxG;IAEK,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAOzD;CACD;AAED,kDAAkD;AAClD,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAS7G","sourcesContent":["/**\n * Host-wide file API — browse, download, upload, mkdir.\n *\n * The dashboard is a trusted-operator surface: a paired device\n * already equals terminal access, so there is no project jail. Path handling\n * still canonicalizes and rejects confusion tricks so the *API* cannot be\n * abused: percent-decode checks, null-byte rejection, symlink resolution to a\n * real absolute path, and server-side logging of every operation.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { link, mkdir, open, readdir, realpath, rename, stat, unlink } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, normalize, resolve, sep } from \"node:path\";\nimport type { Writable } from \"node:stream\";\nimport type { DirListingDto, FileEntryDto } from \"../shared/protocol.js\";\n\nexport type FileOpLogger = (operation: string, path: string, detail?: string) => void;\n\nfunction assertValidChildName(name: string, label: string): void {\n\tif (!name || name.includes(\"/\") || name.includes(\"\\\\\") || name.includes(\"\\0\") || name === \".\" || name === \"..\") {\n\t\tthrow Object.assign(new Error(`Invalid ${label}: ${name}`), { status: 400 });\n\t}\n}\n\n/**\n * Canonicalize a client-supplied path. Throws (status 400) on anything\n * suspicious rather than guessing. Returns the resolved absolute path with\n * symlinks in the *parent* chain resolved (the leaf may not exist yet for\n * writes, so its parent is what gets realpath'd).\n */\nexport async function canonicalizePath(raw: string, opts: { mustExist: boolean }): Promise<string> {\n\tif (typeof raw !== \"string\" || raw.length === 0) {\n\t\tthrow Object.assign(new Error(\"Path is required\"), { status: 400 });\n\t}\n\tif (raw.includes(\"\\0\")) {\n\t\tthrow Object.assign(new Error(\"Path contains a null byte\"), { status: 400 });\n\t}\n\t// Reject lingering percent-encodings that survived normal URL decoding —\n\t// double-encoding is a classic canonicalization-confusion vector.\n\tif (/%2e|%2f|%5c|%00/i.test(raw)) {\n\t\tthrow Object.assign(new Error(\"Path contains percent-encoded traversal sequences\"), { status: 400 });\n\t}\n\tif (!isAbsolute(raw)) {\n\t\tthrow Object.assign(new Error(\"Path must be absolute\"), { status: 400 });\n\t}\n\tconst normalized = normalize(raw);\n\n\tif (opts.mustExist) {\n\t\ttry {\n\t\t\treturn await realpath(normalized);\n\t\t} catch (err) {\n\t\t\tthrow Object.assign(new Error(`Path does not exist or is unreadable: ${normalized}`), {\n\t\t\t\tstatus: 404,\n\t\t\t\tcause: err,\n\t\t\t});\n\t\t}\n\t}\n\t// For creation targets: resolve the parent, keep the leaf name literal.\n\tconst parent = dirname(normalized);\n\tlet realParent: string;\n\ttry {\n\t\trealParent = await realpath(parent);\n\t} catch (err) {\n\t\tthrow Object.assign(new Error(`Parent directory does not exist: ${parent}`), { status: 404, cause: err });\n\t}\n\tconst leaf = normalized.slice(parent === sep ? 1 : parent.length + 1);\n\tif (!leaf || leaf.includes(sep) || leaf === \".\" || leaf === \"..\") {\n\t\tthrow Object.assign(new Error(`Invalid file name: ${leaf || \"(empty)\"}`), { status: 400 });\n\t}\n\treturn join(realParent, leaf);\n}\n\nexport class FileApi {\n\tconstructor(private readonly log: FileOpLogger) {}\n\n\t/** Resolve an existing directory for listing and context-trust RPC operations. */\n\tasync resolveDirectory(rawPath: string): Promise<string> {\n\t\tconst path = await canonicalizePath(rawPath, { mustExist: true });\n\t\tconst info = await stat(path);\n\t\tif (!info.isDirectory()) {\n\t\t\tthrow Object.assign(new Error(`Not a directory: ${path}`), { status: 400 });\n\t\t}\n\t\treturn path;\n\t}\n\n\tasync list(rawPath: string): Promise<Omit<DirListingDto, \"contextTrust\">> {\n\t\tconst path = await this.resolveDirectory(rawPath);\n\t\tconst names = await readdir(path, { withFileTypes: true });\n\t\tconst entries: FileEntryDto[] = [];\n\t\tfor (const dirent of names) {\n\t\t\tlet type: FileEntryDto[\"type\"] = \"other\";\n\t\t\tif (dirent.isDirectory()) type = \"dir\";\n\t\t\telse if (dirent.isFile()) type = \"file\";\n\t\t\telse if (dirent.isSymbolicLink()) type = \"symlink\";\n\t\t\tlet size = 0;\n\t\t\tlet modified = \"\";\n\t\t\ttry {\n\t\t\t\tconst s = await stat(join(path, dirent.name));\n\t\t\t\tsize = s.size;\n\t\t\t\tmodified = s.mtime.toISOString();\n\t\t\t\tif (type === \"symlink\") type = s.isDirectory() ? \"dir\" : \"file\";\n\t\t\t} catch {\n\t\t\t\t// Broken symlink or permission issue — keep the entry, mark it \"other\".\n\t\t\t\ttype = \"other\";\n\t\t\t}\n\t\t\tentries.push({ name: dirent.name, type, size, modified });\n\t\t}\n\t\tentries.sort((a, b) =>\n\t\t\t(a.type === \"dir\") === (b.type === \"dir\") ? a.name.localeCompare(b.name) : a.type === \"dir\" ? -1 : 1,\n\t\t);\n\t\tthis.log(\"list\", path);\n\t\treturn { path, entries };\n\t}\n\n\t/** Resolve a download target; returns the canonical path (must be a file). */\n\tasync resolveDownload(rawPath: string): Promise<{ path: string; size: number }> {\n\t\tconst path = await canonicalizePath(rawPath, { mustExist: true });\n\t\tconst info = await stat(path);\n\t\tif (!info.isFile()) {\n\t\t\tthrow Object.assign(new Error(`Not a file: ${path}`), { status: 400 });\n\t\t}\n\t\tthis.log(\"download\", path, `${info.size} bytes`);\n\t\treturn { path, size: info.size };\n\t}\n\n\t/**\n\t * Upload into a directory. Refuses to overwrite unless `overwrite` is set —\n\t * the collision surfaces as 409 so the client can prompt.\n\t */\n\tasync prepareUpload(\n\t\trawDir: string,\n\t\tfileName: string,\n\t\toverwrite: boolean,\n\t): Promise<{ path: string; stream: Writable; commit: () => Promise<void>; cleanup: () => Promise<void> }> {\n\t\tconst dir = await canonicalizePath(rawDir, { mustExist: true });\n\t\tconst dirInfo = await stat(dir);\n\t\tif (!dirInfo.isDirectory()) {\n\t\t\tthrow Object.assign(new Error(`Upload target is not a directory: ${dir}`), { status: 400 });\n\t\t}\n\t\tassertValidChildName(fileName, \"upload file name\");\n\t\tconst path = join(dir, fileName);\n\t\tlet exists = false;\n\t\ttry {\n\t\t\tawait stat(path);\n\t\t\texists = true;\n\t\t} catch {\n\t\t\texists = false;\n\t\t}\n\t\tif (exists && !overwrite) {\n\t\t\tthrow Object.assign(new Error(`File exists: ${path}`), { status: 409 });\n\t\t}\n\n\t\tconst tempPath = join(dir, `.dreb-upload-${process.pid}-${Date.now()}-${randomBytes(6).toString(\"hex\")}.tmp`);\n\t\tconst file = await open(tempPath, \"wx\");\n\t\tconst stream = file.createWriteStream({ autoClose: true });\n\t\tlet committed = false;\n\t\tconst cleanup = async () => {\n\t\t\tif (committed) return;\n\t\t\tawait unlink(tempPath).catch(() => {});\n\t\t};\n\t\tconst commit = async () => {\n\t\t\ttry {\n\t\t\t\tif (overwrite) {\n\t\t\t\t\tawait rename(tempPath, path);\n\t\t\t\t} else {\n\t\t\t\t\t// Atomic no-overwrite publish: hard-link into the final name and fail\n\t\t\t\t\t// with EEXIST if another writer won the race after the early stat().\n\t\t\t\t\tawait link(tempPath, path).catch((err: NodeJS.ErrnoException) => {\n\t\t\t\t\t\tif (err.code === \"EEXIST\") {\n\t\t\t\t\t\t\tthrow Object.assign(new Error(`File exists: ${path}`), { status: 409, cause: err });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t});\n\t\t\t\t\tawait unlink(tempPath);\n\t\t\t\t}\n\t\t\t\tcommitted = true;\n\t\t\t\tthis.log(\"upload\", path, exists ? \"overwrite\" : \"create\");\n\t\t\t} catch (err) {\n\t\t\t\tawait cleanup();\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t};\n\t\treturn { path, stream, commit, cleanup };\n\t}\n\n\tasync mkdir(rawDir: string, name: string): Promise<string> {\n\t\tassertValidChildName(name, \"folder name\");\n\t\tconst parent = await canonicalizePath(rawDir, { mustExist: true });\n\t\tconst path = join(parent, name);\n\t\tawait mkdir(path);\n\t\tthis.log(\"mkdir\", path);\n\t\treturn path;\n\t}\n}\n\n/** Places shown as shortcuts in the files tab. */\nexport function defaultPlaces(homeDir: string, projectRoots: string[]): Array<{ label: string; path: string }> {\n\tconst places = [\n\t\t{ label: \"home\", path: homeDir },\n\t\t{ label: \"/tmp\", path: resolve(\"/tmp\") },\n\t];\n\tfor (const root of projectRoots) {\n\t\tplaces.push({ label: root.split(sep).filter(Boolean).pop() ?? root, path: root });\n\t}\n\treturn places;\n}\n"]}
1
+ {"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../../src/server/files.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAMH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,aAAa,EAAgB,MAAM,uBAAuB,CAAC;AAEzE,MAAM,MAAM,YAAY,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;AAQtF;;;;;GAKG;AACH,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE;IAAE,SAAS,EAAE,OAAO,CAAA;CAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAwCjG;AAED,qFAAqF;AACrF,wBAAsB,wBAAwB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAoB/E;AAED,qBAAa,OAAO;IACP,OAAO,CAAC,QAAQ,CAAC,GAAG;IAAhC,YAA6B,GAAG,EAAE,YAAY,EAAI;IAElD,kFAAkF;IAC5E,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEvD;IAEK,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC,CA2BxE;IAED,8EAA8E;IACxE,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAQ9E;IAED;;;OAGG;IACG,aAAa,CAClB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,OAAO,GAChB,OAAO,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,QAAQ,CAAC;QAAC,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;QAAC,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;KAAE,CAAC,CAkDxG;IAEK,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAOzD;CACD;AAED,kDAAkD;AAClD,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAS7G","sourcesContent":["/**\n * Host-wide file API — browse, download, upload, mkdir.\n *\n * The dashboard is a trusted-operator surface: a paired device\n * already equals terminal access, so there is no project jail. Path handling\n * still canonicalizes and rejects confusion tricks so the *API* cannot be\n * abused: percent-decode checks, null-byte rejection, symlink resolution to a\n * real absolute path, and server-side logging of every operation.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { access, link, mkdir, open, readdir, realpath, rename, stat, unlink } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, normalize, resolve, sep } from \"node:path\";\nimport type { Writable } from \"node:stream\";\nimport type { DirListingDto, FileEntryDto } from \"../shared/protocol.js\";\n\nexport type FileOpLogger = (operation: string, path: string, detail?: string) => void;\n\nfunction assertValidChildName(name: string, label: string): void {\n\tif (!name || name.includes(\"/\") || name.includes(\"\\\\\") || name.includes(\"\\0\") || name === \".\" || name === \"..\") {\n\t\tthrow Object.assign(new Error(`Invalid ${label}: ${name}`), { status: 400 });\n\t}\n}\n\n/**\n * Canonicalize a client-supplied path. Throws (status 400) on anything\n * suspicious rather than guessing. Returns the resolved absolute path with\n * symlinks in the *parent* chain resolved (the leaf may not exist yet for\n * writes, so its parent is what gets realpath'd).\n */\nexport async function canonicalizePath(raw: string, opts: { mustExist: boolean }): Promise<string> {\n\tif (typeof raw !== \"string\" || raw.length === 0) {\n\t\tthrow Object.assign(new Error(\"Path is required\"), { status: 400 });\n\t}\n\tif (raw.includes(\"\\0\")) {\n\t\tthrow Object.assign(new Error(\"Path contains a null byte\"), { status: 400 });\n\t}\n\t// Reject lingering percent-encodings that survived normal URL decoding —\n\t// double-encoding is a classic canonicalization-confusion vector.\n\tif (/%2e|%2f|%5c|%00/i.test(raw)) {\n\t\tthrow Object.assign(new Error(\"Path contains percent-encoded traversal sequences\"), { status: 400 });\n\t}\n\tif (!isAbsolute(raw)) {\n\t\tthrow Object.assign(new Error(\"Path must be absolute\"), { status: 400 });\n\t}\n\tconst normalized = normalize(raw);\n\n\tif (opts.mustExist) {\n\t\ttry {\n\t\t\treturn await realpath(normalized);\n\t\t} catch (err) {\n\t\t\tthrow Object.assign(new Error(`Path does not exist or is unreadable: ${normalized}`), {\n\t\t\t\tstatus: 404,\n\t\t\t\tcause: err,\n\t\t\t});\n\t\t}\n\t}\n\t// For creation targets: resolve the parent, keep the leaf name literal.\n\tconst parent = dirname(normalized);\n\tlet realParent: string;\n\ttry {\n\t\trealParent = await realpath(parent);\n\t} catch (err) {\n\t\tthrow Object.assign(new Error(`Parent directory does not exist: ${parent}`), { status: 404, cause: err });\n\t}\n\tconst leaf = normalized.slice(parent === sep ? 1 : parent.length + 1);\n\tif (!leaf || leaf.includes(sep) || leaf === \".\" || leaf === \"..\") {\n\t\tthrow Object.assign(new Error(`Invalid file name: ${leaf || \"(empty)\"}`), { status: 400 });\n\t}\n\treturn join(realParent, leaf);\n}\n\n/** Resolve and canonicalize an existing directory supplied by a Dashboard client. */\nexport async function resolveExistingDirectory(rawPath: string): Promise<string> {\n\tconst path = await canonicalizePath(rawPath, { mustExist: true });\n\tlet info: Awaited<ReturnType<typeof stat>>;\n\ttry {\n\t\tinfo = await stat(path);\n\t} catch (err) {\n\t\tthrow Object.assign(new Error(`Path does not exist or is unreadable: ${path}`), { status: 404, cause: err });\n\t}\n\tif (!info.isDirectory()) {\n\t\tthrow Object.assign(new Error(`Not a directory: ${path}`), { status: 400 });\n\t}\n\ttry {\n\t\tawait access(path, constants.R_OK | constants.X_OK);\n\t} catch (err) {\n\t\tthrow Object.assign(new Error(`Directory is not readable and searchable: ${path}`), {\n\t\t\tstatus: 403,\n\t\t\tcause: err,\n\t\t});\n\t}\n\treturn path;\n}\n\nexport class FileApi {\n\tconstructor(private readonly log: FileOpLogger) {}\n\n\t/** Resolve an existing directory for listing and context-trust RPC operations. */\n\tasync resolveDirectory(rawPath: string): Promise<string> {\n\t\treturn resolveExistingDirectory(rawPath);\n\t}\n\n\tasync list(rawPath: string): Promise<Omit<DirListingDto, \"contextTrust\">> {\n\t\tconst path = await this.resolveDirectory(rawPath);\n\t\tconst names = await readdir(path, { withFileTypes: true });\n\t\tconst entries: FileEntryDto[] = [];\n\t\tfor (const dirent of names) {\n\t\t\tlet type: FileEntryDto[\"type\"] = \"other\";\n\t\t\tif (dirent.isDirectory()) type = \"dir\";\n\t\t\telse if (dirent.isFile()) type = \"file\";\n\t\t\telse if (dirent.isSymbolicLink()) type = \"symlink\";\n\t\t\tlet size = 0;\n\t\t\tlet modified = \"\";\n\t\t\ttry {\n\t\t\t\tconst s = await stat(join(path, dirent.name));\n\t\t\t\tsize = s.size;\n\t\t\t\tmodified = s.mtime.toISOString();\n\t\t\t\tif (type === \"symlink\") type = s.isDirectory() ? \"dir\" : \"file\";\n\t\t\t} catch {\n\t\t\t\t// Broken symlink or permission issue — keep the entry, mark it \"other\".\n\t\t\t\ttype = \"other\";\n\t\t\t}\n\t\t\tentries.push({ name: dirent.name, type, size, modified });\n\t\t}\n\t\tentries.sort((a, b) =>\n\t\t\t(a.type === \"dir\") === (b.type === \"dir\") ? a.name.localeCompare(b.name) : a.type === \"dir\" ? -1 : 1,\n\t\t);\n\t\tthis.log(\"list\", path);\n\t\treturn { path, entries };\n\t}\n\n\t/** Resolve a download target; returns the canonical path (must be a file). */\n\tasync resolveDownload(rawPath: string): Promise<{ path: string; size: number }> {\n\t\tconst path = await canonicalizePath(rawPath, { mustExist: true });\n\t\tconst info = await stat(path);\n\t\tif (!info.isFile()) {\n\t\t\tthrow Object.assign(new Error(`Not a file: ${path}`), { status: 400 });\n\t\t}\n\t\tthis.log(\"download\", path, `${info.size} bytes`);\n\t\treturn { path, size: info.size };\n\t}\n\n\t/**\n\t * Upload into a directory. Refuses to overwrite unless `overwrite` is set —\n\t * the collision surfaces as 409 so the client can prompt.\n\t */\n\tasync prepareUpload(\n\t\trawDir: string,\n\t\tfileName: string,\n\t\toverwrite: boolean,\n\t): Promise<{ path: string; stream: Writable; commit: () => Promise<void>; cleanup: () => Promise<void> }> {\n\t\tconst dir = await canonicalizePath(rawDir, { mustExist: true });\n\t\tconst dirInfo = await stat(dir);\n\t\tif (!dirInfo.isDirectory()) {\n\t\t\tthrow Object.assign(new Error(`Upload target is not a directory: ${dir}`), { status: 400 });\n\t\t}\n\t\tassertValidChildName(fileName, \"upload file name\");\n\t\tconst path = join(dir, fileName);\n\t\tlet exists = false;\n\t\ttry {\n\t\t\tawait stat(path);\n\t\t\texists = true;\n\t\t} catch {\n\t\t\texists = false;\n\t\t}\n\t\tif (exists && !overwrite) {\n\t\t\tthrow Object.assign(new Error(`File exists: ${path}`), { status: 409 });\n\t\t}\n\n\t\tconst tempPath = join(dir, `.dreb-upload-${process.pid}-${Date.now()}-${randomBytes(6).toString(\"hex\")}.tmp`);\n\t\tconst file = await open(tempPath, \"wx\");\n\t\tconst stream = file.createWriteStream({ autoClose: true });\n\t\tlet committed = false;\n\t\tconst cleanup = async () => {\n\t\t\tif (committed) return;\n\t\t\tawait unlink(tempPath).catch(() => {});\n\t\t};\n\t\tconst commit = async () => {\n\t\t\ttry {\n\t\t\t\tif (overwrite) {\n\t\t\t\t\tawait rename(tempPath, path);\n\t\t\t\t} else {\n\t\t\t\t\t// Atomic no-overwrite publish: hard-link into the final name and fail\n\t\t\t\t\t// with EEXIST if another writer won the race after the early stat().\n\t\t\t\t\tawait link(tempPath, path).catch((err: NodeJS.ErrnoException) => {\n\t\t\t\t\t\tif (err.code === \"EEXIST\") {\n\t\t\t\t\t\t\tthrow Object.assign(new Error(`File exists: ${path}`), { status: 409, cause: err });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t});\n\t\t\t\t\tawait unlink(tempPath);\n\t\t\t\t}\n\t\t\t\tcommitted = true;\n\t\t\t\tthis.log(\"upload\", path, exists ? \"overwrite\" : \"create\");\n\t\t\t} catch (err) {\n\t\t\t\tawait cleanup();\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t};\n\t\treturn { path, stream, commit, cleanup };\n\t}\n\n\tasync mkdir(rawDir: string, name: string): Promise<string> {\n\t\tassertValidChildName(name, \"folder name\");\n\t\tconst parent = await canonicalizePath(rawDir, { mustExist: true });\n\t\tconst path = join(parent, name);\n\t\tawait mkdir(path);\n\t\tthis.log(\"mkdir\", path);\n\t\treturn path;\n\t}\n}\n\n/** Places shown as shortcuts in the files tab. */\nexport function defaultPlaces(homeDir: string, projectRoots: string[]): Array<{ label: string; path: string }> {\n\tconst places = [\n\t\t{ label: \"home\", path: homeDir },\n\t\t{ label: \"/tmp\", path: resolve(\"/tmp\") },\n\t];\n\tfor (const root of projectRoots) {\n\t\tplaces.push({ label: root.split(sep).filter(Boolean).pop() ?? root, path: root });\n\t}\n\treturn places;\n}\n"]}
@@ -8,7 +8,8 @@
8
8
  * real absolute path, and server-side logging of every operation.
9
9
  */
10
10
  import { randomBytes } from "node:crypto";
11
- import { link, mkdir, open, readdir, realpath, rename, stat, unlink } from "node:fs/promises";
11
+ import { constants } from "node:fs";
12
+ import { access, link, mkdir, open, readdir, realpath, rename, stat, unlink } from "node:fs/promises";
12
13
  import { dirname, isAbsolute, join, normalize, resolve, sep } from "node:path";
13
14
  function assertValidChildName(name, label) {
14
15
  if (!name || name.includes("/") || name.includes("\\") || name.includes("\0") || name === "." || name === "..") {
@@ -63,6 +64,30 @@ export async function canonicalizePath(raw, opts) {
63
64
  }
64
65
  return join(realParent, leaf);
65
66
  }
67
+ /** Resolve and canonicalize an existing directory supplied by a Dashboard client. */
68
+ export async function resolveExistingDirectory(rawPath) {
69
+ const path = await canonicalizePath(rawPath, { mustExist: true });
70
+ let info;
71
+ try {
72
+ info = await stat(path);
73
+ }
74
+ catch (err) {
75
+ throw Object.assign(new Error(`Path does not exist or is unreadable: ${path}`), { status: 404, cause: err });
76
+ }
77
+ if (!info.isDirectory()) {
78
+ throw Object.assign(new Error(`Not a directory: ${path}`), { status: 400 });
79
+ }
80
+ try {
81
+ await access(path, constants.R_OK | constants.X_OK);
82
+ }
83
+ catch (err) {
84
+ throw Object.assign(new Error(`Directory is not readable and searchable: ${path}`), {
85
+ status: 403,
86
+ cause: err,
87
+ });
88
+ }
89
+ return path;
90
+ }
66
91
  export class FileApi {
67
92
  log;
68
93
  constructor(log) {
@@ -70,12 +95,7 @@ export class FileApi {
70
95
  }
71
96
  /** Resolve an existing directory for listing and context-trust RPC operations. */
72
97
  async resolveDirectory(rawPath) {
73
- const path = await canonicalizePath(rawPath, { mustExist: true });
74
- const info = await stat(path);
75
- if (!info.isDirectory()) {
76
- throw Object.assign(new Error(`Not a directory: ${path}`), { status: 400 });
77
- }
78
- return path;
98
+ return resolveExistingDirectory(rawPath);
79
99
  }
80
100
  async list(rawPath) {
81
101
  const path = await this.resolveDirectory(rawPath);
@@ -1 +1 @@
1
- {"version":3,"file":"files.js","sourceRo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ACxB,OAAO,IAAI,CAAC;IAAA,CACZ;CACD;AAED,kDAAkD;AAClD,MAAM,UAAU,aAAa,CAAC,OAAe,EAAE,YAAsB,EAA0C;IAC9G,MAAM,MAAM,GAAG;QACd,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE;QAChC,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE;KACxC,CAAC;IACF,KAAK,MAAM,IAAI,IAAI,YAAY,EAAE,CAAC;QACjC,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,IAAI,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IACnF,CAAC;IACD,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["/**\n * Host-wide file API — browse, download, upload, mkdir.\n *\n * The dashboard is a trusted-operator surface: a paired device\n * already equals terminal access, so there is no project jail. Path handling\n * still canonicalizes and rejects confusion tricks so the *API* cannot be\n * abused: percent-decode checks, null-byte rejection, symlink resolution to a\n * real absolute path, and server-side logging of every operation.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { link, mkdir, open, readdir, realpath, rename, stat, unlink } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, normalize, resolve, sep } from \"node:path\";\nimport type { Writable } from \"node:stream\";\nimport type { DirListingDto, FileEntryDto } from \"../shared/protocol.js\";\n\nexport type FileOpLogger = (operation: string, path: string, detail?: string) => void;\n\nfunction assertValidChildName(name: string, label: string): void {\n\tif (!name || name.includes(\"/\") || name.includes(\"\\\\\") || name.includes(\"\\0\") || name === \".\" || name === \"..\") {\n\t\tthrow Object.assign(new Error(`Invalid ${label}: ${name}`), { status: 400 });\n\t}\n}\n\n/**\n * Canonicalize a client-supplied path. Throws (status 400) on anything\n * suspicious rather than guessing. Returns the resolved absolute path with\n * symlinks in the *parent* chain resolved (the leaf may not exist yet for\n * writes, so its parent is what gets realpath'd).\n */\nexport async function canonicalizePath(raw: string, opts: { mustExist: boolean }): Promise<string> {\n\tif (typeof raw !== \"string\" || raw.length === 0) {\n\t\tthrow Object.assign(new Error(\"Path is required\"), { status: 400 });\n\t}\n\tif (raw.includes(\"\\0\")) {\n\t\tthrow Object.assign(new Error(\"Path contains a null byte\"), { status: 400 });\n\t}\n\t// Reject lingering percent-encodings that survived normal URL decoding —\n\t// double-encoding is a classic canonicalization-confusion vector.\n\tif (/%2e|%2f|%5c|%00/i.test(raw)) {\n\t\tthrow Object.assign(new Error(\"Path contains percent-encoded traversal sequences\"), { status: 400 });\n\t}\n\tif (!isAbsolute(raw)) {\n\t\tthrow Object.assign(new Error(\"Path must be absolute\"), { status: 400 });\n\t}\n\tconst normalized = normalize(raw);\n\n\tif (opts.mustExist) {\n\t\ttry {\n\t\t\treturn await realpath(normalized);\n\t\t} catch (err) {\n\t\t\tthrow Object.assign(new Error(`Path does not exist or is unreadable: ${normalized}`), {\n\t\t\t\tstatus: 404,\n\t\t\t\tcause: err,\n\t\t\t});\n\t\t}\n\t}\n\t// For creation targets: resolve the parent, keep the leaf name literal.\n\tconst parent = dirname(normalized);\n\tlet realParent: string;\n\ttry {\n\t\trealParent = await realpath(parent);\n\t} catch (err) {\n\t\tthrow Object.assign(new Error(`Parent directory does not exist: ${parent}`), { status: 404, cause: err });\n\t}\n\tconst leaf = normalized.slice(parent === sep ? 1 : parent.length + 1);\n\tif (!leaf || leaf.includes(sep) || leaf === \".\" || leaf === \"..\") {\n\t\tthrow Object.assign(new Error(`Invalid file name: ${leaf || \"(empty)\"}`), { status: 400 });\n\t}\n\treturn join(realParent, leaf);\n}\n\nexport class FileApi {\n\tconstructor(private readonly log: FileOpLogger) {}\n\n\t/** Resolve an existing directory for listing and context-trust RPC operations. */\n\tasync resolveDirectory(rawPath: string): Promise<string> {\n\t\tconst path = await canonicalizePath(rawPath, { mustExist: true });\n\t\tconst info = await stat(path);\n\t\tif (!info.isDirectory()) {\n\t\t\tthrow Object.assign(new Error(`Not a directory: ${path}`), { status: 400 });\n\t\t}\n\t\treturn path;\n\t}\n\n\tasync list(rawPath: string): Promise<Omit<DirListingDto, \"contextTrust\">> {\n\t\tconst path = await this.resolveDirectory(rawPath);\n\t\tconst names = await readdir(path, { withFileTypes: true });\n\t\tconst entries: FileEntryDto[] = [];\n\t\tfor (const dirent of names) {\n\t\t\tlet type: FileEntryDto[\"type\"] = \"other\";\n\t\t\tif (dirent.isDirectory()) type = \"dir\";\n\t\t\telse if (dirent.isFile()) type = \"file\";\n\t\t\telse if (dirent.isSymbolicLink()) type = \"symlink\";\n\t\t\tlet size = 0;\n\t\t\tlet modified = \"\";\n\t\t\ttry {\n\t\t\t\tconst s = await stat(join(path, dirent.name));\n\t\t\t\tsize = s.size;\n\t\t\t\tmodified = s.mtime.toISOString();\n\t\t\t\tif (type === \"symlink\") type = s.isDirectory() ? \"dir\" : \"file\";\n\t\t\t} catch {\n\t\t\t\t// Broken symlink or permission issue — keep the entry, mark it \"other\".\n\t\t\t\ttype = \"other\";\n\t\t\t}\n\t\t\tentries.push({ name: dirent.name, type, size, modified });\n\t\t}\n\t\tentries.sort((a, b) =>\n\t\t\t(a.type === \"dir\") === (b.type === \"dir\") ? a.name.localeCompare(b.name) : a.type === \"dir\" ? -1 : 1,\n\t\t);\n\t\tthis.log(\"list\", path);\n\t\treturn { path, entries };\n\t}\n\n\t/** Resolve a download target; returns the canonical path (must be a file). */\n\tasync resolveDownload(rawPath: string): Promise<{ path: string; size: number }> {\n\t\tconst path = await canonicalizePath(rawPath, { mustExist: true });\n\t\tconst info = await stat(path);\n\t\tif (!info.isFile()) {\n\t\t\tthrow Object.assign(new Error(`Not a file: ${path}`), { status: 400 });\n\t\t}\n\t\tthis.log(\"download\", path, `${info.size} bytes`);\n\t\treturn { path, size: info.size };\n\t}\n\n\t/**\n\t * Upload into a directory. Refuses to overwrite unless `overwrite` is set —\n\t * the collision surfaces as 409 so the client can prompt.\n\t */\n\tasync prepareUpload(\n\t\trawDir: string,\n\t\tfileName: string,\n\t\toverwrite: boolean,\n\t): Promise<{ path: string; stream: Writable; commit: () => Promise<void>; cleanup: () => Promise<void> }> {\n\t\tconst dir = await canonicalizePath(rawDir, { mustExist: true });\n\t\tconst dirInfo = await stat(dir);\n\t\tif (!dirInfo.isDirectory()) {\n\t\t\tthrow Object.assign(new Error(`Upload target is not a directory: ${dir}`), { status: 400 });\n\t\t}\n\t\tassertValidChildName(fileName, \"upload file name\");\n\t\tconst path = join(dir, fileName);\n\t\tlet exists = false;\n\t\ttry {\n\t\t\tawait stat(path);\n\t\t\texists = true;\n\t\t} catch {\n\t\t\texists = false;\n\t\t}\n\t\tif (exists && !overwrite) {\n\t\t\tthrow Object.assign(new Error(`File exists: ${path}`), { status: 409 });\n\t\t}\n\n\t\tconst tempPath = join(dir, `.dreb-upload-${process.pid}-${Date.now()}-${randomBytes(6).toString(\"hex\")}.tmp`);\n\t\tconst file = await open(tempPath, \"wx\");\n\t\tconst stream = file.createWriteStream({ autoClose: true });\n\t\tlet committed = false;\n\t\tconst cleanup = async () => {\n\t\t\tif (committed) return;\n\t\t\tawait unlink(tempPath).catch(() => {});\n\t\t};\n\t\tconst commit = async () => {\n\t\t\ttry {\n\t\t\t\tif (overwrite) {\n\t\t\t\t\tawait rename(tempPath, path);\n\t\t\t\t} else {\n\t\t\t\t\t// Atomic no-overwrite publish: hard-link into the final name and fail\n\t\t\t\t\t// with EEXIST if another writer won the race after the early stat().\n\t\t\t\t\tawait link(tempPath, path).catch((err: NodeJS.ErrnoException) => {\n\t\t\t\t\t\tif (err.code === \"EEXIST\") {\n\t\t\t\t\t\t\tthrow Object.assign(new Error(`File exists: ${path}`), { status: 409, cause: err });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t});\n\t\t\t\t\tawait unlink(tempPath);\n\t\t\t\t}\n\t\t\t\tcommitted = true;\n\t\t\t\tthis.log(\"upload\", path, exists ? \"overwrite\" : \"create\");\n\t\t\t} catch (err) {\n\t\t\t\tawait cleanup();\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t};\n\t\treturn { path, stream, commit, cleanup };\n\t}\n\n\tasync mkdir(rawDir: string, name: string): Promise<string> {\n\t\tassertValidChildName(name, \"folder name\");\n\t\tconst parent = await canonicalizePath(rawDir, { mustExist: true });\n\t\tconst path = join(parent, name);\n\t\tawait mkdir(path);\n\t\tthis.log(\"mkdir\", path);\n\t\treturn path;\n\t}\n}\n\n/** Places shown as shortcuts in the files tab. */\nexport function defaultPlaces(homeDir: string, projectRoots: string[]): Array<{ label: string; path: string }> {\n\tconst places = [\n\t\t{ label: \"home\", path: homeDir },\n\t\t{ label: \"/tmp\", path: resolve(\"/tmp\") },\n\t];\n\tfor (const root of projectRoots) {\n\t\tplaces.push({ label: root.split(sep).filter(Boolean).pop() ?? root, path: root });\n\t}\n\treturn places;\n}\n"]}
1
+ {"version":3,"file":"files.js","sourceRoot":"","sources":["../../src/server/files.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AACtG,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAM/E,SAAS,oBAAoB,CAAC,IAAY,EAAE,KAAa,EAAQ;IAChE,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ,C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AAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAChC,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC;QAClB,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QACxB,OAAO,IAAI,CAAC;IAAA,CACZ;CACD;AAED,kDAAkD;AAClD,MAAM,UAAU,aAAa,CAAC,OAAe,EAAE,YAAsB,EAA0C;IAC9G,MAAM,MAAM,GAAG;QACd,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE;QAChC,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE;KACxC,CAAC;IACF,KAAK,MAAM,IAAI,IAAI,YAAY,EAAE,CAAC;QACjC,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,IAAI,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IACnF,CAAC;IACD,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["/**\n * Host-wide file API — browse, download, upload, mkdir.\n *\n * The dashboard is a trusted-operator surface: a paired device\n * already equals terminal access, so there is no project jail. Path handling\n * still canonicalizes and rejects confusion tricks so the *API* cannot be\n * abused: percent-decode checks, null-byte rejection, symlink resolution to a\n * real absolute path, and server-side logging of every operation.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { access, link, mkdir, open, readdir, realpath, rename, stat, unlink } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, normalize, resolve, sep } from \"node:path\";\nimport type { Writable } from \"node:stream\";\nimport type { DirListingDto, FileEntryDto } from \"../shared/protocol.js\";\n\nexport type FileOpLogger = (operation: string, path: string, detail?: string) => void;\n\nfunction assertValidChildName(name: string, label: string): void {\n\tif (!name || name.includes(\"/\") || name.includes(\"\\\\\") || name.includes(\"\\0\") || name === \".\" || name === \"..\") {\n\t\tthrow Object.assign(new Error(`Invalid ${label}: ${name}`), { status: 400 });\n\t}\n}\n\n/**\n * Canonicalize a client-supplied path. Throws (status 400) on anything\n * suspicious rather than guessing. Returns the resolved absolute path with\n * symlinks in the *parent* chain resolved (the leaf may not exist yet for\n * writes, so its parent is what gets realpath'd).\n */\nexport async function canonicalizePath(raw: string, opts: { mustExist: boolean }): Promise<string> {\n\tif (typeof raw !== \"string\" || raw.length === 0) {\n\t\tthrow Object.assign(new Error(\"Path is required\"), { status: 400 });\n\t}\n\tif (raw.includes(\"\\0\")) {\n\t\tthrow Object.assign(new Error(\"Path contains a null byte\"), { status: 400 });\n\t}\n\t// Reject lingering percent-encodings that survived normal URL decoding —\n\t// double-encoding is a classic canonicalization-confusion vector.\n\tif (/%2e|%2f|%5c|%00/i.test(raw)) {\n\t\tthrow Object.assign(new Error(\"Path contains percent-encoded traversal sequences\"), { status: 400 });\n\t}\n\tif (!isAbsolute(raw)) {\n\t\tthrow Object.assign(new Error(\"Path must be absolute\"), { status: 400 });\n\t}\n\tconst normalized = normalize(raw);\n\n\tif (opts.mustExist) {\n\t\ttry {\n\t\t\treturn await realpath(normalized);\n\t\t} catch (err) {\n\t\t\tthrow Object.assign(new Error(`Path does not exist or is unreadable: ${normalized}`), {\n\t\t\t\tstatus: 404,\n\t\t\t\tcause: err,\n\t\t\t});\n\t\t}\n\t}\n\t// For creation targets: resolve the parent, keep the leaf name literal.\n\tconst parent = dirname(normalized);\n\tlet realParent: string;\n\ttry {\n\t\trealParent = await realpath(parent);\n\t} catch (err) {\n\t\tthrow Object.assign(new Error(`Parent directory does not exist: ${parent}`), { status: 404, cause: err });\n\t}\n\tconst leaf = normalized.slice(parent === sep ? 1 : parent.length + 1);\n\tif (!leaf || leaf.includes(sep) || leaf === \".\" || leaf === \"..\") {\n\t\tthrow Object.assign(new Error(`Invalid file name: ${leaf || \"(empty)\"}`), { status: 400 });\n\t}\n\treturn join(realParent, leaf);\n}\n\n/** Resolve and canonicalize an existing directory supplied by a Dashboard client. */\nexport async function resolveExistingDirectory(rawPath: string): Promise<string> {\n\tconst path = await canonicalizePath(rawPath, { mustExist: true });\n\tlet info: Awaited<ReturnType<typeof stat>>;\n\ttry {\n\t\tinfo = await stat(path);\n\t} catch (err) {\n\t\tthrow Object.assign(new Error(`Path does not exist or is unreadable: ${path}`), { status: 404, cause: err });\n\t}\n\tif (!info.isDirectory()) {\n\t\tthrow Object.assign(new Error(`Not a directory: ${path}`), { status: 400 });\n\t}\n\ttry {\n\t\tawait access(path, constants.R_OK | constants.X_OK);\n\t} catch (err) {\n\t\tthrow Object.assign(new Error(`Directory is not readable and searchable: ${path}`), {\n\t\t\tstatus: 403,\n\t\t\tcause: err,\n\t\t});\n\t}\n\treturn path;\n}\n\nexport class FileApi {\n\tconstructor(private readonly log: FileOpLogger) {}\n\n\t/** Resolve an existing directory for listing and context-trust RPC operations. */\n\tasync resolveDirectory(rawPath: string): Promise<string> {\n\t\treturn resolveExistingDirectory(rawPath);\n\t}\n\n\tasync list(rawPath: string): Promise<Omit<DirListingDto, \"contextTrust\">> {\n\t\tconst path = await this.resolveDirectory(rawPath);\n\t\tconst names = await readdir(path, { withFileTypes: true });\n\t\tconst entries: FileEntryDto[] = [];\n\t\tfor (const dirent of names) {\n\t\t\tlet type: FileEntryDto[\"type\"] = \"other\";\n\t\t\tif (dirent.isDirectory()) type = \"dir\";\n\t\t\telse if (dirent.isFile()) type = \"file\";\n\t\t\telse if (dirent.isSymbolicLink()) type = \"symlink\";\n\t\t\tlet size = 0;\n\t\t\tlet modified = \"\";\n\t\t\ttry {\n\t\t\t\tconst s = await stat(join(path, dirent.name));\n\t\t\t\tsize = s.size;\n\t\t\t\tmodified = s.mtime.toISOString();\n\t\t\t\tif (type === \"symlink\") type = s.isDirectory() ? \"dir\" : \"file\";\n\t\t\t} catch {\n\t\t\t\t// Broken symlink or permission issue — keep the entry, mark it \"other\".\n\t\t\t\ttype = \"other\";\n\t\t\t}\n\t\t\tentries.push({ name: dirent.name, type, size, modified });\n\t\t}\n\t\tentries.sort((a, b) =>\n\t\t\t(a.type === \"dir\") === (b.type === \"dir\") ? a.name.localeCompare(b.name) : a.type === \"dir\" ? -1 : 1,\n\t\t);\n\t\tthis.log(\"list\", path);\n\t\treturn { path, entries };\n\t}\n\n\t/** Resolve a download target; returns the canonical path (must be a file). */\n\tasync resolveDownload(rawPath: string): Promise<{ path: string; size: number }> {\n\t\tconst path = await canonicalizePath(rawPath, { mustExist: true });\n\t\tconst info = await stat(path);\n\t\tif (!info.isFile()) {\n\t\t\tthrow Object.assign(new Error(`Not a file: ${path}`), { status: 400 });\n\t\t}\n\t\tthis.log(\"download\", path, `${info.size} bytes`);\n\t\treturn { path, size: info.size };\n\t}\n\n\t/**\n\t * Upload into a directory. Refuses to overwrite unless `overwrite` is set —\n\t * the collision surfaces as 409 so the client can prompt.\n\t */\n\tasync prepareUpload(\n\t\trawDir: string,\n\t\tfileName: string,\n\t\toverwrite: boolean,\n\t): Promise<{ path: string; stream: Writable; commit: () => Promise<void>; cleanup: () => Promise<void> }> {\n\t\tconst dir = await canonicalizePath(rawDir, { mustExist: true });\n\t\tconst dirInfo = await stat(dir);\n\t\tif (!dirInfo.isDirectory()) {\n\t\t\tthrow Object.assign(new Error(`Upload target is not a directory: ${dir}`), { status: 400 });\n\t\t}\n\t\tassertValidChildName(fileName, \"upload file name\");\n\t\tconst path = join(dir, fileName);\n\t\tlet exists = false;\n\t\ttry {\n\t\t\tawait stat(path);\n\t\t\texists = true;\n\t\t} catch {\n\t\t\texists = false;\n\t\t}\n\t\tif (exists && !overwrite) {\n\t\t\tthrow Object.assign(new Error(`File exists: ${path}`), { status: 409 });\n\t\t}\n\n\t\tconst tempPath = join(dir, `.dreb-upload-${process.pid}-${Date.now()}-${randomBytes(6).toString(\"hex\")}.tmp`);\n\t\tconst file = await open(tempPath, \"wx\");\n\t\tconst stream = file.createWriteStream({ autoClose: true });\n\t\tlet committed = false;\n\t\tconst cleanup = async () => {\n\t\t\tif (committed) return;\n\t\t\tawait unlink(tempPath).catch(() => {});\n\t\t};\n\t\tconst commit = async () => {\n\t\t\ttry {\n\t\t\t\tif (overwrite) {\n\t\t\t\t\tawait rename(tempPath, path);\n\t\t\t\t} else {\n\t\t\t\t\t// Atomic no-overwrite publish: hard-link into the final name and fail\n\t\t\t\t\t// with EEXIST if another writer won the race after the early stat().\n\t\t\t\t\tawait link(tempPath, path).catch((err: NodeJS.ErrnoException) => {\n\t\t\t\t\t\tif (err.code === \"EEXIST\") {\n\t\t\t\t\t\t\tthrow Object.assign(new Error(`File exists: ${path}`), { status: 409, cause: err });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t});\n\t\t\t\t\tawait unlink(tempPath);\n\t\t\t\t}\n\t\t\t\tcommitted = true;\n\t\t\t\tthis.log(\"upload\", path, exists ? \"overwrite\" : \"create\");\n\t\t\t} catch (err) {\n\t\t\t\tawait cleanup();\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t};\n\t\treturn { path, stream, commit, cleanup };\n\t}\n\n\tasync mkdir(rawDir: string, name: string): Promise<string> {\n\t\tassertValidChildName(name, \"folder name\");\n\t\tconst parent = await canonicalizePath(rawDir, { mustExist: true });\n\t\tconst path = join(parent, name);\n\t\tawait mkdir(path);\n\t\tthis.log(\"mkdir\", path);\n\t\treturn path;\n\t}\n}\n\n/** Places shown as shortcuts in the files tab. */\nexport function defaultPlaces(homeDir: string, projectRoots: string[]): Array<{ label: string; path: string }> {\n\tconst places = [\n\t\t{ label: \"home\", path: homeDir },\n\t\t{ label: \"/tmp\", path: resolve(\"/tmp\") },\n\t];\n\tfor (const root of projectRoots) {\n\t\tplaces.push({ label: root.split(sep).filter(Boolean).pop() ?? root, path: root });\n\t}\n\treturn places;\n}\n"]}